Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 place?

like image 870
vitorhsb Avatar asked Sep 03 '10 17:09

vitorhsb


People also ask

Can I use onChange in select tag?

The other difference is that the onchange event also works on <select> elements.

How do I use onChange in jQuery?

The change() method triggers the change event, or attaches a function to run when a change event occurs. Note: For select menus, the change event occurs when an option is selected. For text fields or text areas, the change event occurs when the field loses focus, after the content has been changed.

Is onChange an attribute?

The onchange attribute fires the moment when the value of the element is changed. Tip: This event is similar to the oninput event. The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus.


1 Answers

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(); });
like image 85
Justin Russell Avatar answered Sep 22 '22 15:09

Justin Russell