简体   繁体   中英

check if two values are meaningfully equal using === not working in javascript

I want to check if two values are meaningfully equal using javascript but it is not working when a button is clicked. Below is my attempt

jQuery(document).ready(function(){
  jQuery(':button').click(function () {
    if (this.id == 'click') {
        alert('this button was clicked');

        $('input[type=text]').blur(function(){
    $(this).val($.trim($(this).val()));
        });//trim white spaces

      var name = localStorage.getItem("inputName");

    if(document.getElementById('inputName').value === name ){

    alert('both values are equal'); //but it never gets executed when the two values are equal

}else {
      alert('not showing anything'); //always executing this line
    }

    }else {

    }
});
});

how can I execute the if block only when the two values are equal.

Try to get the value with .val() and check which type var name has

You can do normal comparison == for this task or do a checking parse to use === instead

CODE SNIPPET

 $('.click').on("click", function() { var input = $('#inputName').val(); var name = "hello"; if (input == name) { alert('both values are equal'); } else { alert('both are not equal'); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="click" id="click">Click</button> <input type=text id="inputName" /> 

if(some.value === name && other.value === eman ) {
  execute();
}

That doesn't solve any of the "listener" problems you may have, but that is how you require two conditions to be true (or more if you continue the pattern).

Also, || is for "or" conditions.

For specific cases I have used an "additive" solution where both conditions being true sets a variable to '2', just one condition being true setting that variable to 1, and none of the conditions being true sets that variable to 0. That helps when one and only one condition must be true...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM