Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

javascript - Checkbox like radio button, limit to only one selection, uncheck if other checkbox is checked

The current js works fine, but at the moment it's possible to select multiple checkboxes. However, I want to limit only the selection to only one checkbox , so that checkboxes would behave like radio buttons - if one is checked the other one is unchecked, and that only one checkbox is allowed :

JS code:

/* * * * * * * * * * * * * * * * * *
* Show/hide fields conditionally
* * * * * * * * * * * * * * * * * */
(function($) {
$.fn.conditionize = function(options){ 
  
   var settings = $.extend({
      hideJS: true
  }, options );
  
  $.fn.showOrHide = function(listenTo, listenFor, $section) {
    if ($(listenTo).is('select, input[type=text]') && $(listenTo).val() == listenFor ) {
      $section.slideDown();
    }
    else if ($(listenTo + ":checked").val() == listenFor) {
      $section.slideDown();
    }
    else {
      $section.slideUp();
    }
  } 

  return this.each( function() {
    var listenTo = "[name=" + $(this).data('cond-option') + "]";
    var listenFor = $(this).data('cond-value');
    var $section = $(this);

    //Set up event listener
    $(listenTo).on('change', function() {
      $.fn.showOrHide(listenTo, listenFor, $section);
    });
    //If setting was chosen, hide everything first...
    if (settings.hideJS) {
      $(this).hide();
    }
    //Show based on current value on page load
    $.fn.showOrHide(listenTo, listenFor, $section);
  });
}
}(jQuery));

$('.conditional').conditionize();

and here is the html code:

<div id="demo">
  <h3>I'm interested in</h3>
  <label class="solo"><input type="radio" name="example1" value="private"><span></span>
    <span class="label-icon"><i class="fas fa-users"></i> Solo/Private Lessons</span>
  </label>
  <label class="group"><input type="radio" name="example1" value="group"><span></span>
    <span class="label-icon"><i class="fas fa-users"></i> Group Lessons</span>
  </label>
    <label class="workshop"><input type="radio" name="example1" value="workshop"><span></span>
      <span class="label-icon"><i class="fas fa-guitar"></i> Workshops and Clinics</span>
    </label>

  <div class="conditional" data-cond-option="example1" data-cond-value="private">
    <h4>Which instruments are you interested in learning?</h4>
    <label><input type="checkbox" name="guitar"><span></span> Guitar</label>
    <label><input type="checkbox" name="drums"><span></span> Drums</label>
      <label><input type="checkbox" name="violin"><span></span> Violin</label>
      <label><input type="checkbox" name="example3"><span></span> Bass</label>
      <label><input type="checkbox" name="example3"><span></span> Flute</label>
      <label><input type="checkbox" name="example3"><span></span> Saxophone</label>
      <label><input type="checkbox" name="example3"><span></span> Other</label>


      <div class="years-of-experience">
    <div class="conditional inline" data-cond-option="guitar" data-cond-value="on">
      <label><input type="text" size="4"> &nbsp; Years of experience in guitar</label>
    </div>
    <div class="conditional" data-cond-option="drums" data-cond-value="on">
      <label><input type="text" size="4"> &nbsp; Years of experience in drums</label>
    </div>
    <div class="conditional" data-cond-option="violin" data-cond-value="on">
      <label><input type="text" size="4"> &nbsp; Years of experience in violin</label>
    </div>
  </div>

      <div class="student-profile">
        <h4>Tell us a little more about yourself:</h4>
        <!-- Name -->
        <div>
          Student name<br>
            <input type="text" value="First"> <input type="text" value="Last">
        </div>
        <div>
          <label>Age<br>
            <span class="explanation">Currently accepting students 5+</span>
            <input type="text"></label>
        </div>
        <div>
          <label>Parent/guardian name
            <span class="explanation">If student is a minor</span>
             <input type="text" value="First"> <input type="text" value="Last">
        </div>
        <div>
          <label>Occupation
            <span class="explanation">If student, list school</span>
             <input type="text"></label>
        </div>
      </div><!-- /.student-profile -->
      <input type="submit" class="big-blue-button" value="Let's take a look at the class contract &rarr;">
  </div><!-- .solo-classes -->

  <div class="conditional" data-cond-option="example1" data-cond-value="group">
    <p>What kind of group lessons are you interested in?</p>
  </div>

  <div class="conditional" data-cond-option="example1" data-cond-value="workshop">
    <p>What kind of workshops are you interested in?</p>
  </div>

</div>
question from:https://stackoverflow.com/questions/65843093/checkbox-like-radio-button-limit-to-only-one-selection-uncheck-if-other-checkb

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I found only the following way

First: Add the attribute onClick with value check(this) to each of your checkboxes.

Second: Add following jquery function to your code:

function check(clickedObj)
{
  //Have you clicked checkbox checked or not?
  let checkboxState =$(clickedObj).prop( "checked" );
  //Find the container div and the find all containing checkboxes
  let checkboxes = $(clickedObj).parent().parent().find("input[type='checkbox']");
  //Loop through all foundend checkboxes and uncheck all
  $(checkboxes).each(function()
  {
    $(this).removeAttr("checked");
  })
  //Restore selected checkbox state in case you wanted to check it
  if (checkboxState == true) {
    $(clickedObj).prop("checked", true);
  }
}

According my jsfiddle it did work. Any ideas for improvements are welcome. :-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...