0

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.

2
  • 5
    ElementById not ElementsById you used plural where singurlar is needed Commented May 30, 2017 at 11:55
  • it's Element not Elements.So change like this:- document.getElementById('selProvinces'); Commented May 30, 2017 at 11:56

2 Answers 2

1

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>
0

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
})

Not the answer you're looking for? Browse other questions tagged or ask your own question.