Nag Nag - 7 months ago 72
Javascript Question

onclick event is not working with option tag in html?

I have a following html drop down menu with

Go
button, it is working fine for the first two option values selection first and then hitting
Go
button, but not working for other two option values, which are having onclick events, Please help me that how to work with onclick event in
<option>
tag so that I can execute respective alert messages. I need it should work in Google Chrome browser. Thanks in advance.

<html>
<head>
<script>
function third(){
alert("It is a third option event");
}
function fourth(){
alert("Fourth option value");
}
</script>
</head>
<form name="testform" id="testformid">
<select name="testdropdownmenu" >
<option value="" selected>Please Select</option>
<option value="https://www.w3schools.com">First Option</option>
<option value="https://www.google.co.in">Second Option</option>
<option onclick="third()">Third Option</option>
<option onclick="fourth()">Fourth Option</option>
</select>
<input type="button" name="go" value="Go" onClick="location=document.testform.testdropdownmenu.options
[document.testform.testdropdownmenu.selectedIndex].value;">
</form>
</html>

Answer

Jquery

$(function(){
  $('#testdropdownmenu').on('change', function(){
  var val = $(this).val();
  if(val === 'third') {
    alert('third option') 
  }
  else if(val === 'fourth') {
    alert('fourth option') 
  }
  })
  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form name="testform" id="testformid">
<select name="testdropdownmenu" id="testdropdownmenu">
<option value="" selected>Please Select</option>
<option value="https://www.w3schools.com">First Option</option>
<option value="https://www.google.co.in">Second Option</option>
<option value="third">Third Option</option>
<option value="fourth">Fourth Option</option>
</select>
<input type="button" name="go" value="Go" onClick="location=document.testform.testdropdownmenu.options
[document.testform.testdropdownmenu.selectedIndex].value;">
</form>

JavaScript

function checkval() {
  var val = document.getElementById('testdropdownmenu').value 
  alert(val);
}
    <form name="testform" id="testformid">
    <select name="testdropdownmenu" id="testdropdownmenu"onchange="checkval()">
    <option value="" selected>Please Select</option>
    <option value="https://www.w3schools.com">First Option</option>
    <option value="https://www.google.co.in">Second Option</option>
    <option value="third">Third Option</option>
    <option value="fourth">Fourth Option</option>
    </select>
    <input type="button" name="go" value="Go" onClick="location=document.testform.testdropdownmenu.options
    [document.testform.testdropdownmenu.selectedIndex].value;">
    </form>

Use the onchange event on select and then compare its value.