Pawan Dongol
Pawan Dongol

Reputation: 1158

if else condition in Ajax and Jquery not working

I am new in Ajax and JQuery and the simple requirement is to display a value as selected by the user using the number input field.

My code is as below:

<input type="text" id="number" />
<span id="display"></span>

<script type="text/javascript">
    $('#number').keyup(function (){
        if($('#number').text($(this).val())===1){
            $("#display").html("15,000");
        }
        else if('#number').text($(this).val())==2){
            $("#display").html("28,000");
        }
        else if('#number').text($(this).val())==3){
            $("#display").html("39,000");
        }
        else if('#number').text($(this).val())==4){
           $("#display").html("48,000");
        }
        else if('#number').text($(this).val())==5){
           $("#display").html("55,000");
        }
    });
</script>

Upvotes: 0

Views: 862

Answers (1)

Alexandr Lazarev
Alexandr Lazarev

Reputation: 12892

It has nothing to do with Ajax. Your syntax is not valid.

First of all, you have many statements with ommited bracket such as this statement:

else if('#number').text($(this).val())==2)

By adding a bracket in front of ('#number') the code is fixed.

But the condition of the if statement is not what we need. Such a statement checks if text() method returned true. This method sets the text contents of the matched elements. Obviously, you do not need to use it. All you need to do is check the value of the input. This can be done with the help of the val() method.

So, your code should look like:

$(function() {     
    $('#number').keyup(function (){
        if($(this).val() == 1){
            $("#display").html("15,000");
        }
        else if($(this).val() == 2){
            $("#display").html("28,000");
        }
        else if($(this).val() == 3){
            $("#display").html("39,000");
        }
        else if($(this).val() == 4){
            $("#display").html("48,000");
        }
        else if($(this).val() == 5){
            $("#display").html("55,000");
        }
    });
});

Fiddle: http://jsfiddle.net/82t86kqw/1/

As already mentioned in comments, such type of construction is usually performed using switch / case statements. Having to much if / else isn`t best practice.

Upvotes: 2

Related Questions