kavinder
kavinder

Reputation: 609

Want to call a different Javascript method each time a different option is selected from select box

I have a select box with two options as recent and popular, the requirement is, if I select recent then a call to back-end should go to get the respective response and same should happen for popular too. I have been through many questions asked here but could not find the exact answer I am looking for. My current code look like this

<select class="recentOrPopular" name="mostpopular">
<option value="recent">Recent</option>
<option value="popular">Popular</option>
</select>

This is the simple html with two options, and the JavaScript is :

if($('.recentOrPopular').val('recent')){
    this.myrecentFunction();
    }

$( ".recentOrPopular" ).change(function() {
    if($('.recentOrPopular').val('popular')){
        this.myPopularFunction();
    }
    if($('.recentOrPopular').val('recent')){
        this.myrecentFunction();
    }
});

so by default myrecentFunction is getting called initially, but if I am changing the option then both of the if blocks are getting called. the link to sme kind of fiddle is : here

Upvotes: 1

Views: 69

Answers (4)

Arun P Johny
Arun P Johny

Reputation: 388316

you are setting the value using the .val(value) instead of reading it comparing

$(".recentOrPopular").change(function () {
    var value = $(this).val();
    if (value == 'popular') {
        this.myPopularFunction();
    } else if (value == 'recent') {
        this.myrecentFunction();
    }
});

using switch

$(".recentOrPopular").change(function () {
    var value = $(this).val();
    switch (value) {
        case 'popular':
            this.myPopularFunction();
            break;
        case 'recent':
            this.myrecentFunction();
            break;
    }
});

Upvotes: 2

iJade
iJade

Reputation: 23801

Modify your code as

 $( ".recentOrPopular" ).change(function() {
    if($('.recentOrPopular').val()=='popular'){
        this.myPopularFunction();
    }
    if($('.recentOrPopular').val()=='recent'){
        this.myrecentFunction();
    }
});

Upvotes: 0

Sumit Gupta
Sumit Gupta

Reputation: 2192

$('.recentOrPopular').val('popular')

is use to SET the value, if you want to compare them use

if($('.recentOrPopular').val() == 'popular')

also, instead of having if() and then if() use if ... else if() this ensure that if first condition meet, second won't execute.

Upvotes: 2

Voonic
Voonic

Reputation: 4775

<select class="recentOrPopular" name="mostpopular" id="dropdownPName" >

pName = document.getElementById('dropdownPName');
var value = pName.options[pName.selectedIndex].value;
switch(value)
{
    case 'recent' : //call your function

    case 'popular' : // call your function

}

Upvotes: -1

Related Questions