How to compare 2 elements with same getElementById(x)?

Discussion in 'Javascript' started by vadymus@gmail.com, Dec 22, 2005.

  1. Guest

    Hello,
    I need to compare 2 id names but not their values. For example:

    document.getElementById(i) == document.getElementById(j)

    these elements above seem to give error or do not work.
    My original statement is this (and note, when I add line above to it,
    that does not work):

    function uniqueValues(){
    var myForm = document.add2db;
    var iMax = myForm.imax.value;
    //var IsSimilar, IsSame;
    for (i=0;i<iMax;i++)
    {

    var fieldValue=document.getElementById(i).value;
    alert("id is "+document.getElementById(i));
    for(j=0;j<iMax;j++)
    {
    var fieldValue2=document.getElementById(j).value;
    if ((fieldValue == fieldValue2) && (document.getElementById(i) !=
    document.getElementById(j))) { //FIX HERE
    alert("I am sorry, but these values are identical:
    "+document.getElementById(j).value);
    document.getElementById(j).focus();
    return false;
    }
    }
    }
    //return true;
    }
     
    , Dec 22, 2005
    #1
    1. Advertising

  2. Guest

    > I need to compare 2 id names but not their values. For example:
    > document.getElementById(i) == document.getElementById(j)


    Well, there's this method, .isEqualNode() but since IDs are supposed to
    be unique, in your case i==j should perfectly suffice.
     
    , Dec 22, 2005
    #2
    1. Advertising

  3. Lee Guest

    said:
    >
    >Hello,
    >I need to compare 2 id names but not their values. For example:
    >
    >document.getElementById(i) == document.getElementById(j)
    >
    >these elements above seem to give error or do not work.


    Maybe I'm missing something, but why don't you just compare
    the two id's? "if (i==j)". You should never have two elements
    with the same id.
     
    Lee, Dec 22, 2005
    #3
  4. Guest

    Thank you so much...
    I did finf .name but it did not work for me. Identical id's are not
    recognized (maybe I do smth wrong?):

    function uniqueValues(){
    var myForm = document.add2db;
    var iMax = myForm.imax.value;
    for (i=0;i<iMax;i++)
    {

    var fieldValue=document.getElementById(i).value;
    //alert("id is "+document.getElementById(i).name);
    for(j=0;j<iMax;j++)
    {
    var fieldValue2=document.getElementById(j).value;
    if ((fieldValue == fieldValue2) && (document.getElementById(i).name
    != document.getElementById(j).name)) { //FIX HERE
    alert("I am sorry, but these values are identical:
    "+document.getElementById(j).value);
    document.getElementById(j).focus();
    return false;
    }
    }
    }
    //return true;
    }



    I am going to try .isEqualNode() now
     
    , Dec 22, 2005
    #4
  5. Guest

    Lee, you are absolutely right i and j can be compared. I cannot believe
    it is more simple that I thought. However, my script does not catch
    identical values here still.

    I try to submit form with unique field values as below.
    - imax is the number of fields.
    - all unique field values are from textarea called texarea0, textarea1,
    .......texareaN (all together is imax)
    - these texarea fields have unique html IDs: 0, 1, 2, 3.....N

    Code below does not catch nonubique values eventhough there are no
    errors when run

    function uniqueValues(){
    var myForm = document.add2db;
    var iMax = myForm.imax.value;
    for (i=0;i<iMax;i++)
    {

    var fieldValue=document.getElementById(i).value;
    //alert("id is "+document.getElementById(i).name);
    for(j=0;j<iMax;j++)
    {
    var fieldValue2=document.getElementById(j).value;
    if ((fieldValue == fieldValue2) && (i!=j)) { //FIX
    HEREdocument.getElementById(i).name != document.getElementById(j).name
    alert("I am sorry, but these values are identical:
    "+document.getElementById(j).value);
    document.getElementById(j).focus();
    return false;
    }
    }
    }
    //return true;
    }
     
    , Dec 22, 2005
    #5
  6. Guest

    napisal(a):
    > Lee, you are absolutely right i and j can be compared. I cannot believe
    > it is more simple that I thought. However, my script does not catch
    > identical values here still.
    >
    > I try to submit form with unique field values as below.
    > - imax is the number of fields.
    > - all unique field values are from textarea called texarea0, textarea1,
    > .......texareaN (all together is imax)
    > - these texarea fields have unique html IDs: 0, 1, 2, 3.....N
    >
    > Code below does not catch nonubique values eventhough there are no
    > errors when run
    >
    > function uniqueValues(){
    > var myForm = document.add2db;
    > var iMax = myForm.imax.value;
    > for (i=0;i<iMax;i++)
    > {
    >
    > var fieldValue=document.getElementById(i).value;
    > //alert("id is "+document.getElementById(i).name);
    > for(j=0;j<iMax;j++)
    > {
    > var fieldValue2=document.getElementById(j).value;
    > if ((fieldValue == fieldValue2) && (i!=j)) { //FIX
    > HEREdocument.getElementById(i).name != document.getElementById(j).name
    > alert("I am sorry, but these values are identical:
    > "+document.getElementById(j).value);
    > document.getElementById(j).focus();
    > return false;
    > }
    > }
    > }
    > //return true;
    > }


    Not sure what's the problem now, but I see you're doing quite a few too
    many checks. That is, say, i=3, j=5, then j=3, i=5 will check the same.

    for (i=0; i < iMax-1 ; i++)...
    {
    ....
    for(j=i+1;j<iMax;j++)
    {
    ....
    if (fieldValue == fieldValue2)
    {

    then i will never be equal to j and still all pairs get checked.

    Maybe send a piece of HTML, possible that you're mishandling IDs there
    somehow.
     
    , Dec 23, 2005
    #6
  7. RobG Guest

    wrote:
    > Lee, you are absolutely right i and j can be compared. I cannot believe
    > it is more simple that I thought. However, my script does not catch
    > identical values here still.
    >
    > I try to submit form with unique field values as below.
    > - imax is the number of fields.
    > - all unique field values are from textarea called texarea0, textarea1,
    > .......texareaN (all together is imax)
    > - these texarea fields have unique html IDs: 0, 1, 2, 3.....N


    This indicates that your HTML is invalid. IDs can include numbers,
    but can't start with them.


    >
    > Code below does not catch nonubique values eventhough there are no
    > errors when run


    The following loops through all the elements of the form and barfs
    when the first duplicate value is reached:

    function uniqueValues()
    {
    var val, vals = {};
    var el, els = document.forms['add2db'].elements;

    for (var i=0, len=els.length; i<len; ++i){
    el = els;
    val = el.value
    if (vals[val]){
    alert('Already have ' + val);
    if (el.focus) el.focus();
    return;
    }
    vals[val] = val;
    }
    }


    [...]


    --
    Rob
     
    RobG, Dec 23, 2005
    #7
  8. Guest

    > val = el.value
    > if (vals[val]){ }
    > vals[val] = val;


    except if the user enters two zeros.

    vals[val] = true;
     
    , Dec 23, 2005
    #8
  9. wrote:

    >> val = el.value
    >> if (vals[val]){ }
    >> vals[val] = val;

    >
    > except if the user enters two zeros.
    >
    > vals[val] = true;


    What are you talking about? `vals' is a reference to an Object object.
    Property names as well as form controls' values are _string_ values:

    var vals = {"0": "0"}, val = "00";
    if (vals[val])
    {
    // will never be executed
    }

    One problem that remains, however, is that Object objects inherit
    properties from Object, so that test is not reliable; for retaining
    and those inherited property values and avoiding false positives, it
    is necessary to map form controls' values that correspond to those
    properties' names to unused property names; one may instead also use
    Object.prototype.hasOwnProperty() where supported.

    Please quote the minimum of what you are replying to and provide
    attribution of quoted material:

    <URL:http://jibbering.com/faq/faq_notes/pots1.html#ps1Post>
    <URL:http://www.safalra.com/special/googlegroupsreply/>


    PointedEars
     
    Thomas 'PointedEars' Lahn, Dec 23, 2005
    #9
  10. Guest

    Hello,
    The code offered by RobG returns "Already have 0" alert and exists. It
    does not find all similar values. Please, suggest something, if
    possible...

    function uniqueValues()
    {
    var val, vals = {};
    var el, els = document.forms['add2db'].elements;

    for (var i=0, len=els.length; i<len; ++i){
    el = els;
    val = el.value
    if (vals[val]){
    alert('Already have ' + val);
    if (el.focus) el.focus();
    return;
    }
    vals[val] = val;
    }
    }
     
    , Dec 23, 2005
    #10
  11. Guest

    Well, actually I was right, my version works except that it takes 5
    minutes to check 192 fields. Any suggestions to improve code below?

    function uniqueValues(){
    var myForm = document.add2db;
    var iMax = myForm.imax.value;
    for (i=0;i<iMax;i++)
    {

    var fieldValue=document.getElementById(i).value;
    //alert("id is "+document.getElementById(i).name);
    for(j=0;j<iMax;j++)
    {
    var fieldValue2=document.getElementById(j).value;
    if ((i!=j) && (fieldValue == fieldValue2)) { //FIX HERE
    alert("I am sorry, but these values are identical:
    "+document.getElementById(j).value);
    document.getElementById(j).focus();
    return false;
    }
    }
    }
    return true;
    }
     
    , Dec 23, 2005
    #11
  12. Jonas Raoni Guest

    escreveu:
    > Well, actually I was right, my version works except that it takes 5
    > minutes to check 192 fields. Any suggestions to improve code below?


    As another guy said, it isn't right to have a field's id starting with
    a number, so in the example bellow, I changed to t0, t1, t2...

    <form id="add2db">
    <input type="text" id="t0" value="0" />
    <input type="text" id="t1" value="1" />
    <input type="text" id="t2" value="2" />
    <input type="text" id="t3" value="3" />
    <input type="hidden" id="imax" value="4" />
    <input type="button" onclick="uniqueValues();" value="Test" />
    </form>

    <script type="text/javascript">
    function uniqueValues(){
    for(var f = document.forms.add2db, i = f.imax.value, j, o; i; )
    for(j = --i; j;)
    if(f["t" + i].value == (o = f["t" + --j]).value)
    return o.focus(), o.select(), alert("I am sorry, but the values are
    identical."), false;
    return true;
    }
    </script>

    I hope it will help...

    --
    Jonas Raoni Soares Silva
    http://www.jsfromhell.com
     
    Jonas Raoni, Dec 23, 2005
    #12
  13. wrote:

    > The code offered by RobG returns "Already have 0" alert and exists.
    > It does not find all similar values. Please, suggest something, if
    > possible...


    Gladly. Would you please quote what you reply to and provide
    attribution of quoted material?

    <URL:http://jibbering.com/faq/faq_notes/pots1.html#ps1Post>
    <URL:http://www.safalra.com/special/googlegroupsreply/>

    > function uniqueValues()
    > {
    > var val, vals = {};
    > var el, els = document.forms['add2db'].elements;
    >
    > for (var i=0, len=els.length; i<len; ++i){
    > el = els;
    > val = el.value
    > if (vals[val]){
    > alert('Already have ' + val);
    > if (el.focus) el.focus();
    > return;


    Remove that line to prevent the function from exiting. Remove other lines
    in that block if you do not need the respective feature.

    If the code is to find all equal or similar values, I suggest you use an
    Array for property value. Say you want to have an array of references of
    all equal values in the form, you could do

    var vals = {};
    for (var i = 0, len = els.length; i < len; ++i)
    {
    var el = els, val = el.value;
    if (vals[val])
    {
    vals[val].push(el);
    }
    else
    {
    // Creates a new Array object with the `el' reference as only
    // element and assigns a reference to that Array object to a
    // property of the Object object referred to by `vals';
    // use `new Array(...)' where Array literals are not supported.
    vals[val] = [el];
    }
    }

    vals["0"] would then be a reference to an Array object encapsulating a list
    of references to all form elements that have value "0". If instead you
    want to find all similar values, you would need to define what you consider
    to be similar first; then an appropriate hash function can provide for
    mapping the similar value to a property.

    Note that the inheritance caveat I mentioned before in
    news: would still apply.


    PointedEars
     
    Thomas 'PointedEars' Lahn, Dec 23, 2005
    #13
  14. RobG Guest

    Jonas Raoni wrote:

    [...]

    > <script type="text/javascript">
    > function uniqueValues(){
    > for(var f = document.forms.add2db, i = f.imax.value, j, o; i; )
    > for(j = --i; j;)
    > if(f["t" + i].value == (o = f["t" + --j]).value)
    > return o.focus(), o.select(), alert("I am sorry, but the values are
    > identical."), false;
    > return true;
    > }
    > </script>
    >
    > I hope it will help...


    But it's very inefficient, it will require n^2 checks to be performed
    (where n is the number of inputs to check).

    My first post simply stopped at the first match as designed. Thomas'
    final version likely suits the OP better.


    --
    Rob
     
    RobG, Dec 25, 2005
    #14
  15. RobG Guest

    Thomas 'PointedEars' Lahn wrote:

    [...]

    > var vals = {};
    > for (var i = 0, len = els.length; i < len; ++i)
    > {
    > var el = els, val = el.value;
    > if (vals[val])


    If there is a concern that vals[val] may be evaluated incorrectly, then:

    if (val in vals)


    will be better - it works with empty values too. I can't think why I
    didn't go that way in the first place.


    [...]


    --
    Rob
     
    RobG, Dec 25, 2005
    #15
  16. Guest

    RobG wrote:
    > Thomas 'PointedEars' Lahn wrote:
    >
    > If there is a concern that vals[val] may be evaluated incorrectly, then:
    >
    > if (val in vals)


    and if user enters 'constructor' in any field?

    var vals=new Object;
    alert('constructor' in vals);

    Tricky :)
     
    , Dec 25, 2005
    #16
  17. Jonas Raoni Guest

    RobG escreveu:
    > Jonas Raoni wrote:
    > > <script type="text/javascript">
    > > function uniqueValues(){
    > > :
    > > }
    > > </script>
    > > I hope it will help...

    > But it's very inefficient, it will require n^2 checks to be performed
    > (where n is the number of inputs to check).


    Hmm, it's not "n ^ 2", but n ^ 2 / 2 + n / 2 since it works this way:

    abcd
    abc
    ab
    a

    Your version do n ^ 2 loops, but due to the fact that the inner loop
    ("x in y") is done internally, i have no doubt that it will work faster
    than mine one =]

    Anyway, it wasn't my intention to make a better code, I just wanted to
    help that guy "Any suggestions to improve code below?"


    --
    Jonas Raoni Soares Silva
    http://www.jsfromhell.com
     
    Jonas Raoni, Dec 25, 2005
    #17
  18. RobG Guest

    wrote:
    > RobG wrote:
    >
    >>Thomas 'PointedEars' Lahn wrote:
    >>
    >>If there is a concern that vals[val] may be evaluated incorrectly, then:
    >>
    >> if (val in vals)

    >
    >
    > and if user enters 'constructor' in any field?
    >
    > var vals=new Object;
    > alert('constructor' in vals);


    Good point.

    >
    > Tricky :)


    But fixable:

    if (val in vals && 'string' == typeof vals[val]) {
    // ...
    }



    --
    Rob
     
    RobG, Dec 27, 2005
    #18
  19. RobG wrote:
    > Thomas 'PointedEars' Lahn wrote:
    >
    > [...]
    >
    >> var vals = {};
    >> for (var i = 0, len = els.length; i < len; ++i)
    >> {
    >> var el = els, val = el.value;
    >> if (vals[val])

    >
    > If there is a concern that vals[val] may be evaluated
    > incorrectly, then:
    >
    > if (val in vals)


    That wouldn't help as the in operator calls the object's [[HasProperty]]
    method, and if the object itself has no property with the given name the
    [[HasProperty]] method calls the [[HasProperty]] method of the object's
    prototype (and so on up the prototype chain). So a value with a name
    such as, for example, "toString" will collide with a function reference.

    Given that the next line of code calls a - push - method on whatever is
    referred to by - vals[val] -, a safer test might be:-

    if((vals[val])&(vals[val].push)){ ...

    - as then the Array nature of the objects assigned as properties of the
    object would be verified (assuming no prototype augmentation to provide
    an inherited property of Object that was an Array, and no introduction
    of - push - methods on other object types).

    The problem here is the oft-discussed reason that it is unwise to speak
    of javascript objects as 'HashTables' or 'associative arrays'; a
    javascript object is never 'empty'. If the property names used in such a
    context are to be truly arbitrary (as opposed to a known set where
    collisions with object prototype properties can be know not to be an
    issue) then the only real solution is a programmer-defined storage
    object that deals with naming issues internally.

    > will be better -


    Generally the binary - in - operator is of little value or use in
    javascript programming, testing the nature of the value returned with a
    property accessor in a way that reliably puts - undefined - on the
    'rejected' side of the test will invariably be more discriminating and
    reliable. (A big clue that this is the case may be found in the fact
    that VK is the _only_ individual to have proposed the use of the - in -
    operator in a general programming context; anything VK chooses may be
    regarded as highly suspect for no other reason).

    > it works with empty values too.

    <snip>

    I don't really understand what you mean here as objects may have
    properties named with any sequence of charters, including an empty
    string. I don't think I would encourage people to give object's
    properties named with the empty string because that would be an
    invitation to encounter implementation bugs, but properties named with
    empty sequences of characters are completely legal by ECMA 262.

    Richard.
     
    Richard Cornford, Dec 28, 2005
    #19
  20. Richard Cornford wrote:

    > The problem here is the oft-discussed reason that it is unwise to speak
    > of javascript objects as 'HashTables' or 'associative arrays'; a
    > javascript object is never 'empty'. If the property names used in such a
    > context are to be truly arbitrary (as opposed to a known set where
    > collisions with object prototype properties can be know not to be an
    > issue) then the only real solution is a programmer-defined storage
    > object that deals with naming issues internally.


    Maybe I was misunderstood; to ensure I am not: that "programmer-defined
    object that deals with naming issues internally" is one way to implement
    what I called "an appropriate hash function" that "can provide for mapping
    the similar value to a property." I was not, by all means, referring to
    objects as hash tables or associative arrays.


    PointedEars
     
    Thomas 'PointedEars' Lahn, Dec 28, 2005
    #20
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. YC
    Replies:
    1
    Views:
    4,856
    siva chelliah
    Aug 13, 2003
  2. weston
    Replies:
    19
    Views:
    236
  3. Phlip
    Replies:
    2
    Views:
    107
  4. Claudio Calboni
    Replies:
    4
    Views:
    266
  5. css-discuss.org

    algorithm to compare 3 array elements

    css-discuss.org, Sep 27, 2011, in forum: Javascript
    Replies:
    11
    Views:
    1,154
    Antony Scriven
    Sep 28, 2011
Loading...

Share This Page