简体   繁体   中英

How to trigger the onclick / onchange event for a already selected option clicks in javascript

I am trying to get option value of an already selected option in the select choice list. How can I make it possible. Here is my code snippet

 $(document).ready(function(){ $("#getCusineType").bind('click', function() { alert($(this).find('option:selected').val()); }); $("#getCusineType").bind('focusout', function() { alert($(this).find('option:selected').val()); }); function getCusineType(){ var getCusineType = $('#getCusineType').val(); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="getCusineType" onchange="getCusineType()"> <option value="1">Indian</option> <option value="2">American</option> <option value="3">Italian</option> <option value="4">General</option> </select> 

If you want to get selected option value :

var value=$("#getCusineType").val();

or text

var text=$("#getCusineType option:selected").text();

If you want to get the selected value after change event, you should bind a change event handler.

$("#getCusineType").change(function() {
   alert($(this).val());
})

 console.log("Value is: "+$('#getCusineType').val()); console.log("Text is: "+$("#getCusineType option:selected").text()); $("select").click(function() { console.log($(this).val()); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="getCusineType"> <option value="1">Indian</option> <option value="2">American</option> <option value="3">Italian</option> <option value="4">General</option> </select> 

simply way to trigger the on change event

 $(function(){
      $("#getCusineType").on('change', function(){
        alert($(this).val());
      }).trigger('change');
    });

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