Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onclick event in HTML <select> not working Chrome and Safari

I have different JavaScript function associated with each option tag to toggle layers on/off in an OpenLayers map. It works fine Opera, Firefox and IE9, but not in Chrome and Safari. I read that I could use onchange on the select tag, but since I'm new to JavaScript, I don't really how it would call four different functions?

<select size="1" name="usgsfeed" id="usgsfeed">
<option value="usgs_hour" onclick="display_usgs_hour();">Past hour, all earthquakes</option>
<option value="usgs_day" onclick="display_usgs_day();" SELECTED>Past day, magnitude > 1</option>
<option value="usgs_week" onclick="display_usgs_week();">Past week, magnitude > 2.5</option>
<option value="usgs_month" onclick="display_usgs_month();">Past month, magnitude > 2.5</option>
<option value="none" onclick="display_none();">None</option>
</select>
like image 725
cba Avatar asked Jul 08 '12 11:07

cba


People also ask

Does Onclick work on any element?

The onclick attribute is part of the Event Attributes, and can be used on any HTML elements.

Does onclick event work on mobile?

Yes it will work. This has been answered here: Would onClick event work on touch on touch-screen devices?

Can you have multiple onclick events HTML?

So the answer is - yes you can :) However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty. Save this answer.


3 Answers

Call the function according to the select's value:

<select onchange="window['display_'+this.value]();">

If the value is "usgs_hour" the concatenation would be 'display_' + 'usgs_hour' === 'display_usgs_hour' and that function is called.

jsfiddle demo: http://jsfiddle.net/Ag3kh/

like image 77
Esailija Avatar answered Nov 15 '22 21:11

Esailija


use switch construction for selected value

$('#usgsfeed').change(function () {
    swith($(this).val()) {
    case 'usgs_hour':
        display_usgs_hour();
        break;.....
    }
})
like image 21
Andrey Vorobyev Avatar answered Nov 15 '22 21:11

Andrey Vorobyev


you should indeed use onchange!

To do this in javascript (not jquery) this would work:

JavaScript:

<script type='text/javascript'>

function SelectChanged()  {  
    if (document.aform.usgsfeed.value == "usgs_hour")  {
        alert("usgs_hour chosen");
    else if( ...etc) 
    }  
 }

</script>

HTML:

<form name="aform">
    <select size="1" name="usgsfeed" id="usgsfeed"  onchange='SelectChanged();>
        <option value="usgs_hour">Past hour, all earthquakes</option>
        <option value="usgs_day" SELECTED>Past day, magnitude > 1</option>
        <option value="usgs_week">Past week, magnitude > 2.5</option>
        <option value="usgs_month">Past month, magnitude > 2.5</option>
        <option value="none">None</option>
    </select>
</form>
like image 43
Sindre Avatar answered Nov 15 '22 19:11

Sindre