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?
The other difference is that the onchange event also works on <select> elements.
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.
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.
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(); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With