RicLeal
RicLeal

Reputation: 951

Form input onload substitute

I have the following code:

<input id="id_sf-0-use_incident_energy_guess" 
name="sf-0-use_incident_energy_guess" 
onchange="show_hide_guess(this.id);" 
onload="show_hide_guess(this.id);" 
type="checkbox">

The problem is the onload. It doesn't work in input fields...

I cannot use jquery $(document).ready because I don't know yet the id of this form... (this is a django formset and every generated form has a different prefix).

Do you know how I can sort this out?

Thanks in advance.

Upvotes: 0

Views: 401

Answers (2)

Thomas Weglinski
Thomas Weglinski

Reputation: 1094

I would use the immediate function to imitate the load event. You may try this:

<input id="id_sf-0-use_incident_energy_guess" 
    name="sf-0-use_incident_energy_guess" 
    onchange="show_hide_guess(this.id);" 
    type="checkbox">

<script>
    function show_hide_guess(id) {
        console.log("get: " + id);
        // your code goes here
    }

    (function(show_hide_guess) {        
        var i, inputs = document.getElementsByTagName('input'),
            len = inputs.length;
        for (i=0; i<len; i++) {
            var input = inputs[i],
                id = input.getAttribute("id");
            show_hide_guess(id);
        }

    })(show_hide_guess);
</script>

Note: You have to pass the show_hide_guess() method to the immediate function to get it work both on load and on change.

Upvotes: 1

ShankarSangoli
ShankarSangoli

Reputation: 69915

There is no load event on a input element. You can add a class to the input element and target it using css class selector.

Html

<input id="id_sf-0-use_incident_energy_guess" class="input-energy-guess"
  name="sf-0-use_incident_energy_guess" 
  onchange="show_hide_guess(this.id);"
  type="checkbox">

Js

$(function () {
    //Now you can access the input using class selector
    $('.input-energy-guess').each(function () {
       show_hide_guess(this.id);
    });
});

If you cannot add the class or modify the html then you can use the attribute ends with selector.

$(function () {
    $('name$=”use_incident_energy_guess”').each(function () {
       show_hide_guess(this.id);
    });
});

Upvotes: 3

Related Questions