How to validate a form using HTML5 and CSS - html

I coded a form that can post information to another page where it is processed. I wanted to ask users if there are options that were not selected. My form looks like this:
<form action="answers-of-brain-teaser-questions.php" method="post">
<div>
<div>Question 1</div>
<input name="q1" type="radio" value="1">A. 1
<br />
<input name="q1" type="radio" value="2">B. 4
<br />
<input name="q1" type="radio" value="3">C. 3
<br />
<input name="q1" type="radio" value="4">D. 2
</div>
<div>
<div id="question">Question 2</div>
<input name="q2" type="radio" value="5">A. 1
<br />
<input name="q2" type="radio" value="6">B. 2
<br />
<input name="q2" type="radio" value="7">C. 3
<br />
<input name="q2" type="radio" value="8">D. 4
</div>
</form>
How can I show users a message if some radio buttons are clicked. I only want to show a message if a question has no selected answer (no radio button is selected). For example, if no option is selected for question 2.

The easiest way to do this is with the built-in HTML5 attribute called required which tells the user that he has left a field (in our case the radio button).
An example how to use it:
<!DOCTYPE HTML>
<html>
<body>
<form id="exampleForm" action="#" method="get">
<input name="q1" type="radio" required="required" value="4">test<br />
<input name="q1" type="radio" required="required" value="4">test<br />
<input name="q1" type="radio" required="required" value="4">test<br />
<input name="sform" type="submit">
</form>
</body>
</html>

If you have no access to JQuery and want to support browsers not supporting required, you can use something like this:
var names = new Array("q1", "q2");
var notSelected = new Array();
var checked = "";
for(var i = 0; i < names.length; ++i) {
var current = getElementsByName(names[i]);
for(var j = 0; j < current.length; ++j) {
if(current[j].checked) {
checked = names[i];
}
}
if(names[i] !== checked)
notSelected.push(names[i]);
}
if(notSelected.length>0)
alert("You have to select the following radiogroups: "+notSelected.join(", "));

If you want to validate it via jquery it will go like-
//in script add jquery-min.js
function validate(){
if($("input[name=q2]:checked").length > 0) {
//Is Valid
}
}
<form action="answers-of-brain-teaser-questions.php" method="post" onsubmit="validate()">
<div>
<div>Question 1</div>
<input name="q1" type="radio" value="1">A. 1
<br />
<input name="q1" type="radio" value="2">B. 4
<br />
<input name="q1" type="radio" value="3">C. 3
<br />
<input name="q1" type="radio" value="4">D. 2
</div>
<div>
<div id="question">Question 2</div>
<input name="q2" type="radio" value="5">A. 1
<br />
<input name="q2" type="radio" value="6">B. 2
<br />
<input name="q2" type="radio" value="7">C. 3
<br />
<input name="q2" type="radio" value="8">D. 4
</div>
</form>
And if you want to do it in php page-
then check it via-
if(!isset($_POST['q2'})){
//your msg to user
}

Related

How to "lock" an html radiobutton after selection?

