473,396 Members | 1,987 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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

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 '05 #1
21 7895
> 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 '05 #2
<va*****@gmail.com> wrote in message
news:11*********************@o13g2000cwo.googlegro ups.com...
Hello,
I need to compare 2 id names but not their values. For example:

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


Try:

document.getElementById(i).name == document.getElementById(j).name
Dec 22 '05 #3
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 '05 #4
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 '05 #5

va*****@gmail.com 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 '05 #6
va*****@gmail.com 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[i];
val = el.value
if (vals[val]){
alert('Already have ' + val);
if (el.focus) el.focus();
return;
}
vals[val] = val;
}
}
[...]
--
Rob
Dec 23 '05 #7
> val = el.value
if (vals[val]){ }
vals[val] = val;


except if the user enters two zeros.

vals[val] = true;

Dec 23 '05 #8
bw****@gmail.com 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
Dec 23 '05 #9
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[i];
val = el.value
if (vals[val]){
alert('Already have ' + val);
if (el.focus) el.focus();
return;
}
vals[val] = val;
}
}

Dec 23 '05 #10
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 '05 #11
va*****@gmail.com 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

Dec 23 '05 #12
va*****@gmail.com 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[i];
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[i], 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:13****************@PointedEars.de would still apply.
PointedEars
Dec 23 '05 #13
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
Dec 25 '05 #14
Thomas 'PointedEars' Lahn wrote:

[...]
var vals = {};
for (var i = 0, len = els.length; i < len; ++i)
{
var el = els[i], 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
Dec 25 '05 #15

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 '05 #16
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

Dec 25 '05 #17
bw****@gmail.com 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
Dec 27 '05 #18
RobG wrote:
Thomas 'PointedEars' Lahn wrote:

[...]
var vals = {};
for (var i = 0, len = els.length; i < len; ++i)
{
var el = els[i], 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.
Dec 28 '05 #19
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
Dec 28 '05 #20
Richard Cornford wrote:
[...]
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 test would fail with JavaScript < 1.2 (NN < 4), JScript < 5.5 (IE < 5.5)
and ECMAScript < 3. A more reliable test would be

if (vals[val] && vals[val].constructor == Array)
{
// ...
}

since that would only fail with JavaScript < 1.1 (NN < 3) and JScript < 2.0
(IE < 4.0).

Of course, for the above versions without native Array.prototype.push()
support, one could augment the prototype before (with all side-effects of
user-defined properties):

if (typeof Array.prototype.push == "undefined")
{
Array.prototype.push = function Array_push()
{
for (var i = 0, len = arguments.length; i < len; i++)
{
this[this.length] = arguments[i];
}
}
}
PointedEars
Dec 28 '05 #21
Thank you all. I will try your suggestions when I get to my testing
area.
Happy holidays!!!

Dec 28 '05 #22

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
by: michael | last post by:
Is it possible to get all href URLs contained in a unordered list and place them in an array? Or in fact two different arrays, differently named one for each <ul> group? <ul> <li><a...
5
by: hibernate | last post by:
I'm somewhat new to javascript/DHTML, and this problem has been plaguing me. I have made an 'array' of <div> tags within my html document like so: <div id="menu"> menu1 </div> <div id="menu">...
22
by: Luke | last post by:
Elements with name attribute: form, input, textarea, a, frame, iframe, button, select, map, meta, applet, object, param, img (if you know more reply...) Methods of addresing html elements:...
122
by: Einar | last post by:
Hi, I wonder if there is a nice bit twiddling hack to compare a large number of variables? If you first store them in an array, you can do: for (i = 0; i < n; i++) { if (array != value) {...
3
by: Newcomsas | last post by:
Hello, I'm trying to solve a problem with JS textbox array without success. I have two buttons in my page: PLUS and MINUS; at every click on PLUS a new textbox named 'dear' is generated. So, if...
2
by: Noah Sussman | last post by:
Hello, I am writing a function to reposition an element based on whether one of its edges is outside the visible area of the browser window (the code is below). My client has asked for code...
11
by: balakrishnan.dinesh | last post by:
hi frnds, Im having two 20digit numbers, But while comparing those it is giiving wrong ouput in javascript. for example here is my code, my secanrio is , ~ If first 20 digit number is...
4
by: Claudio Calboni | last post by:
Hello folks, I'm having some performance issues with the client-side part of my application. Basically, it renders a huge HTML table (about 20'000 cells in my testing scenario), without content....
5
by: =?Utf-8?B?c2lwcHl1Y29ubg==?= | last post by:
Hi I have a Container that is an an Array List of Class Each ArrayList element can be the class or a another ArrayList of Class So there the ArrayList could look like Element 1 - Class...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.