rytis
rytis

Reputation: 2721

Assign onchange to an object and pass a parameter

So I have the following JavaScript:

<script language=JavaScript>
    function reload(form){
        var val=form.profile.options[form.profile.options.selectedIndex].value;
        self.location='?profile=' + val ;
    }
    function init(){
        var form = document.getElementById("myform");
        document.getElementById("id_profile").onchange = reload(form);
    }
    window.onload = init;
</script>

But then it keeps on reloading itself constantly. Which is expected. But how can I assign reload and pass a function instance to it?

I could do:

<script language=JavaScript>
    function reload(){
        var form = document.getElementById("myform");
        var val=form.profile.options[form.profile.options.selectedIndex].value;
        self.location='?profile=' + val ;
    }
    function init(){
        document.getElementById("id_profile").onchange = reload;
    }
    window.onload = init;
</script>

But what if I have more forms? Or I let say I want to reuse reload on multiple pages with different form names.

I would like to avoid setting onchange in the HTML tag though:

onchange="reload(this.form)"

If this is possible at all?

Thanks!

Upvotes: 2

Views: 3305

Answers (2)

user113716
user113716

Reputation: 322462

But what if I have more forms?

You can assign the same function to all the profile elements in the forms, and reference the element that received the change event inside the function using this.

<script type="text/javascript">
    function reload(){
        // In here, "this" is the element that received the event

        var val = this.options[ this.options.selectedIndex ].value;
        self.location='?profile=' + val ;
    }
    function init(){
        var len = document.forms.length;
        while( len-- ) {
            document.forms[ len ].profile.onchange = reload;
        }
    }
    window.onload = init;
</script>

Upvotes: 2

gen_Eric
gen_Eric

Reputation: 227200

You can make a function that returns a function (a closure) for the reload function.

function reload(form){
    return function(){
      var val=form.profile.options[form.profile.options.selectedIndex].value;
      self.location='?profile=' + val ;
    }
}
function init(){
    var form = document.getElementById("myform");
    document.getElementById("id_profile").onchange = reload(form);
}
window.onload = init;

Upvotes: 2

Related Questions