0

i have this html code

  <select id="pa_color" class="" name="attribute_pa_color" 
   data-attribute_name="attribute_pa_color" data-show_option_none="yes">

<option value="">Choose an option</option>
<option value="blu" class="attached enabled">blu</option>
<option value="red" class="attached enabled">red</option>
  </select>

so i want to add a javascript code under this or before this and when i will select any option in dropdown it will show an alert with the option i selected

so i cannot edit this html i need just another javascript code that will detected change of this and will show alert

arpak
  • 133
  • 1
  • 10
  • 2
    Possible duplicate of [Get selected value in dropdown list using JavaScript?](http://stackoverflow.com/questions/1085801/get-selected-value-in-dropdown-list-using-javascript) – Mihai Alexandru-Ionut Apr 15 '17 at 18:27
  • @Alexandru-IonutMihai, actually, considering OP's chosen tags, they don't want to do it without jQuery. So it's not a duplicate of that question, but of this one: [jQuery get selected option value (not the text, but the attribute 'value')](http://stackoverflow.com/questions/13089944/jquery-get-selected-option-value-not-the-text-but-the-attribute-value) – tao Apr 15 '17 at 18:47

1 Answers1

1

This will do it (using jQuery):

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

$('#pa_color').on('change', function(){
   alert($(this).val());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="pa_color" class="" name="attribute_pa_color" 
   data-attribute_name="attribute_pa_color" data-show_option_none="yes">

<option value="">Choose an option</option>
<option value="blu" class="attached enabled">blu</option>
<option value="red" class="attached enabled">red</option>
  </select>

If you want to do it without jQuery:

document.getElementById("pa_color").onchange = function(e) { 
  alert(e.target.value)
};

Alternatively, you could just place onchange="alert(this.value)" on the <select> tag itself:

<select onchange="alert(this.value)">
  <option value="">Choose an option</option>
  <option value="blu">blu</option>
  <option value="red">red</option>
</select>
tao
  • 82,996
  • 16
  • 114
  • 150