0

How do I add the title attribute value "not selected" if the checkbox is unchecked?

This is what I tried so far, https://jsfiddle.net/5qakegrz/2/

<input type=checkbox class="fnPress" checked>1
<input type=checkbox class="fnPress">1

<script>
$(function(){
    $('input.fnPress:checked').attr("title", "selected"); 
    $('input.fnPress').change(function(){
        if($(this).is(":checked")) {
            $(this).attr("title", "selected");
        } else {
            $(this).removeAttr("title");
        }
    }); 
});

</script>
1
  • change $(this).removeAttr("title"); to $(this).attr("title", "not selected"); Commented Sep 20, 2018 at 8:23

2 Answers 2

1

To achieve this first we can add title not selected on all checkboxes and then for selected one we can update it to selected. In change callback function we will add title selected if it is checked and if it is unchecked the title would be not selected. see below code.

$(function(){
    $('input.fnPress').attr("title", "not selected"); 
    $('input.fnPress:checked').attr("title", "selected"); 
    $('input.fnPress').change(function(){
        if($(this).is(":checked")) {
            $(this).attr("title", "selected");
        } else {
            $(this).attr("title", "not selected");
        }
    }); 
});
<input type=checkbox class="fnPress" checked>1
<input type=checkbox class="fnPress">1

Sign up to request clarification or add additional context in comments.

Comments

1
$(function() {
  var // cache selector so we don't keep scanning the DOM over and over
    $inputs = $('input.fnPress'),
    // use a function to update the "title" attribute
    update_title = function(elements) {
      // iterate over the elements given as argument
      elements.each(function() {
        // cache the element so we save one DOM scanning
        var $this = $(this);

        // change the title attribute depending on the checkbox's state
        $this.attr(
          'title',
          $this.prop('checked') ? 'selected' : 'not selected'
        );
      });
    };

  // call the function on change
  $inputs.on('change', function() {
    update_title($inputs);
  });

  // start by setting the title attributes
  update_title($inputs);
});

1 Comment

Thank you for with detail comments. very helpful :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.