0

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/

Code Junkie
  • 7,602
  • 26
  • 79
  • 141
  • Why do you need an `onclick` handler for `option`. Instead have a `onchange` handler on the select or incase if you need to handle on click, use `click` handler on select. – Selvakumar Arumugam Apr 17 '12 at 20:07
  • I need to handle the click event only when Add New Option has been selected. As stated below, onChange doesn't work in this case. I just tested the code with onClick in jsfiddle and it appears to work fine. I'm not sure why it doesn't work in my app yet. – Code Junkie Apr 17 '12 at 20:18

4 Answers4

3

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

Community
  • 1
  • 1
jorgebg
  • 6,560
  • 1
  • 22
  • 31
2

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");
    } 
});
Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148
1

Try

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

instead of:

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

See if that works?

Drakkainen
  • 1,142
  • 11
  • 25
0

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>
Intacto
  • 527
  • 3
  • 8