3

I don't have any form here. Just a few divs with a few questions. I want to check here if radio button is checked or not if it is checked then store its value in an array and move onto the next screen. I found out that the required attribute for client side validation only works for forms and i don't have any forms here.

here is my html below :

<div class="first-div">
    <p>Question1: Where in the world would you find the Spire?</p>
    <span><input type="radio" name="radio" id="a1" value="a1" /> Kerry. </input></span>
    <span><input type="radio" name="radio" id="a1" value="a1" /> Galway. </input></span>
    <span><input type="radio" name="radio" id="a1" value="a1" /> Dublin. </input></span>
    <span><input type="radio" name="radio" id="a1" value="a1" /> Donegal. </input></span>
    <div class="button_box">
        <button class="back" disabled="true" style="color:#aaa">Back</button>
        <button class="next">Next</button>
    </div>
</div>

<div class="next-div" style="display:none;">
    <p>Question2: Where in the world would you find the Colosseum?</p>
    <span><input type="radio" name="radio" id="b1" value="a2" /> Taipei. </input></span>
    <span><input type="radio" name="radio" id="b1" value="a2" /> Rome. </input></span>
    <span><input type="radio" name="radio" id="b1" value="a2" /> Reykjavic. </input></span>
    <span><input type="radio" name="radio" id="b1" value="a2" /> Brussels. </input></span>
    <div class="button_box">
        <button class="back">Back</button>
        <button class="next">Next</button>
    </div>
</div>

<div class="next-div" style="display:none;">
    <p>Question3: Where in the world would you find the Colosseum?</p>
    <span><input type="radio" name="radio" id="c1" value="a3" /> Taipei. </input></span>
    <span><input type="radio" name="radio" id="c1" value="a3" /> Rome. </input></span>
    <span><input type="radio" name="radio" id="c1" value="a3" /> Reykjavic. </input></span>
    <span><input type="radio" name="radio" id="c1" value="a3" /> Brussels. </input></span>
    <div class="button_box">
        <button class="back">Back</button>
        <button class="next">Next</button>
    </div>
</div>
<div class="next-div" style="display:none;">
    <p>Question4: Where in the world would you find the Colosseum?</p>
    <span><input type="radio" name="radio" id="d1" value="a3" /> Taipei. </input></span>
    <span><input type="radio" name="radio" id="d1" value="a3" /> Rome. </input></span>
    <span><input type="radio" name="radio" id="d1" value="a3" /> Reykjavic. </input></span>
    <span><input type="radio" name="radio" id="d1" value="a3" /> Brussels. </input></span>
    <div class="button_box">
        <button class="back">Back</button>
        <button class="finish">Finish</button>
    </div>
</div>

and here is my jquery for now

$('.next').click(function(){
   $(this).parent().parent().hide().next().show();//hide parent and show next
});

$('.back').click(function(){
   $(this).parent().parent().hide().prev().show();//hide parent and show previous
});
Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77
Rex
  • 33
  • 1
  • 6

10 Answers10

3

check this will help:-

var checkedValues = [];
 $('.next').click(function() {
    var $form = $(this).parent().parent();
    var $checked =     $(this).parent().parent().find('input[type=radio]:checked')
    var isChecked = $checked.length > 0;
    if(!isChecked){
      alert('Please Choose an option.');
      return;
    }
    checkedValues.push($checked.val());
    console.log($checked.val());
    $form.hide().next().show(); //hide parent and show next
  });

  $('.back').click(function() {
    console.log('back');
    $(this).parent().parent().hide().prev().show(); //hide parent and show previous
  });

here a working demo

  • Perfect ! Thanks. Also how do i retrieve the last answer if i press back. Can you also please update your code here....i,ve given you an upvote...how do i mark it as your answer as correct ? – Rex Jan 18 '17 at 06:51
  • I will Handle it in the sample and send you back Mark as answer please – Mohammed Elshennawy Jan 18 '17 at 06:52
  • Can you update code for the back button now ? When i press the back button the answers just disappear. – Rex Jan 18 '17 at 07:09
  • @Henry...yes i did...the one with the mapping solution...its good...i also commented on it...please check. – Rex Jan 18 '17 at 07:24
  • Brother this is the updated [demo](http://plnkr.co/edit/Ue0le0HalhwUqI4yC7ID?p=preview) you may simulate the back button in the next button if you want to load the old values again first @Rex (sorry for being late i was having a meeting) – Mohammed Elshennawy Jan 18 '17 at 08:20
  • Oh thanks brother...but now i have this issue when i press the back button and then then the next button the values get deleted again. – Rex Jan 18 '17 at 08:28
  • yes i know and if you read carefully the pervious comment you will find :- you may simulate the back button in the next button if you want to load the old values again first (a little work to do). if you stuck just let me know . – Mohammed Elshennawy Jan 18 '17 at 08:33
  • Brother, check the [demo](http://plnkr.co/edit/Ue0le0HalhwUqI4yC7ID?p=preview) it is now updated as you want. Please up vote. – Mohammed Elshennawy Jan 18 '17 at 08:51
  • Thanks...already up voted....just another question...you sound like a professional developer...is this the right way to approach this kind of problem ? Like a person is sitting for a college admission test where the user is given a couple of question and we want the user to display one question at a time and we are storing the answers in an array later to be processed....how would you solve this professionally. – Rex Jan 18 '17 at 10:37
  • Look, This is not an easy question as I do not have good knowledge about test systems but, I think it is not a good choice to put all questions in HTML and show/hide it may help in cheating and makes the content easy to be taken, it is better to get them from the server on demand this helps you to select question randomly if you want or whatever scenario you want.you may Just put some question and try to answer them and you will figure out the good way to do it. if the comment adds something useful please mark it. – Mohammed Elshennawy Jan 18 '17 at 17:49
1

Use .prop() method by jQuery. And do not use the same id multiple times:

HTML:

<div id="first" class="first-div">
    <p>Question1: Where in the world would you find the Spire?</p> 
    <span><input type="radio" name="radio" id="a10" value="0" /> Kerry. </input></span>
    <span><input type="radio" name="radio" id="a11" value="1" /> Galway. </input></span>
    <span><input type="radio" name="radio" id="a12" value="2" /> Dublin. </input></span>
    <span><input type="radio" name="radio" id="a13" value="3" /> Donegal. </input></span>
    <div class="button_box">
       <button class="back" disabled="true" style="color:#aaa">Back</button>
       <button class="next">Next</button>
    </div>   
</div>

Javascript:

$("#first input").each(function () {
    if ( $(this).prop("checked") ) {
        console.log( $(this).val() );
    }
});
elementzero23
  • 1,389
  • 2
  • 16
  • 38
1

Just use map. Here's a simple solution. Hope it helps!

var arr = [];

    $('.next').click(function () {
        var self = $('input[type="radio"]:checked');
        if (!self.is(':checked')) {
            alert("Please choose an option");
            $(this).parent().show();
        }else {
            self.prop('checked', false);
            $(this).parent().parent().hide().next().show();
        }
    });

    $('.back').click(function () {
        $(this).parent().parent().hide().prev().show();
    });

    $('input[type="radio"]').on('click', function () {
        var get_values = $('input[type="radio"]:checked').map(function () {
            return this.value;
        }).get();
        arr.push(get_values[0]);
        console.log(arr);
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="first-div">
    <p>Question1: Where in the world would you find the Spire?</p>
    <span><input type="radio" name="radio" id="a1" value="a1"/> Kerry. </input></span>
    <span><input type="radio" name="radio" id="a1" value="a1"/> Galway. </input></span>
    <span><input type="radio" name="radio" id="a1" value="a1"/> Dublin. </input></span>
    <span><input type="radio" name="radio" id="a1" value="a1"/> Donegal. </input></span>
    <div class="button_box">
        <button class="back" disabled="true" style="color:#aaa">Back</button>
        <button class="next">Next</button>
    </div>
</div>

<div class="next-div" style="display:none;">
    <p>Question2: Where in the world would you find the Colosseum?</p>
    <span><input type="radio" name="radio" id="b1" value="a2"/> Taipei. </input></span>
    <span><input type="radio" name="radio" id="b1" value="a2"/> Rome. </input></span>
    <span><input type="radio" name="radio" id="b1" value="a2"/> Reykjavic. </input></span>
    <span><input type="radio" name="radio" id="b1" value="a2"/> Brussels. </input></span>
    <div class="button_box">
        <button class="back">Back</button>
        <button class="next">Next</button>
    </div>
</div>

<div class="next-div" style="display:none;">
    <p>Question3: Where in the world would you find the Colosseum?</p>
    <span><input type="radio" name="radio" id="c1" value="a3"/> Taipei. </input></span>
    <span><input type="radio" name="radio" id="c1" value="a3"/> Rome. </input></span>
    <span><input type="radio" name="radio" id="c1" value="a3"/> Reykjavic. </input></span>
    <span><input type="radio" name="radio" id="c1" value="a3"/> Brussels. </input></span>
    <div class="button_box">
        <button class="back">Back</button>
        <button class="next">Next</button>
    </div>
</div>
<div class="next-div" style="display:none;">
    <p>Question4: Where in the world would you find the Colosseum?</p>
    <span><input type="radio" name="radio" id="d1" value="a4"/> Taipei. </input></span>
    <span><input type="radio" name="radio" id="d1" value="a4"/> Rome. </input></span>
    <span><input type="radio" name="radio" id="d1" value="a4"/> Reykjavic. </input></span>
    <span><input type="radio" name="radio" id="d1" value="a4"/> Brussels. </input></span>
    <div class="button_box">
        <button class="back">Back</button>
        <button class="finish">Finish</button>
    </div>
</div>
HenryDev
  • 4,685
  • 5
  • 27
  • 64
  • Great..but how do you handle client side validation here if the user does not checks anything and presses next...it should give some error. – Rex Jan 18 '17 at 07:14
  • I,ll mark it as an answer after you handle client side validation since that was my main question. – Rex Jan 18 '17 at 07:14
1

I made a Code for you which validate your question. If the user doesn't select any answers it will alert him to select any answer. If the user select any answer I alert the value of input and text relative to that input and push that both values in an array which i console.log you can check that at console. If any problem check my code here -> https://jsfiddle.net/Arsh_kalsi01/81bLwLov/1/

  var valuesArray=[];


$('.next').click(function(){
  var obj = $(this);
    performMyAction(obj);
   
});
$('.finish').click(function(){
  var obj = $(this);
    performMyAction(obj);
   
});


    function performMyAction(obj)
    {
       var objectmain = obj.parent().parent();
        var hasalert = true;
        
      $(objectmain).find("input").each(function () {
          if ( $(this).is(':checked')) {
          var objval = $(this).val();
          var obtxt = $(this).parent().text();
          valuesArray.push({'value':objval,'Text':obtxt});
              alert( objval +obtxt);
              console.log(valuesArray);
              hasalert=false;
          }
      });
        
        if(hasalert==true)
        {
        alert("Check Any Radio Button");
        }else{
        obj.parent().parent().hide().next().show();//hide parent and show next
        }
        
       
    }
    
    $('.back').click(function(){
       $(this).parent().parent().hide().prev().show();//hide parent and show previous
    });
 

     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="first-div">
    <p>Question1: Where in the world would you find the Spire?</p> 
    <span><input type="radio" name="radio" class="First"  value="a1(1)"  /> Kerry. </span>
    <span><input type="radio" name="radio" class="First" value="a1(2)"  /> Galway. </span>
    <span><input type="radio" name="radio" class="First" value="a1(3)"  /> Dublin.</span>
    <span><input type="radio" name="radio"   class="First" value="a1(4)"  /> Donegal. </span>
    <div class="button_box">
        <button class="back" disabled="true" style="color:#aaa">Back</button>
       <button class="next">Next</button>
    </div>   

</div>

<div class="next-div" style="display:none;">
   <p>Question2: Where in the world would you find the Colosseum?</p> 
<span><input type="radio" name="radio"  class="second" value="a2(1)"  /> Taipei. </span>
<span><input type="radio" name="radio" class="second"  value="a2(2)"  /> Rome. </span>
<span><input type="radio" name="radio"  class="second" value="a2(3)"  /> Reykjavic.</span>
<span><input type="radio" name="radio" class="second"  value="a2(4)"  /> Brussels. </span>
<div class="button_box">
   <button class="back">Back</button>
   <button class="next">Next</button>
</div>
   </div>

<div class="next-div" style="display:none;">
    <p>Question3: Where in the world would you find the Colosseum?</p> 
<span><input type="radio" name="radio" class="third"  value="a3(1)"  /> Taipei.</span>
<span><input type="radio" name="radio" class="third"  value="a3(2)"  /> Rome. </span>
<span><input type="radio" name="radio"  class="third" value="a3(3)"  /> Reykjavic. </span>
<span><input type="radio" name="radio" class="third" value="a3(4)"  /> Brussels. </span>
<div class="button_box">
   <button class="back">Back</button>
   <button class="next">Next</button>
</div>
</div>
<div class="next-div" style="display:none;">
    <p>Question4: Where in the world would you find the Colosseum?</p> 
<span><input type="radio" name="radio" class="fourth"  value="a4(1)"  /> Taipei. </span>
<span><input type="radio" name="radio" class="fourth"  value="a4(2)"  /> Rome. </span>
<span><input type="radio" name="radio" class="fourth"  value="a4(3)"  /> Reykjavic. </span>
<span><input type="radio" name="radio" class="fourth"  value="a4(4)"  /> Brussels. </span>
<div class="button_box">
    <button class="back">Back</button>
   <button class="finish">Finish</button>
</div>   
</div>
Arsh Kalsi
  • 179
  • 1
  • 10
  • No client side validation handling here...when i press next without selecting anything it just goes to the next section :-( – Rex Jan 18 '17 at 08:19
1

Can you please run code snippet of my recent answer. when you press next without selecting anything it show you a alert box and not go to next section:-

Arsh Kalsi
  • 179
  • 1
  • 10
0

Just use the .checked to see if is true or false

Felix Fong
  • 969
  • 1
  • 8
  • 21
0

Updated
If you just want to check for whole document without form you can do like this:

if (!$("input[type=radio]:checked").val()) {
        alert("Please select department");
        return false;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

As you can see you just have to give name of the input radio group of just give a simple name to all of them and then check. If checked then store checked radio button's value you can google how to store checked radio button's value in jquery.

Update: Not you can run a loop to check if any of the radio button is checked or not. If checked then using that same expression val() will give all the checked radio's value the push them into an array. using push() of jquery

  • Not working...i have id and not names...also how do i store the value in an array here after checking the radio button. – Rex Jan 18 '17 at 06:31
0

I think you are trying to do a validation if the user has selected an answer before moving to the next question. you can check for if an option is selected in the radio group using :checked for that particular context radio group(in case you want to have the same group name).

$('.next').click(function(){

   var context = $(this).parent().parent();
   if($("input[name='radio']",context).is(":checked"))
   context.hide().next().show();//hide parent and show next
   else
   alert("select an answer before moving to next");
});

Hope this helps.

$('.next').click(function(){
  
   var context = $(this).parent().parent();
   if($("input[name='radio']",context).is(":checked"))
   context.hide().next().show();//hide parent and show next
   else
   alert("select an answer before moving to next");
});

$('.back').click(function(){
   $(this).parent().parent().hide().prev().show();//hide parent and show previous
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first-div">
<p>Question1: Where in the world would you find the Spire?</p> 
<span><input type="radio" name="radio"  value="a1"  /> Kerry. </input></span>
<span><input type="radio" name="radio"  value="a1"  /> Galway. </input></span>
<span><input type="radio" name="radio"  value="a1"  /> Dublin. </input></span>
<span><input type="radio" name="radio"  value="a1"  /> Donegal. </input></span>
<div class="button_box">
    <button class="back" disabled="true" style="color:#aaa">Back</button>
   <button class="next">Next</button>
</div>   
</div>

<div class="next-div" style="display:none;">
   <p>Question2: Where in the world would you find the Colosseum?</p> 
<span><input type="radio" name="radio"  value="a2"  /> Taipei. </input></span>
<span><input type="radio" name="radio"  value="a2"  /> Rome. </input></span>
<span><input type="radio" name="radio"  value="a2"  /> Reykjavic. </input></span>
<span><input type="radio" name="radio"  value="a2"  /> Brussels. </input></span>
<div class="button_box">
   <button class="back">Back</button>
   <button class="next">Next</button>
</div>
   </div>

<div class="next-div" style="display:none;">
    <p>Question3: Where in the world would you find the Colosseum?</p> 
<span><input type="radio" name="radio"  value="a3"  /> Taipei. </input></span>
<span><input type="radio" name="radio"  value="a3"  /> Rome. </input></span>
<span><input type="radio" name="radio"  value="a3"  /> Reykjavic. </input></span>
<span><input type="radio" name="radio" value="a3"  /> Brussels. </input></span>
<div class="button_box">
   <button class="back">Back</button>
   <button class="next">Next</button>
</div>
</div>
<div class="next-div" style="display:none;">
    <p>Question4: Where in the world would you find the Colosseum?</p> 
<span><input type="radio" name="radio"  value="a3"  /> Taipei. </input></span>
<span><input type="radio" name="radio"  value="a3"  /> Rome. </input></span>
<span><input type="radio" name="radio"  value="a3"  /> Reykjavic. </input></span>
<span><input type="radio" name="radio"  value="a3"  /> Brussels. </input></span>
<div class="button_box">
    <button class="back">Back</button>
   <button class="finish">Finish</button>
</div>   
</div>

P.S : I have removed the same id attribute from all elements which will make the html invalid.

Rajesh
  • 24,354
  • 5
  • 48
  • 79
Deep
  • 9,594
  • 2
  • 21
  • 33
0

Check This one too

var arr = [];
$('#id-next').click( function() {
    if( $('#first input[name=radio]').is(':checked') ) {
     arr.push( $('#first input[name=radio]:checked').val() );
      alert("Answer : "+$('#first input[name=radio]:checked').val());
    }
    else
      alert("Select Answer");
    
    alert("Array is : "+arr.join(","));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="first" class="first-div">
    <p>Question1: Where in the world would you find the Spire?</p> 
    <span>
    <input type="radio" name="radio" id="a10" value="0" /> Kerry. </span>
    <span><input type="radio" name="radio" id="a11" value="1" /> Galway. </span>
    <span><input type="radio" name="radio" id="a12" value="2" /> Dublin. </span>
    <span><input type="radio" name="radio" id="a13" value="3" /> Donegal. </span>
    <div class="button_box">
       <button class="back" disabled="true" style="color:#aaa">Back</button>
       <button class="next" id="id-next">Next</button>
    </div>   
</div>
Shantaram Tupe
  • 1,646
  • 3
  • 16
  • 42
0

In my understanding, you are looking for a validator.

function validateAnswer() {
  return $('[class$="-div"] :visible')
          .find('input[name="radio"]')
          .is(":checked");
}

Working Demo

Also few pointers

  • ID of an element must be unique
  • Instead of .parent().parent(), you should use .parents(selector)
  • Its better to have a common class across all questions and then use $(this).closest('commonClass').nest().show() on validate
Rajesh
  • 24,354
  • 5
  • 48
  • 79