How to edit 'onchange' attribute in a 'select' tag? (using jquery)
I'm trying to edit the 'onchange' event of an existent 'select' element.
For example purposes I have the following code:
<select id="sel_id" onchange="javascript:foo();" >
and whenever I try to change its 'onchange' attribute I was using the following:
$("#sel_id").attr("onchange", "foo_2()");
FYI, this code which should be fine doesn't work, the 'onchange' attribute remains unchanged. So how should you edit it?
AMMENDMENT:
You can remove the attribute and then bind a different function like:
$("#sel_id").removeAttr("onchange").bind("change", function(){ foo_2(); });
but the issue remains, is it possible to change the 'onchange' attribute without removing it in the first plac开发者_高级运维e?
Not an exact answer to the question, but I'd probably remove the event using this:
document.getElementById('sel_id').onchange = undefined;
(as seen at How to Clear/Remove JavaScript Event Handler? )
and then go with this:
$('#sel_id').change(function() { foo_2(); });
Works for me if I use the native setAttribute()
.
Also, remember that you need quotes around the selector.
$("#sel_id")[0].setAttribute("onchange", "foo_2()");
Also remember to define foo_2
in the global namespace, and not inside jQuery's .ready()
function.
Use JQuery change function.
$('#sel_id').change(function() { //your code });
Here's a way to do it using just javascript:
<html>
<head>
<script type = "text/javascript" langauge="JavaScript">
function foo (){
alert("foo");
}
function fi() {
alert('fi');
}
</script>
</head>
<body>
<select id = "select_list" onchange="foo();">
<option value = "1">1</option>
<option value = "2">2</option>
</select>
<input type = "button" value = "change" onclick = "document.getElementById('select_list').onchange = fi;">
</body>
</html>
精彩评论