开发者

Add number of radio buttons selected (in php/js)

I have 5 sets of radio buttons, set1, set2, set3, set4, set5. Values are yes/no for each.

I need the number of yes's to be shown in a hidden text box.. ie 1,2,3,4 or 5, and obviously change as people select different options..

<input type="radio" name="set1" id="set1_no" value="no">
<input type="radio" name="set1" id="set1_yes" value="yes">

<input type="radio" name="set2" id="set2_no" value="no开发者_StackOverflow社区">
<input type="radio" name="set2" id="set2_yes" value="yes">

<input type="radio" name="set3" id="set3_no" value="no">
<input type="radio" name="set3" id="set3_yes" value="yes">

<input type="radio" name="set4" id="set4_no" value="no">
<input type="radio" name="set4" id="set4_yes" value="yes">

<input type="radio" name="set5" id="set5_no" value="no">
<input type="radio" name="set5" id="set5_yes" value="yes">


<input type="hidden" name="number_of_yes" value="" readonly="readonly">


Given that you are setting a hidden field (which doesn't need to be readonly, by the way, since it is...well...hidden) I would probably only update it onsubmit of the <form>. If you really need it updated as you go just use an onclick or onchange instead. However you trigger it, you can try something like this:

yourForm.onsubmit = setYesCount;

function setYesCount() {
  var count = 0;

  // could use yourForm.getElementsByTagName(),
  // but since the OP didn't provide surrounding HTML:
  var els = document.getElementsByTagName("input");
  for (var i=0; i < els.length; i++) {
    if (els[i].type === "radio" && els[i].checked && els[i].value === "yes")
      count++;
  }
  // add an id attribute to the hidden input
  // for the following to work
  document.getElementById("number_of_yes").value = count;
}

(And if I don't say it somebody else will: you could do this in one or two lines with jQuery.)

EDIT: jQuery version - again I've put it on the form's submit event (I'm assuming you have a form and can fill in the id). You can change this to a change or click event if needed.

$(document).ready(function() {
  $("#yourFormsId").submit(function() {
         $('input[name="number_of_yes"]').val(
            $('input:checked[type="radio"][value="yes"]').length);
  });
});


You can use javascript to maintain a counter variable whenever NO or YES is clicked. Define a class for all NO and YES buttons

I'd imagine doing something like this

var ctr = 0;
$(document).ready( function($) {
     $(".noradio").click((function () {
                 if (ctr != 0)
                 {
                     ctr--;
                 }
           })
     $(".yesradio").click()(function () {
                     ctr++;
           })
     $('input[name=hiddeninputname]').val(ctr);
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