开发者

text change on jquery :ischecked

开发者 https://www.devze.com 2023-02-23 06:47 出处:网络
I am trying to build a function to change the text on checkbox selection, please check following... Jquery code

I am trying to build a function to change the text on checkbox selection, please check following...

Jquery code

$(document).ready(function() {
if($('#active').is(':checked')) {
    $('strong', '#status').text('Active');
}
else {
    $('strong', '#status').text('Inactive');
}
});

Html Form

 <span id="status"><input name="active" type="checkbox" value="1" id="active" />
<strong>Active</strong></span>

It works perfect when page loads, but if we change value of #active or we click #active it doesn't change text like active or inactive. thanks for help.开发者_运维技巧


Inside a doc ready block or just before the closing body tag you first need to attach a change handler to the element. You can then trigger the change event so that the text is correct when the page is rendered.

$(function(){

    function setDisplayText() {

      var displayText = this.checked ? 'Active' : 'Inactive';
      $('strong', '#status').text(displayText);

    }

    //setup change handler and then trigger 
    //it to ensure correct text on doc ready
    $('#active').change(setDisplayText)
                .trigger('change');

});


You need to attach an event listener to your checkbox.

$(document).ready(function() {

  function updateStatus() {
    if($('#active').is(':checked')) {
      $('strong', '#status').text('Active');
    }
    else {
      $('strong', '#status').text('Inactive');
    }
  }

  $('#active').bind('change', updateStatus);

  updateStatus();

});

Update - changed code to fire on document ready as well.


This is because you are not binding the code to the onchange event of the checkbox.

When the page loads, your code just checks whether the checkbox is checked or not because the code is bound to the onready event of the document object. After this it will not run the same code again

You can try this.

$('#active').bind('change', function() {
    if($('#active').is(':checked')) {
     $('strong', '#status').text('Active');
    }
    else {
     $('strong', '#status').text('Inactive');
    }    
});


Have you tired using the 'change' event handler?

It would look a little something like this:

$('#active').change(function(e)
{
  if($(this).is(':checked')) {
    $('strong', '#status').text('Active');
  }
  else {
    $('strong', '#status').text('Inactive');
  }
});


You can call a function onChange of checkbox :

<input name="active" type="checkbox" value="1" id="active" onchange="ChangeText();"/>

$(document).ready(function() { 
function ChangeText() {
if($('#active').is(':checked')) {
     $('strong', '#status').text('Active');
 } else {
     $('strong', '#status').text('Inactive'); 
} 
}
}); 

you can call the same function (ChangeText) on onload of body.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号