Given this checkbox html element:
<h4>This is a question?</h4>
<input type="radio" value="1" name="q">answer 1</input>
<input type="radio" value="2" name="q">answer 2</input>
<input type="radio" value="3" name="q">answer 3</input>
How can I lock the state of a checkbox after it has been selected? That is, how can I avoid the user to change his answer?
A hacky idea using CSS. You make a layer that will prevent any click event when one input is checked
.block {
position:relative;
}
.block input:checked ~ i {
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
}
<div class="block">
<h4>This is a question? (blocked)</h4>
<input type="radio" value="1" name="q1">answer 1
<input type="radio" value="2" name="q1">answer 2
<input type="radio" value="3" name="q1">answer 3
<i></i>
</div>
<div >
<h4>This is a question? (not blocked)</h4>
<input type="radio" value="1" name="q2">answer 1
<input type="radio" value="2" name="q2">answer 2
<input type="radio" value="3" name="q2">answer 3
<i></i>
</div>
With Anush Bhatia's example, you would need to also use JQuery.
Here is a simple snippet without the use of JQuery:
function change(yourname) {
var radios = document.getElementsByName(youname);
for (var i=0, iLen=radios.length; i<iLen; i++) {
radios[i].disabled = true;
}
}
Remember that you should also call the function on change using
<input type="radio" value="1" onchange="change(\"q\");" name="q">answer 1</input>
$('input:radio').click(function(){
var $inputs = $('input:radio')
if($(this).is(':radio')){
$inputs.not(this).prop('disabled',true); // <-- disable all but checked one
}else{
$inputs.prop('disabled',false); // <--
}
})
Try using this.
Refer to the link below http://jsfiddle.net/ur9zxo2e/
You could make each question be in ONE element and apply a questionHandle function to each question element
var questionElement1=document.getElementById('q1')
function questionHandle(elem){
var answered=false
function listen(ev){
if(answered){return ev.preventDefault()}
//else, since this only happens IF not pressed already
answered=true //so that it will not be pressed again
//any other thing you want to do for when question is answered below after this INSIDE this function
console.log(`question ${ev.path[0].value} was chosen`)//an example of anything you can do
}
try{
[...elem.children]
.forEach(a=>a.addEventListener('click',listen))
}
catch(err){return Error(err)}
}
questionHandle(questionElement1)
<h4>This is a question?</h4>
<div id="q1">
<input type="radio" value="1" name="q">answer 1</input>
<input type="radio" value="2" name="q">answer 2</input>
<input type="radio" value="3" name="q">answer 3</input>
</div>
I will do that this way :
const myForm = document.forms['my-form']
myForm.radioChoice = {}
myForm.oninput = ({target}) =>
{
if( target.type === 'radio')
{
if (!myForm.radioChoice[target.name])
myForm.radioChoice[target.name] = target.value
else
myForm[target.name].value = myForm.radioChoice[target.name]
}
}
<form action="" name="my-form">
<fieldset>
<legend>Question 1</legend>
<label><input type="radio" value="1" name="q1" />answer 1</label>
<label><input type="radio" value="2" name="q1" />answer 2</label>
<label><input type="radio" value="3" name="q1" />answer 3</label>
</fieldset>
<fieldset>
<legend>Question 2</legend>
<label><input type="radio" value="1" name="q2" />answer 1</label>
<label><input type="radio" value="2" name="q2" />answer 2</label>
<label><input type="radio" value="3" name="q2" />answer 3</label>
</fieldset>
</form>

How to check the array of radio buttons is checked or not?

Following is the html content and I want to check whether one of the radio button is checked or not?
<div class="col-sm-4 rating">
<input type="hidden" name="questionId[]" value="4"/>
<input type="radio" class="career_ratings" id="career_star31" name="career_rating_answer[3]" value="1" />
<label for="career_star31" title=""></label>
<input type="radio" class="career_ratings" id="career_star32" name="career_rating_answer[3]" value="2"/>
<label for="career_star32" title=""></label>
<input type="radio" class="career_ratings" id="career_star33" name="career_rating_answer[3]" value="3"/>
<label for="career_star33" title=""></label>
<input type="radio" class="career_ratings" id="career_star34" name="career_rating_answer[3]" value="4"/>
<label for="career_star34" title=""></label>
</div>
https://plnkr.co/edit/vlYNcBeEUkP0wLtcbqtV?p=preview
<!DOCTYPE html>
<html>
<body>
<form>
<div class="col-sm-4 rating">
<input type="hidden" name="questionId[]" value="4" />
<input type="radio" class="career_ratings" id="career_star31" name="career_rating_answer[3]" value="1" />
<label for="career_star31" title="1">1</label>
<input type="radio" class="career_ratings" id="career_star32" name="career_rating_answer[3]" value="2" />
<label for="career_star32" title="2">2</label>
<input type="radio" class="career_ratings" id="career_star33" name="career_rating_answer[3]" value="3" />
<label for="career_star33" title="3">3</label>
<input type="radio" class="career_ratings" id="career_star34" name="career_rating_answer[3]" value="4" />
<label for="career_star34" title="4">4</label>
</div>
<button onclick="check()">Try it</button>
</form>
<script>
function check() {
var radio = document.getElementsByClassName('career_ratings');
var x = false;
for (var i = 0; i < radio.length; i++) {
if (radio[i].checked) {
x = true;
}
}
alert(x)
}
</script>
</body>
</html>

Multiples input type="radio" that can be selected and and deselected

