Comparison with 0 and JSLint error |
Comparison with 0 and JSLint error |
RainLover |
Jul 11 2014, 02:38 AM
Post
#1
|
Advanced Member Group: Members Posts: 216 Joined: 16-November 09 Member No.: 10,346 |
Here's the code:
CODE <input type="number" value="0" id="input"> <script> if (document.getElementById('input').value == 0) { alert('Hello, world!'); } </script> DEMO And here's the JSLint error: QUOTE Expected '===' and instead saw '=='. But when I listen to the advice and change == to ===, the alert stops appearing. This post has been edited by RainLover: Jul 11 2014, 02:39 AM |
Christian J |
Jul 11 2014, 04:34 AM
Post
#2
|
. Group: WDG Moderators Posts: 9,630 Joined: 10-August 06 Member No.: 7 |
The === operator compares both value and type, but IIRC the type of a form field value is always "string". This means that:
CODE if (document.getElementById('input').value === 0) can never be true, since it checks for the number zero. Instead, try using quotes: CODE if (document.getElementById('input').value === '0') which makes it into a string with the value zero. |
RainLover |
Jul 11 2014, 04:41 AM
Post
#3
|
Advanced Member Group: Members Posts: 216 Joined: 16-November 09 Member No.: 10,346 |
the type of a form field value is always "string". That's what I wanted to make sure about. Thanks! Am I right in my assumption that input.value == '0' is faster than input.value == 0 as the first one doesn't need a conversion? This post has been edited by RainLover: Jul 11 2014, 05:27 AM |
Christian J |
Jul 11 2014, 06:51 AM
Post
#4
|
. Group: WDG Moderators Posts: 9,630 Joined: 10-August 06 Member No.: 7 |
the type of a form field value is always "string". That's what I wanted to make sure about. Thanks! Can't remember any spec reference for it (despite discussing it here in several older threads), but you can test browsers with CODE alert(typeof formfield); QUOTE Am I right in my assumption that input.value == '0' is faster than input.value == 0 as the first one doesn't need a conversion? No idea, why not do a test on a large number of INPUT elements? For inspiration, here's another javascript speed test: http://quirksmode.org/dom/innerhtml.html |
Lo-Fi Version | Time is now: 29th March 2024 - 03:09 AM |