Antony Star
Antony Star

Reputation: 37

jQuery automatically execute an event after the HTML document is loaded;

I want to execute onchange event on document's ready().

Original function is onchange=“fucntionname(parms)”

<select name="country" id="selCountries" onchange="region.changed(this, 1, 'selProvinces')">
    <option value="0">{$lang.please_select}{$name_of_region[0]}</option>
    <!-- {foreach from=$country_list item=country} -->
    <option value="{$country.region_id}" {if $consignee.country eq $country.region_id}selected{/if}>{$country.region_name}</option>
    <!-- {/foreach} -->
</select>

Javascript

<script type="text/javascript">
    $(document).ready(function(){
        var onll=document.getElementsById('selProvinces');
        region.changed(onll, 1, 'selProvinces');
    })
</script>

Error I am getting

document.getElementsById is not a function at HTMLDocument.

Upvotes: 0

Views: 74

Answers (2)

vijayP
vijayP

Reputation: 11512

If you already have jQuery with you then simply go with jQuery function. Those are easy to remember:

$(document).ready(function(){
    $("#selCountries").change();//this will execute whatever onchange already bounded to this element
})

Upvotes: 0

gavgrif
gavgrif

Reputation: 15509

As discussed there is the typo in the getElementById - but further to that - since you are using jQuery - you can separate the html and event handler to give cleaner code. It is always better to separate structure and function.

<select name="country" id="selCountries">
    <option value="0">{$lang.please_select}{$name_of_region[0]}</option>
    <!-- {foreach from=$country_list item=country} -->
    <option value="{$country.region_id}" {if $consignee.country eq $country.region_id}selected{/if}>{$country.region_name}</option>
    <!-- {/foreach} -->
</select>


//Javascript
<script>
    $(document).ready(function(){
        $('#selCountries').change(function(){
        var region=$(this).val();
        region.changed(region, 1, 'selProvinces');
       })
    })
</script>

Upvotes: 1

Related Questions