0

I am receiving an alert if I select an option after I have already selected one but not for the option I select first. Im not sure why I am not receiving an alert the first time I select an option. I know I haven't worded it well but its a tricky one to word! Here is my code :

HTML

<select id="button1" class="button" title="Button 1" onchange="getDropDownVal()">
  <option value="0">--Please choose an option for the first blank--</option>
  <option id="buttonText1_1" class="buttonText" value="1">Banana</option>
  <option id="buttonText1_2" class="buttonText" value="2">Apple</option>
  <option id="buttonText1_3" class="buttonText" value="3">Grape</option>
  <option id="buttonText1_4" class="buttonText" value="4">Peach</option>
  <option id="buttonText1_5" class="buttonText" value="5">Melon</option>
  <option id="buttonText1_6" class="buttonText" value="6">Pineapple</option>
</select>

JS

function getDropDownVal() {
  document.getElementById("button1").onchange = function() {
    alert(this.value);
    return false;
  }
}

Here is my code in a Fiddle but this doesn't seem to show an alert at all?

Thanks in advance.

Eddie
  • 390
  • 3
  • 13
  • 1
    The duplicate question covers your first problem. – Quentin Dec 19 '18 at 13:55
  • 1
    Your second problem is that you have a change handler which only adds a change handler. So you have to change it twice for it to actually *do* anything. Don't use HTML `onXXX` attributes. – Quentin Dec 19 '18 at 13:55
  • No need for `onChange` attribute. `document.getElementById("button1").onchange = function() { alert(this.value); return false; }` will work fine without function. – Najam Us Saqib Dec 19 '18 at 13:58
  • 1
    remove the function that covers the onchange it will work i mean remove getDropDownval, you are getting this error in console "getDropDownVal is not defined at HTMLSelectElement.onchange ((index):55)" – Harshit Pant Dec 19 '18 at 13:59
  • You can also remove the onchange="getDropDownVal()" from html code. That is also not required in this case. – Harshit Pant Dec 19 '18 at 14:06
  • @HarshitPant Thanks for looking at this, im a little confused with what you mean. What bits should I be removing/adding to make this work? How can I call this in the html tag without using onChange? – Eddie Dec 19 '18 at 14:08
  • 1
    ok in js: document.getElementById("button1").onchange = function() { alert(this.value); return false; } and in html remove the onchange, that's it. you will see it works. So the function that you defined is not required, so this takes the event onChange when the data under that id is changed. – Harshit Pant Dec 19 '18 at 14:12
  • Ahh thanks Harshit!:) – Eddie Dec 19 '18 at 14:14

0 Answers0