Skip to content
Advertisement

jQuery bind click event to button on each option of select element

I’m trying to make a click event on submit button on each option element of select.

Here is my script:

var selectObj = $("#selectObj");

selectObj.find("option").each(function(){
    selectObj.val($(this).val());
    $("#submitBtn").click();
});

But, it just work on the last option element.

Advertisement

Answer

But, it just work on the last option element.

I don’t know what you are trying to achieve, but your code should work.

Also not sure about the usage of selectObj.val($(this).val());

var selectObj = $("#selectObj");

selectObj.find("option").each(function(){
    //selectObj.val($(this).val());
    $("#submitBtn").click(myFunc($(this).val()));
});

function myFunc(val){
  console.log(val);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectObj">
  <option value="first">First</option>
  <option value="second">Second</option>
</select>

<button type="button" id="submitBtn" >Test</button>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement