简体   繁体   中英

Fire Jquery Event on Selection of Dropdown (Not Change of Dropdown Value)

Hi I have a jquery function which i want to fire when dropdown value is selected (not when it is clicked, and not when it is changed - but when any value is selected)

here is the html

<select class="addpropertyinput" name="property_availablefor" id="property_availablefor" required>
    <option value="">Available for</option>
    <option value="Rent">Rent</option>
    <option value="Sale">Sale</option>
</select>
<div class="errormsg" id="errormsg3"></div>

Jquery

var validate_property_availablefor = function()
{
    var item3 = $("#property_availablefor").val();
    $("#errormsg14").html("")
    $("#errormsg21").html("")
    if (item3 == '')
    {
        $("#errormsg3").html("Please Select Available For")
        property_availablefor = "";
    }
    else
    {
        $("#errormsg3").html("")
        property_availablefor = item3;
    }
}

   $("#property_availablefor").on('change', validate_property_availablefor);

Now I can replace 'change' with 'click' or 'focusout' but that does not solve problem perfectly, because then it fires as soon as it is clicked or focused out. I need to fire it when value is selected in dropdown. Not changed, not when dropdown is clicked. Only when the dropdown value is selected.

<option> events are not supported on all browsers (I've only confirmed it works on firefox). Keep your current change event, but also add a click event that responds only when the selection is blank:

 var validate_property_availablefor = function() { var item3 = $("#property_availablefor").val(); $("#errormsg14").html("") $("#errormsg21").html("") if (item3 == '') { $("#errormsg3").html("Please Select Available For") property_availablefor = ""; } else { $("#errormsg3").html("") property_availablefor = item3; } } $("#property_availablefor").on('change', validate_property_availablefor); $("#property_availablefor option").on('click', function(event){ var selectedVal = $(this).val(); console.log(selectedVal); if (selectedVal === '')//only do something when it's blank { $("#errormsg3").html("Please Select Available For") property_availablefor = ""; } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class="addpropertyinput" name="property_availablefor" id="property_availablefor" required> <option value="">Available for</option> <option value="Rent">Rent</option> <option value="Sale">Sale</option> </select> <div class="errormsg" id="errormsg3"></div> 

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