kapitanluffy kapitanluffy - 2 months ago 13
Javascript Question

javascript onclick alert not working in chrome

<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 :(

Answer

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>
Comments