-3

I need to handle alert event on chosen option.

  <select>
       <option value="1">A</option>
       <option value="2">B</option>
       <option value="3">C</option>
       <option value="3">D</option>
   </select>

For ex., if I choose "B" option, I want alert like "Chosen option is: B", etc...

Thank you!

Dre
  • 35
  • 1
  • 4

2 Answers2

0

Try It Once Its Working .

function myFunction() {
    var x = document.getElementById("mySelect").value;
   alert('You Selected'+' '+x);
}
<p>Select a any value in list.</p>

<select id="mySelect" onchange="myFunction()">
  <option value="1">A
  <option value="2">B
  <option value="3">C
  <option value="4">D
</select>
S.R
  • 84
  • 6
  • `onchange="myFunction(this)"` using `function myFunction(sel) { alert('You Selected '+sel.value); }` is simpler - you do need to add value="..." to your options too – mplungjan Sep 08 '16 at 13:06
0

Working example: (It's a jQuery example, using selectors and events basically)

// Wait for DOM load
$(document).ready(function() {
  
  // Binding change event to the <select>
  $('#my_select').change(function() {
    
    // Saving the HTML corresponding to the value selected
    $selected = $('#my_select option:selected').text();;
    // Debugging actual selection DOM-node on console
    console.log($('#my_select option:selected'));
    // Showing the message
    alert("Chosen option is: " + $selected);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!-- I have set an ID to identify you select -->
<select id="my_select">
   <option value="1">A</option>
   <option value="2">B</option>
   <option value="3">C</option>
   <option value="3">D</option>
</select>

Some official jQuery's documentation links:

http://api.jquery.com/category/events/

http://api.jquery.com/category/selectors/

RPichioli
  • 3,245
  • 2
  • 25
  • 29