user3033194
user3033194

Reputation: 1821

If-else condition not executing correctly in Javascript

I hope the question is not too silly, but I am stuck with it and have tried may things. I have a dropdown in a table row which I am adding dynamically, and I am associating a change event with the dropdown. I have the following code here:

$(document).on("change", $('tr').find('select'), function(){

    if ($(this).val() == 0){
        $('#items_selected').text(1);
        alert("2nd time wrong");
    }else{
        alert("2nd time right");
        $('#items_selected').text(parseInt($('#items_selected').text()) + parseInt($(this).val()));
    }
});

Now, there is a checkbox, which when checked causes the dropdown (previously disabled) to become enabled.This fires the change event properly, executing the if condition in the code above. But when I change the value in the dropdown from the default value of 0 to something else, the event does fire, but again the if condition executes, not the else, which should now work. Is there something wrong with my event type (change), or are my datatypes (string/number) messed up, or is it something else? I tried parseInt() and other things but they didn't work. Can someone help please?

Upvotes: 0

Views: 73

Answers (2)

Quentin Roy
Quentin Roy

Reputation: 7887

In the present code you call on on $(document). As a result, in the event handler, this will be the document (even if you are actually looking at events happening on the dropdown).

You can try something like this:

$("#the-select").on("change", function(){
    // good practice: always use "==="
    if ($(this).val() === "0"){
        $('#items_selected').text(1);
        alert("2nd time wrong");
    }else{
        alert("2nd time right");
        $('#items_selected').text(parseInt($('#items_selected').text()) + parseInt($(this).val()));
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="the-select">
  <option>0</option>
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>

<div id="items_selected">0</div>

If you absolutely want to call on on $(document) (though I can't see why you would), then keep in mind that this won't be your dropdown. Put it in a variable in the upper scope, re-select it in the handler, or bind your handler to the dropdown.

Upvotes: 0

ssilas777
ssilas777

Reputation: 9804

You should check the select text value like $(this).find("option:selected").val()

Below code works:

$(document).on("change", $('tr').find('select'), function(){    
    if ($(this).find("option:selected").val() == 0){   
        alert($(this).find("option:selected").val());
    }else{
        alert($(this).find("option:selected").val());         
    }
});

Working FIDDLE

Upvotes: 1

Related Questions