开发者

jQuery radio buttons - choose only one?

This is probably a stupidly simple question, but I'm stuck.

I had created a form with multiple checkboxes, and when the checkboxes were clicked, it would pass the values of each checkbox as a comma-separated list to a hidden input field. It worked a treat. but due to some issues, I now have to alter my code so that it uses radio buttons instead - so no comma-separated list of values, just one at a time.

I altered the code to swap it out to radio buttons, and it's working fine except for two things: 1) it's not switching between radio buttons (each time I select a button, it stays selected as I choose others) and 2) it's adding to the list instead of returning the single option selected. In other words, it's still acting like a checkbox, except visually, it's round and has a dot. LOL

This is my code thus far:

jQuery(document).ready(function($) {
        $(':radio').click(function() { 
          var radio = $(this);
          var text = $('input[name="cat"]');
          if(radio.is(':checked')) {
            text.val(text.val() + radio.val());
            //alert(text.val());
          } else {
            text.val(function() {  
                $(this).val().replace(radio.val(),"");
            });
          }
        });
    });

so when I uncomment that "alert" line, I can see what's passed, and it's just adding to the list instead of replacing with the new value. Anyone know how to fix the above so only one option can be selected and passed? (The above 开发者_运维知识库code works awesomely as a checkbox thing though. I actually think I got the above code from here somewhere, although I can't remember where!)

EDIT: here's the code that solved the issue and works a treat (thanks to you all :) ) - maybe it'll help someone else in the future.

`jQuery(document).ready(function($) {
        $(':radio').change(function() { 
          var radio = $(this);
          var text = $('input[name="cat"]');
          if(radio.is(':checked')) {
            text.val(radio.val());
            //alert(text.val());
          } else {
            text.val(function() {  
                $(this).val().replace(radio.val(),"");
            });
          }
        });
    });`


Radio buttons have to have the same name attribute. The id attribute can be different, but the same name attribute is what allows you to only select one at a time.


This is the simpler way to do the same thing: Assuming the radio group name = a

$("input[name='a']").change(function(){
    alert($(this).val());
});

For demo: http://jsfiddle.net/naveed_ahmad/AtrXw/


Well, you're setting the value of the "text" element to its current value plus the value of the selected radio button. To get rid of the previous radio button value, you'll have to either remove it based on some pattern, or else stash the original value of the text input somewhere so you can reconstruct it.

If your radio buttons don't act like radio buttons, it's because you didn't give them all the same name. That's how radio buttons work: among those that share a name, at most one can be selected at any time.


Your code cannot work with radio-boxes because it presumes that you click on a checkbox to uncheck it. In case of radio boxes, you don't have to click on a box to uncheck it, you simply select another radio-box, so the function that removes the value of the unchecked box from the hidden field is never called.

Of course you could modify your code to work with radio-boxes but I don' think this is necessary: It's the default behaviour of radio boxes to pass the value of the selected box to the server, so you don't have to copy its value to a hidden field.


I think this is what you want:

jQuery(document).ready(function($) {
    $(':radio').click(function() { 
      var radio = $(this);
      var text = $('input[name="cat"]');
      removeRadioValues()
      text.val(text.val()+radio.val());
    });
});
function removeRadioValues(){
    var tf = $('input[name="cat"]');
    var text = tf.val()
    $(':radio').each(function(){
        text = text.replace($(this).val(),'');
    });
    tf.val(text);
}


When you set the name html property same for all radios, then you can select only one. Following is an example that I used for setting the radio button and selecting the user selected value.

Reference

  1. When should I use the name attribute in HTML4/HTML5?
  2. Recommended jQuery templates for 2012?

CODE

   <script type="text/template" id="cardTemplate">
    <TR class=Normal>
        <TD style="WIDTH: 275px" align=left>
                <SPAN> LIJO </SPAN>
        </TD>
        <TD>
            <label><input type="radio" name="defaultScanOption" id= "defaultScanOptionCase" value="Case" checked>Case</label>
            <label><input type="radio" name="defaultScanOption" id= "defaultScanOptionWorkLot" value="WorkLot">WorkLot</label>
            <label><input type="radio" name="defaultScanOption" id= "defaultScanOptionCutLot" value="CutLot">CutLot</label>
            <label><input type="radio" name="defaultScanOption" id= "defaultScanOptionMoonrock" value="Moonrock">Moonrock</label>
        </TD>
     </TR>
   </script>

 $(document).ready(function () 
 {

        //Add Scan Type radio buttons as a table row  
        var cardTemplate = $("#cardTemplate").html();        
        $('#tblPlantParameters tr:last').after(cardTemplate);

        //When Scan Type radio button selection change, set value in hidden field
        $('input[name=defaultScanOption]:radio').change(function()
        {
            var selectedOptionValue = $(this).val();
            alert(selectedOptionValue);
            $('#hidSelectedScanOption').val(selectedOptionValue);
        });     


        //Set the Scan Type radio button if it has a value other than default
        var existingDefaultScanType = document.getElementById('hidExistingScanOption').value;
        alert(existingDefaultScanType);
        if(existingDefaultScanType != null && existingDefaultScanType != "")
        {
            $("input[name=defaultScanOption][value="+existingDefaultScanType+"]").attr('checked', true);
        } 
 });
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