getting an onclick event to a select option using js
26,280
Solution 1
I think you want to have your event handler on your select rather than on the option. See this fiddle for what I mean
<select size="10" name="syn_list" id="syn_list" class="span12" dir="rtl" style="text-align:right;" onchange="updateTxtContent();">
<option value="13">option a</option>
<option value="14">option b</option>
</select>
<script>
function updateTxtContent(){
alert($("#syn_list").val());
}
</script>
Or since it looks like you aren't using jQuery:
function updateTxtContent(){
var e = document.getElementById("syn_list");
var f = e.options[e.selectedIndex].value;
alert(f);
}
Solution 2
maybe try an onchange event in your select tag.
<select size="10" name="syn_list" id="syn_list" class="span12" dir="rtl" style="text-align:right;" onchange='updateTxtContext(this.value);'>
Author by
Vad.Gut
Updated on November 22, 2022Comments
-
Vad.Gut over 1 year
i am having a very frustrating problem. I have this code which filters out my results and inputs them into a select box
var syn = <?=json_encode($syn)?>; function filterByCity() { var e = document.getElementById("city_filter"); var city = e.options[e.selectedIndex].value; var selectOptions = document.getElementById('syn_list'); selectOptions.options.length = 0; for (i = 0; i < syn.length; i++) { if (city == syn[i]['city'] || city == 'all') { selectOptions.options[selectOptions.options.length] = new Option(syn[i]['name'], syn[i]['id'] + '" onclick="updateTxtContent(\'' + syn[i]['id'] + '\')'); } } }
as you might see i am adding a onclick listener to every select "option" which look great in the source code of the page itself but if i copy it into an edit i notice this my problem is that the "updateTxtContent()" function is not called.
<select size="10" name="syn_list" id="syn_list" class="span12" dir="rtl" style="text-align:right;"> <option value="13" onclick="updateTxtContent('13')">option a</option> <option value="14" onclick="updateTxtContent('14')">option b</option>
obviously there should be a better way to do this that i am not aware of.
-
Ian over 11 yearsYou could even pass
this
as a parameter to the function, and then just usethis.value
...just to avoid thegetElementById
-
Vad.Gut over 11 yearsyea well this does not really answer my question but it did make the entire thing work so thank you very much. you and MikeB
-
AaronC over 9 yearsthis worked for me when my 'id' was of the form 'flow.groupA01s[0].address'