How can I get IE Javascript to implement the 'this' keyword functionality?

Is there a workaround for Internet Explorer to implement the functionality offered by the 'this' javascript keyword to get the dom element that raised the event?

My problematic scenario: I have a variable number of text fields in an html form, for example

<input type="text" id="11"/>  
<input type="text" id="12"/>

      

..

I need to handle the "onchange" event for each text field, and the handling depends on the "id" of the field that triggered the event. So far, I understand my options are: 1) attach a dedicated event handler for each textbox. so if i have n fields i have n different functions, something like:

<input type="text" id="11" onchange="function11();"/>  
<input type="text" id="12" onchange="function12();"/>

      

but textboxes are added and removed dynamically, so it's better to use one common function.

2) use the 'this' keyword like:

<input type="text" id="11" onchange="functionGeneric(this);"/>  
<input type="text" id="12" onchange="functionGeneric(this);"/>

      

But this setting does not work with Internet Explorer.

Can anyone suggest a work-around to get it working in IE or some other solution that can be applied here? Thanks.

+2


source to share


2 answers


I cannot reproduce your problem. Here's the SSCCE , based on the latest information in the comments:

<!doctype html>
<html lang="en">
    <head>
        <title>SO question 2618458</title>
        <script>
            function functionGeneric(id) {
                alert(id); // Shows either 11 or 12 correctly.
            }
        </script>
    </head>
    <body>
        <input type="text" id="text_11" onchange="functionGeneric(this.id.split('_')[1]);"/>  
        <input type="text" id="text_12" onchange="functionGeneric(this.id.split('_')[1]);"/>
    </body>
</html>

      



It works great in all major browsers I have. Your real problem lies elsewhere. Until you come up with more detail or better, SSCCE, it shoots into the dark at the root cause.

+3


source


The second option probably doesn't work because element IDs must start with an alphabet or underscore (at least according to the spec).

I would choose something like this:



// make the ids start with a word, like "foo", followed by "_", followed by a number
$("input[id^='foo_']").change(function() {
    doSomething(this.id.split("_")[1]); // extract the number, pass to function
});

      

This will add a change handler to all of your inputs with IDs starting with 'foo' and dividing the number from the ID go to the generic function that works with the number.

+1


source







All Articles