ThomasE
ThomasE

Reputation: 409

JQuery Dropdown Value

I have a dropdown that has a list of items, the first item has a value of 0, the other items a value greater than 0.

The following code is attached to the change event:

<script type="text/javascript">
    $("#SearchRegionId").change(function (e) {
        var select = $("#SearchKommuneId");
        select.empty();
        if ($("#SearchRegionId").val() != 0);
        {
            $.ajax({
                url: '/Kommune/getKommunerIRegion/',
                type: 'POST',
                data: { RegionId: $("#SearchRegionId").val() },
                dataType: 'json',
                success: function (data) {
                    for (i in data) {
                        select.append($('<option value="' + data[i].KommuneId + '">' + data[i].KommuneNavn + '</option>'));
                    }
                }
            });
        }
    });
</script>

My problem is that when I test to see if $("#SearchRegionId").val() != 0 it always comes out true even if the selected value is 0. I have showed the value in an alert box that shows the value 0, but something tells me that it is not really 0.

Upvotes: 0

Views: 101

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

You have a ; at the end of if

if ($("#SearchRegionId").val() != 0)

The ; at the end of ; means that the if condition is ended there and the code block after that will get executed irrespective of the value of the condition.

<script type="text/javascript">
    $("#SearchRegionId").change(function (e) {
        var select = $("#SearchKommuneId");
        select.empty();
        if ($("#SearchRegionId").val() != 0)
        {
            $.ajax({
                url: '/Kommune/getKommunerIRegion/',
                type: 'POST',
                data: { RegionId: $("#SearchRegionId").val() },
                dataType: 'json',
                success: function (data) {
                    for (i in data) {
                        select.append($('<option value="' + data[i].KommuneId + '">' + data[i].KommuneNavn + '</option>'));
                    }
                }
            });
        }
    });
</script>

Demo: Problem
Demo: Solution

Upvotes: 1

me123chan
me123chan

Reputation: 43

Why you write

select.empty();

after you assign the value, then you check it.....

It makes the

var select;

become empty, isn't it? That's what I think, same as roXon

Upvotes: 0

Related Questions