kp singh
kp singh

Reputation: 1460

load and click event on checkbox

I want to change the content of div on page load and on click according to checkbox state. i know i can place the if condition to ready function but I want to use the code once. is there any way to do this as below code is working fine for click event but not on the document load.

<input type="checkbox" id="a">
<div>change content</div>
<script>
$(function(){
  $('#a').on('load click', function(){
    if($(this).is(':checked'))
       $('div').html('new content');
  })
})
</script>

Upvotes: 2

Views: 1159

Answers (2)

Arko Elsenaar
Arko Elsenaar

Reputation: 1729

You could try something like this (untested):

$(function() {
    $("#a").on('click', function() {
        //code
    });
    $("#a").trigger('click');
});

Upvotes: 1

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196002

Use the change event and trigger it as well

$(function(){
  $('#a').on('change', function(){
    if($(this).is(':checked'))
       $('div').html('new content');
  }).trigger('change');
})

Upvotes: 4

Related Questions