arpak
arpak

Reputation: 133

javascript get value of dropdown that is on same page

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

Upvotes: 0

Views: 560

Answers (1)

tao
tao

Reputation: 90028

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>

Upvotes: 1

Related Questions