javascript onclick alert not working in chrome
27,107
Solution 1
use onchange instead of onclick for select lists.
<select name="history" id="history" onchange="historyChanged(this);">
<option value="history1">history 1</option>
<option value="history2">history 2</option>
<option value="clearhistory">Clear History</option>
</select>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
function historyChanged() {
var historySelectList = $('select#history');
var selectedValue = $('option:selected', historySelectList).val();
alert(selectedValue);
if (selectedValue == 'clearHistory') {
historySelectList.form.submit();
}
}
$(function() {
alert('my alert');
$('select#history').change(historyChanged);
});
</script>
Solution 2
If you want to use onClick
for option element in Chrome, IE, etc., you must use short fix: set onChange
attribute of select element to "this.options[this.selectedIndex].onclick()"
Solution 3
Use onChange on the select instead of each option. here is the jsfiddle http://jsfiddle.net/tBjkg/
<select name="history" id="history" onChange="alert(this.value);">
<option value="history1">history 1</option>
<option value="history2">history 2</option>
<option value="clearhistory">Clear History</option>
</select>
The alert(this.value) is referring to the value of the option within the select that is currently selected.
Author by
kapitanluffy
Updated on July 26, 2022Comments
-
kapitanluffy almost 2 years
<select name="history" id="history" > <option value="history 1" onClick="alert('h1');">history 1</option> <option value="history 2" onClick="alert('h2');">history 2</option> <option value="clearhistory" onClick="this.form.submit();" >Clear History</option> </select>
could someone help me with this script? i am expecting that whenever the user clicks history 1 ..it will alert h1 the script works in firefox and IE but not in Chrome :(
-
Hashid Hameed almost 10 yearsAwesome! This had been eating my head for hours now! Thanks alot!