Tsukimoto Mitsumasa
Tsukimoto Mitsumasa

Reputation: 582

How to determine if <option> tag is being clicked?

I have this,

<select id="rid" style="border: 1px solid #ccc;" name="rid">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
    <option value="4">Option 4</option>
    <option value="5">Option 5</option>
    <option value="6">Option 6</option>
</select>

In my script, I want to know if for instance Option 1 is being selected or being clicked. What I'm trying here is to know an option is being clicked via the <option>'s attribute value. If an option is being clicked I will alert() something telling me that that option is being clicked. How would I do that in my js script?

Upvotes: 0

Views: 92

Answers (3)

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60503

something like that

$('#rid').change(function() {
   alert($(this).val());
});

jsFiddle

or checking for specific value, even before onchange

$(document).ready(function() {
    var rid = $('#rid');
    alertForOne(rid.val());
    rid.change(function() {
        alertForOne(rid.val());
    });

});

function alertForOne(val) {
    if (val == 1)
    alert('test');
}

jsFiddle

Upvotes: 5

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

If you concerned about clicks and not change then use .click event.

$('#rid').click(function () {
   if ($(this).val() == "1") {
      console.log("option 1 was clicked");
     //^- Using alert here would block the selection.
   }
});

Above is based on what is in OP -

If an option is being clicked I will alert() something telling me that that option is being clicked.

As per -

I want to know if for instance Option 1 is being selected or being clicked.

Upvotes: 2

Adil
Adil

Reputation: 148150

Try this,

Live Demo

$('#rid').change(function(){
     alert($(this).val());
});

Upvotes: 4

Related Questions