I have the following code of inputs
<div id="especiality">
<input type="radio" class="rad" name="Item1" value="Item1" />Publicidad
<br />
<input type="radio" class="rad" name="Item2" value="Item2" />Editorial
<br />
<input type="radio" class="rad" name="Item3" value="Item3" />Identidad Corporativa
<br />
<input type="radio" class="rad" name="Item4" value="Item4" />Web
<br />
<input type="radio" class="rad" name="Item5" value="Item5" />Empaques
<br />
<input type="radio" class="rad" name="Item6" value="Item6" />Tipografía
<br />
<input type="radio" class="rad" name="Item7" value="Item7" />Fotografía
<br />
<input type="radio" class="rad" name="Item8" value="Item8" />Señalética
<br />
<input type="radio" class="rad" name="Item9" value="Item9" />Animación
<br />
<input type="radio" class="rad" name="Item10" value="Item10" />Ilustración
<br />
</div>
That works with this script
<script>
$(document).ready(function () {
$("#button").click(function () {
// Radios
$(".rad:checked").each(function() {
console.log("Radio: " + $(this).val());
});
});
})
</script>
It works for select multiples options and thats ok but it doesn't when it comes to deselect the option. Any solutions?
Thanks
Selector for unchecked items would be:
$(".rad:not(:checked)").each(function() {
Radio buttons are designed to let you select exactly one out of a group. You can start a group with zero selected (by omitting the checked attribute from all of them) but there isn't a clean way to go back to that state.
To group radio buttons, give them all the same name.
If you want to select zero or more from a group, you should be using checkboxes, not radio buttons.

Validate a Radio Button

I want to make a simple validation form, which will show warning message, when it will be uncheck in a <div>.
This is what, i come up till now.
<form action="result.php" method="post">
<b>1st question:</b><br />
Option 1 <input type="radio" name="question1" value="Option1" /><br />
Option 2 <input type="radio" name="question1" value="Option2" /><br />
Option 3 <input type="radio" name="question1" value="Option3" /><br />
Option 4 <input type="radio" name="question1" value="Option4" /><br />
<br />
<b>2nd question:</b><br />
Option 1 <input type="radio" name="question2" value="Option1" /><br />
Option 2 <input type="radio" name="question2" value="Option2" /><br />
Option 3 <input type="radio" name="question2" value="Option3" /><br />
Option 4 <input type="radio" name="question2" value="Option4" /><br />
<br />
<input type="submit" value="submit" />
</form>`
you can do this by jQuery. The length attribute it calculate The number of elements in the jQuery object
$("#forms").submit(function(){ //or you can use click event
if ($("input[name='question1']:checked").length > 0){
$('.show_message').html(' ');
$('.show_message').html('selected ');
}
else{
$('.show_message').html(' ');
$('.show_message').html(' no one selected ');
return false;
}
});
and
<div class="show_message"></div>
<form id="form" action="result.php" method="post">
. . . .
</form>

change form action with radio buttons

I would like to implement something similar to a google search with radio buttons. Depending on the radio button selected, would change the type of search (search,images,video, etc).
Right now I have:
<div id ="searchtext">
<form method="get" id ="searchbox" action="http://www.google.com/search"/>
<input type="text" name="q" size="30" class="searchtext" maxlength="255" value="" />
<input type="image" value="Search" class="searchbutton" src="images/searchbar/searchbutton.png"/>
<br/>
</div>
<div id="radiosearch">
<input type="radio" name="radiosearch" onclick="document.searchbox.action='http://www.google.com/search?q=';" checked="checked"/> Web
<input type="radio" name="radiosearch" onclick="document.searchbox.action='http://images.google.com/images?q=';"/>Images
<input type="radio" name="radiosearch" onclick="document.searchbox.action='http://maps.google.com/maps?hl=en&tab=wl?q=';"/>Maps
<input type="radio" name="radiosearch" onclick="document.searchbox.action='http://www.youtube.com/results?q=';"/>Youtube
<span class = "class1">
Change Theme
</span>
</div>
However, clicking on the radio boxes is not changing the form action. Any Ideas?
Try
<input type="radio" name="radiosearch" onclick="document.getElementById('searchbox').action='http://www.google.com/search?q=';" checked="checked"/> Web
<input type="radio" name="radiosearch" onclick="document.getElementById('searchbox').action='http://images.google.com/images?q=';"/>Images
<input type="radio" name="radiosearch" onclick="document.getElementById('searchbox').action='http://maps.google.com/maps?hl=en&tab=wl?q=';"/>Maps
<input type="radio" name="radiosearch" onclick="document.getElementById('searchbox').action='http://www.youtube.com/results?q=';"/>Youtube