简体   繁体   中英

How to prevent JQUERY change() function triggering when default select option selected

I would like to prevent my JQUERY change() function from triggering when the default select option is selected from the drop-down menu. However, I would like the function to trigger if any other option from the drop-down menu is selected.

In the example below Andorra is the default select option, so I would like the change() function to trigger when any other country is selected from the drop-down.

HTML

<select id="customer_country" name="customer_country"
class="validate[required] input_styling target"
style="background: #FFFFFF;">
                <option value="">Please Select a Country</option>
                <option value="Afghanistan">Afghanistan</option>
                <option value="Åland Islands">Åland Islands</option>
                <option value="Albania">Albania</option>
                <option value="Algeria">Algeria</option>
                <option value="American Samoa">American Samoa</option>
                <option value="Andorra" selected>Andorra</option>
...

</select>

JQUERY

$(document).ready(function(){
    // show popup when selecting a country from the drop-down
    $( ".target" ).change(function() {
        var docHeight = $(document).height(); //grab the height of the page
        var scrollTop = $(window).scrollTop(); //grab the px value from the top of the page to where you're scrolling
        $('.overlay-bg').show().css({'height' : docHeight}); //display your popup and set height to the page height
        $('.overlay-content').css({'top': scrollTop+20+'px'}); //set the content 20px from the window top
    });

Any help would be great.

Wrap the function in an if statement comparing the default value ("") to the selected value

  $( ".target" ).change(function() {
     if($(this).val() != "") {
        var docHeight = $(document).height();
        var scrollTop = $(window).scrollTop(); 
        $('.overlay-bg').show().css({'height' : docHeight}); 
        $('.overlay-content').css({'top': scrollTop+20+'px'});
     }
    });

Here is a JSFiddle if needed to help clarify (I simplified the .change() but you get the idea).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM