www.webdeveloper.com
Results 1 to 3 of 3

Thread: Newbie! Simple javscript code not working.

Hybrid View

  1. #1
    Join Date
    Jul 2013
    Posts
    1

    Newbie! Simple javscript code not working.

    I'm new to javascript. My code (in the head section) below is not working for some reason. I know the problem is in the line " if (lfckv == 'true') " . It says "NOT ticked" when I check or uncheck the checkbox.

    Code:
     <script>
                function exefunction(){
                    var lfckv = document.getElementById("lifecheck").checked;
                    if (lfckv == 'true')
    				{
    				alert("ticked");
    				}
    				else
    				{
    				alert("NOT ticked");
    			}
    			}
    				</script>
    My HTML code:

    HTML Code:
    <input type="checkbox" name="tag" value="tag"  id="lifecheck"  onclick="exefunction()"/> Tag this message

  2. #2
    Join Date
    Jun 2008
    Posts
    106
    You have 2 problems.
    1) You are trying to compare a boolean to a string when you should be comparing a boolean to another boolean.

    2) You're using the double equals operator (==), not the triple equals operator (===).
    The triple equals operator is better in 99% of cases. It does not do type coercion (Google it); it checks if the values are identical.

    Here are some examples to show why you shouldn't use == (aka, the eqeq operator).
    Code:
    true == 'true'     // false
    false == 'false'   // false
    false == 0       // true
    true == '1'        // true
    true == 1         // true
    null == undefined     // true




    So we simply change your if () statement in your code to compare .checked to a boolean and not a string, and we also use ===.
    Code:
    function exefunction() {
        var lfckv = document.getElementById("lifecheck").checked;
        if (lfckv === true) {
            alert('ticked');
        } else {
            alert('NOT ticked');
        }
    }
    Or, since you always call alert (just with a different string), you could shorten your function to this:
    Code:
    function exefunction() {
        alert((document.getElementById("lifecheck").checked === true ? 'NOT ' : '') + 'ticked');
    }
    That is using the ternary operator to shorten it to one line. No variables are necessary because we didn't use anything more than once.
    Last edited by tenfold; 07-31-2013 at 09:50 AM.

  3. #3
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,266
    Or , simply ?

    if (lfckv) alert('ticked'); else alert('NOT ticked');

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles