I am working on survey application in this I want only unique answers to be selected like for eg

     <form action="somefile.php" method="post" name="testForm">
     <tr><td>Question 1 </td><td>
        4<input type="radio" name="1" value='4' class="Session"/>
        3<input type="radio" name="2" value='3' class="Session"/>
        2<input type="radio" name="3" value='2' class="Session"/>
        1<input type="radio" name="4" value='1' class="Session"/></td></tr>
        <tr><td>Question 2 </td><td>
        4<input type="radio" name="1" value='4' class="Session"/>
        3<input type="radio" name="2" value='3' class="Session"/>
        2<input type="radio" name="3" value='2' class="Session"/>
        1<input type="radio" name="4" value='1' class="Session"/></td></tr>
        <tr><td>Question 3 </td><td>
        4<input type="radio" name="1" value='4' class="Session"/>
        3<input type="radio" name="2" value='3' class="Session"/>
        2<input type="radio" name="3" value='2' class="Session"/>
        1<input type="radio" name="4" value='1' class="Session"/></td></tr>
        <tr><td>Question 4 </td><td>
        4<input type="radio" name="1" value='4' class="Session"/>
        3<input type="radio" name="2" value='3' class="Session"/>
        2<input type="radio" name="3" value='2' class="Session"/>
        1<input type="radio" name="4" value='1' class="Session"/></td></tr>
       <tr><td><input type="submit" value="submit" onClick="return check()"/></td></tr>
       <div id="unAnswered"></div>

on submit I want to check for 2 things
- all the questions are to be answered
- the values selected for each should be unique like for question 1 if user has select 4 then for question 2, 3 & 4 the 4th option should be disabled.

I worked out something like this in javascript :

<script type="text/javascript" language="javascript">
    $(document).ready(function() {
 $('input:radio').click(function() {
       //reset all the radios
       $('input:radio').removeAttr('disabled');
       if($(this).is(':checked')) {
           var val = $(this).val();
           //disable all the ones with the same value
           $('input:radio').each(function() {
               if(val == $(this).val()) {
                   $(this).attr('disabled',true);
               }
           });
           //let's not disable the one we have just clicked on
           $(this).removeAttr('disabled');
       }
    }); 
       });
function check() {
       for(var i=1;i<5;i++){
                    var answer=false;
                    var q=i;//appending number
                    var x=document.getElementsByName(q);//getting those radio groups
                    var len=x.length;
                    for(var p=0;p<len;p++){
                        if(x[p].checked){
                            answer=true; 
                        }
                    }
                    if(!answer){
                        document.getElementById("unAnswered").innerHTML
                            ="<span style=\"color:red\">You must answer all questions</span>";
                        return false;//exit if one is not answered
                    }
                }

             document.forms["testForm"].submit();//by here all questions are answered
}

</script>

This works fine when checking if all are answered or not but the problem is :
it disables that value for all other questions but once another option is selected, it resets all radios & the user is able to select same value for another question.
I tried commenting this line too

$('input:radio').removeAttr('disabled');

but then the user has only one shot to select the values which I do not want.

What is wrong in my code? Please help.

Thanks in advance.

Dani AI

Generated

Brief summary and a practical fix

The core issue in 's original handler is re-enabling every radio on each click, which undoes previous uniqueness rules. 's remark about handling both select and deselect is on the right track, but a simpler, more reliable pattern is to compute the currently chosen answers and then enable/disable only the options that conflict with that current set.

A robust approach (use the change event and prop('disabled', ...))—collect checked values keyed by question name, then for every radio: leave it enabled if it is the checked one for its group, otherwise disable it if some other group already chose the same value. Run the same refresh once at load so preselected answers are respected.

$(function(){
  function refreshUnique() {
    var selected = {};
    $('input.Session:checked').each(function(){
      selected[$(this).attr('name')] = $(this).val();
    });
    $('input.Session').each(function(){
      var $r = $(this), name = $r.attr('name'), val = $r.val();
      if ($r.is(':checked')) {
        $r.prop('disabled', false);
      } else {
        var conflict = false;
        for (var q in selected) {
          if (q !== name && selected[q] === val) { conflict = true; break; }
        }
        $r.prop('disabled', conflict);
      }
    });
  }
  $('input.Session').on('change', refreshUnique);
  refreshUnique();
});

Notes and caveats

  • Prefer semantic group names such as q1, q2 rather than bare numbers; it makes selectors and debugging easier.
  • Use .prop('disabled', true/false) (not .attr) for boolean attributes.
  • Disabled controls are not submitted by the browser; the checked radio remains enabled in this pattern so answers are still posted.
  • Always enforce uniqueness on the server as well (client-side JS can be bypassed).
  • For better accessibility, consider visually marking a value as “taken (selected by Question X)” or using ARIA attributes instead of completely removing focusability for keyboard users.

Recommended Answers

All 4 Replies

Err... You mixed jquery with pure JS... It is quite confusing to have to think back and forth; besides, it is not neat. Anyway, you should think about how it works first.

When a radio button is clicked
Check what value is being changed to (clicked or unclicked)
If clicked, disable all others with the same name/value
else remove disable property from all others with the same name/value

Your JQuery is not correct because you just check if it is clicked but no else. In other words, a user will have only 1 shot to select it... Add else {} where it removes the disable from all of the same name/value. Also, remove the line you said you commented it out because it will cause all disable radio buttons to be clickable again.

i am actually new to javascript so that is why I have messed it all up. Well il try & see how it works out. thanks :)

I used php instead of javascript to validate the radio buttons.

If the cost of connecting to the server is not that expensive, it is fine. ;) Regardless the checking occur at the front-end (HTML with JavaScript), please remember that you will have to make sure that the back-end (server) always validates the value. The reason is that a user could manipulate HTTP request or use a toll to by pass the JavaScript validation.

commented: thanks +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.