Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if selectbox is grabbed and get it's ID with Jquery

I am trying to see if any selectbox is grabbed, with jquery, then get it’s id from that, I have multiple boxes with the same name but a different id after, these are spawned via php. Ex. number1 eg. number + integer.

I would like to check/register an event where on click of any selectbox the id gets grabbed and put into a variable for later manipulation.

kind of like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if ($('select').clicked) {
    var sID = $('select').getID();
    // use id to see which selectbox has been clicked.
}

The above needs to happen dynamically eg. we don’t know the selectbox, so we need an event to check if ANY select has been clicked, then grab it’s ID.

I have around 20 selectboxes, and don’t want to make an individual check for them, as that takes up too much space, and more select boxes could come in the future.

P.S. is this even possible?

>Solution :

It’s actually quite easy with jQuery.
Use the on() method to attach a click handler on each select and grab the current clicked using $(this).

$(document).ready(function(){
  $('select').on('click',function(){
    console.log($(this).attr('id'));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<select id="s1">
  <option>1</option>
</select>
<select id="s2">
  <option>1</option>
</select>
<select id="s3">
  <option>1</option>
</select>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading