Tuesday, July 14, 2015

How to check or verify if atleast one of the form radio buttons were selected?

This page keeps collecting feedback from a user for 5 times and then responds with a thank you message. This example using jQuery + forms is mainly written to expand it to a series of questions to be posed to a user and collect feedback about them from the user in a compact way.


Include the jQuery reference:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script  type='text/javascript'>
        var count=1;

And then write the repeat function that does the trick to slide over a set of questions. Here only one question is repeating but you can extend it to other purposes.


        function submitform()
        {
                //alert(count);
                //alert("Inside submitform");
                if(count==5)
                {
                         $('#formid').html("Thank you!");
                }
                else
                {
                        //alert("Inside the submitform");
                        count=count+1;
                        $('#formid').html("<form action=\"submitform()\" method=\"post\" id=\"reportform\"> <label><input type=\"radio\" name=\"report\" value=\"customer\" /> Customers</label><br /><label><input type=\"radio\" name=\"report\" value=\"item\" /> Items Sold</label><br /><label><input type=\"radio\" name=\"report\" value=\"department\" /> Sales Departments</label><br /><label><input type=\"radio\" name=\"report\" value=\"person\" /> Sales People</label><br /><input type=\"button\" name=\"reportsubmit\" value=\"Submit\" onClick=\"verifyText(this.form)\" /> </form>");
                }
        }
</script>

</head>
<body>

Now the body section starts.. You can show the user whatever you want. Here I am asking the same question. Once you click the submit it verified is atleast one of the radio buttons is selected. If selected, then repeat if not, stay on the same page.

<div id="formid">
<form action="submitform()" method="post" id="reportform">
    <label><input type="radio" name="report" value="customer" /> Customers</label><br />
    <label><input type="radio" name="report" value="item" /> Items Sold</label><br />
    <label><input type="radio" name="report" value="department" /> Sales Departments</label><br />
    <label><input type="radio" name="report" value="person" /> Sales People</label><br />
    <input type="button" name="reportsubmit" value="Submit" onClick="verifyText(this.form)" />
</form>
</div>

This is the verify section:

<script>
function verifyText (form) {
        var checked = form.querySelector('input:checked');
        var value = checked ? checked.value : null;
        alert(value);
        if(value!=null)
                submitform();

}


</script>


No comments: