views:

335

answers:

2

just trying to test for equality in this piece of code, but getting a fail.

<input type="text" name="dave_blah"/>
<input type="text" name="dave_bleh"/>

I then access the name values of each of these inputs and assign them to two variables, name1 and name2. I then extract the first part of the name,delimited by a "_".

var oldName = name1.name.split('_',1);//dave
var thisName= name2.name.split('_',1);//dave
alert(oldName);
alert(thisName);
if(oldName !== thisName){//if "dave" is not equal to "dave"
alert("name difference = "+ oldName + " " + thisName);
}

Yet, when running this code, the message alerts regardless (I've tried != too). In principle, the alert shouldn't execute. It's quite late in the evening, so it's probably obvious, but can someone point this noob in the right direction? If I remove the not operator from the if statement - the function works as desired.

+2  A: 

OK. I've sussed the problem. The comparison was seeing the participants in the test both as Objects, as opposed to the string value of the contents. So, I solved it by casting the results to a string.

sunwukung
+4  A: 

thisName and oldName are both arrays, do something like this:

var oldName = name1.name.split('_',1)[0]; //dave
var thisName= name2.name.split('_',1)[0]; //dave

And I think it should work.

dylanfm
Yea, String.prototype.split returns an array.
seanmonstar
this worked too - easy to miss. I forgot it returns an array simply because I was only returning a single value, so it was validating true on the fact that they were both arrays (which is why typecasting worked). This is cleaner - script updated! Thanks for your help.
sunwukung