Code Junkie
Code Junkie

Reputation: 7788

jQuery click not working with select option in ie7/8

I'm using jQuery 1.7.1. The following code appends an additional option to my select menus that appends a .click event. This code works perfectly fine in firefox/ie9, but gives me the following error in ie7/8 when clicking on the Add New Option. I've tried the select event without any luck as well. Does anybody know how to make this work in legacy browsers like ie7/8

$("select").append($('<option></option>').text("Add New Option").click(function(){
    alert("test");
}));   

JS Error SCRIPT5022: Syntax error, unrecognized expression: # jquery-1.7.1.js, line 4179 character 2

JS Fiddle example

http://jsfiddle.net/gchristman/gucgG/3/

Upvotes: 0

Views: 1355

Answers (4)

Intacto
Intacto

Reputation: 557

for ie7/8 use javascript: JS fiddle

<select id="sel" onchange="test(this.value)"><option>option1</option></select>

<script language="javascript"><!--
//<![CDATA[
s=document.getElementById("sel");
var opt = document.createElement('option');
opt.value = "add";
opt.innerHTML = "Add New Option";
s.appendChild(opt);

function test(val){
    if (val = "add"){
        alert("test");
    }
}

//]]>
--></script>

Upvotes: 0

jorgebg
jorgebg

Reputation: 6600

You should use the onchange event. Try this instead:

$("select").append($('<option></option>').text("Add New Option")).change(function(){
    alert("test");
}));   

Related: Click event on select option element in chrome

Upvotes: 3

Mathew Thompson
Mathew Thompson

Reputation: 56429

Don't attach click events to options, just subscribe to the change event on the select and check if it's the item you added? I've gave your new item a value of 0 in order to identify it in the change.

$("select").append($('<option></option').text("Add New Option").val(0));

$("select").change(function () {
    if $("select option:selected").val() == 0) {
        alert("test");
    } 
});

Upvotes: 2

Drakkainen
Drakkainen

Reputation: 1142

Try

.on("click", function() {
    alert("test");
}));

instead of:

.click(function() {
    alert("test");
}));

See if that works?

Upvotes: 1

Related Questions