简体   繁体   中英

Select only one checkbox (and deselect rest) and show input field if checkbox selected

  1. I have a form with "Yes" and "No" as two checkboxes. These come in unselected at first. I'd like the user to only select one of these with the option to deselect their choice if they don't want to make a decision (which is why I didn't use radio buttons). Selecting Yes should deselect No and vice versa. I'm not sure how to do this. I'm using PHP (codeigniter), Javascript and JQuery.

  2. Secondly, after either Yes or No is selected, an input field needs to be displayed. I've got this setup but it toggles on the "onclick" action, which means selecting Yes twice shows and hides the input field! I want the input field to show if Yes or No are selected and disappear if the both Yes and No are unselected.

     $do_toggle = "onClick=\\"javascript:toggle('togglenote');\\""; echo form_radio('decision'.$key,'y',FALSE,$do_toggle)."Yes "; echo form_radio('decision'.$key,'n',FALSE,$do_toggle)."No"; echo form_input($mytext); // I put a div tag around the form_input above // but it's not showing in the StackOverflow question... // but it's there for the toggle to work.

Assuming your html is like this (i think it is):

<input type="checkbox" name="decisionY" value="y" /> Yes
<input type="checkbox" name="decisionN" value="N" /> Yes
<input type="text" id="togglenote" name="togglenote" />

Your js would be:

$(document).ready(function(){
  $(":checkbox[name^='decision']").change(function(){
     if($(this).is(":checked")){
        $(":checkbox[name[^='decision']").attr("checked", false); //Uncheck the other
        $(this).attr("checked", true);
        $("#togglenote").show();
     }
     if($(":checkbox[name^='decision']:checked").size() == 0){
        $("#togglenote").hide();
     }
  });
});

Hope this helps. Cheers.

This should do what you want:

$("#checkbox1").change(function() {

if ($(this).attr("checked") && $("#checkbox2").attr("checked")) {
   $("checkbox2").removeAttr("checked");
} else if ($(this).attr("checked")) {
   $("#inputfield").show();
} else {
   $("#inputfield").hide();
}
});


$("#checkbox2").change(function() {

if ($(this).attr("checked") && $("#checkbox1").attr("checked")) {
   $("checkbox1").removeAttr("checked");
} else if ($(this).attr("checked")) {
   $("#inputfield").show();
} else {
   $("#inputfield").hide();
}
});
  1. select one of them as jQuery or javascript
  2. Dont think that this is 100% garantee that some hacker can't set up both and post :)
  3. Analise $_REQUEST array against setted up both yes/no values
  4. Make decision.

PS. JQuery works not at my nokia 6303c :) device, hard coded - will work ... so application must have 2 parts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM