Home > Enterprise >  Check a radio button by default with jQuery
Check a radio button by default with jQuery

Time:02-25

in an html page that I use to display text snippets, I use jQuery to filter those that contain just text, text including some url links or both :

JS code :

$(document).ready(function() {
  $('input[type=radio]').attr('checked', false);
  $(".selection").on("change", ":radio", function() {
    var checkedVal = parseInt($(this).filter(":checked").val(), 10);
    $(".container").hide().filter(function() {
      if (checkedVal === 2) {
        return $(this).find('a[href]').length && $(this)
      } else if (checkedVal === 1) {
        return $(this).find('a[href]').length <= 0 && $(this)
      } else {
        return $(this)
      }
    }).show();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  </button> Display : <input type="radio" name="check" value="1" /> Texts only | <input type="radio" name="check" value="2" /> Texts w/ links | <input type="radio" name="check" value="-1" checked="checked" /> Texts   Texts w/ links</div>

I would like the "Texts Texts w/ links" button to be checked by default and this choice to be kept when the page is refreshed.

I don't know how to do this. Any help would be greatly appreciated, thank you.

CodePudding user response:

Instead of unchecking all the buttons, check the one you want to be the default.

$(document).ready(function() {
  $('.selection :radio[value=-1]').attr('checked', true);
  $(".selection").on("change", ":radio", function() {
    var checkedVal = parseInt($(".selection :radio:checked").val(), 10);
    $(".container").hide().filter(function() {
      if (checkedVal === 2) {
        return $(this).find('a[href]').length && $(this)
      } else if (checkedVal === 1) {
        return $(this).find('a[href]').length <= 0 && $(this)
      } else {
        return $(this)
      }
    }).show();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  </button> Display : <input type="radio" name="check" value="1" /> Texts only | <input type="radio" name="check" value="2" /> Texts w/ links | <input type="radio" name="check" value="-1" checked="checked" /> Texts   Texts w/ links</div>

  • Related