0

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.

11
  • 4
    jQuery(':button') is not valid. Did you mean jQuery('button')? Commented Apr 11, 2017 at 22:17
  • 2
    BTW === is used to check if something is identical, not necessarily meaningfully equal. Commented Apr 11, 2017 at 22:18
  • @AndrewLi but the if block is not executing Commented Apr 11, 2017 at 22:18
  • What do you get when you use == instead of ===? Commented Apr 11, 2017 at 22:19
  • 2
    If you log the values to the console, are they the same? console.log(document.getElementById('inputName').value, name); Commented Apr 11, 2017 at 22:20

2 Answers 2

1

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" />

Sign up to request clarification or add additional context in comments.

Comments

0
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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.