How to validate radio button on HTML forms using jQuery? - javascript

I'm trying to do a form field validation. I got the text fields validation working from here, but not for the radio buttons as I am unsure of where I did wrong.
HTML:
<div>
<label>Gender:</label>
<input type="radio" name="gender" class="gender" value="Female" >Female</input>
<input type="radio" name="gender" class="gender" value="Male" >Male</input> <br/>
<span class="error">This field is required</span>
</div>
jQuery:
$('.gender').on('input', function() {
var input = $( this );
var is_checked = $("input[name=gender]:checked").length != 0;;
if (is_checked) {$('.gender').removeClass("invalid").addClass("valid");}
else {$('.gender').removeClass("valid").addClass("invalid");}
});
This is the real-time validation code which I played around on. It does not work however. When submitting the form, my error message still shows up regardless of which radio button I choose.
$("#studentsform").submit(function(event) {
var form_data = $("#studentsform").serializeArray();
var error_free = true;
for (var input in form_data){
var element = $("#"+form_data[input]['name']);
var valid = element.hasClass("valid");
var error_element = $("span", element.parent());
if (!valid) {error_element.removeClass("error").addClass("error_show"); error_free = false;}
else {error_element.removeClass("error_show").addClass("error");}
}
if (!error_free) {
event.preventDefault();
}
else {
idcount++
var Surname = $('#surname').val();
var Name = $('#name').val();
var Gender = $('.gender:checked').val();
var Addr = $('#address').val();
var Email = $('#email').val();
var Phone = $('#phone').val();
$("#tblData tbody").append( "<tr>"+ "<td>" + idcount + "</td>"+ "<td>" + Surname + "</td>"+
"<td>" + Name + "</td>"+
"<td>" + Gender + "</td>"+
"<td>" + Addr + "</td>"+
"<td>" + Email + "</td>"+
"<td>" + Phone + "</td>"+
"<td><button class='btnEdit'>Edit</button><button class='btnDelete'>Delete</button></td>"+ "</tr>");
$(".btnEdit").bind("click", Edit);
$(".btnDelete").bind("click", Delete);
}
});
After checking all real-time validation, on the submit button I do the code above, which is to double check for validations and if it is error free, i append all the inputs into a row.
Preview:
As you can see from the picture above, even after clicking on Insert, my error message still shows up.
The author's code are very structured, but if anyone has a better and simpler way, could you please provide me a sample solution?
Much thanks!

Looks like you need
$("input[name=gender]").prop("checked");
which will return a boolean matching the checked value
Edit:
If you want to keep your code the same, you need to add the .valid class to all the gender-classed inputs. This way, when you check one radio, it will make both valid, and you shouldn't get an error.
$('.gender').on('input', function() {
var input = $( this );
var is_checked = $("input[name=gender]:checked").length != 0;
if (is_checked){
$('.gender').removeClass("invalid").addClass("valid");
} else {
$('.gender').removeClass("valid").addClass("invalid");
}
});

Related

Javascript - radio buttons onlick not working

I am stuck with a problem. I want to add call functions based on selection in radio button. But one of radio buttons doesn't work at all (not calling the function), other is not checked when clicked. Here is my code:
function clearElement(element_id){
document.getElementById(element_id).remove();
}
function createCheck(){
if (!document.getElementById('check')){
var btn = "<button onclick=\"checkData()\" id='check'>Check</button>";
document.getElementById("added").innerHTML += btn;
}
}
function addElements(){
var added0 = "<p>Choose the filling method:</p><br>";
var added1 = "<input type=\"radio\" value='Auto' id='auto' name=\"auto_manual\">I have ID</input>";
var added2 = "<input type=\"radio\" value='Manually' id='manual' name=\"auto_manual\"> Enter data manually</input><br>";
var added3 = "<p>Identification Code</p><br><input type=text id='ID'><br>";
var added4 = "<p>Enter your email address:</p><br><input type='email' id='mail' autocomplete=\"on\"></input><br>";
var added5 = "<button onclick=\"fillIn()\">Continue</button>";
document.body.innerHTML += "<div id=\"added\">" + added0 + added1 + added2 + added3 + added4 + added5 + "</div>";
var f0 = document.getElementById('auto');
var f1 = document.getElementById('manual');
f0.onclick = function() { createCheck();};
f1.onclick = function() { clearSelect('check');};
}
I want it to work the following way: if a user chooses "I have ID" option, the radio button is checked and the button "Check" will be created. If "Enter data manually", the button "Check" will disappear if exists.
Could you, please, help me with it?
Update (HTML):
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<title>Demo Web App</title>
</head>
<body>
<h1>Template Creator Bot</h1> <br> <br>
<script>
...
</script>
<div id='change'>
<select name="docs" id="selectedTemplate">
<option value="Order">Order</option>
<option value="Complaint">Complaint</option>
<option value="Other">Other</option>
</select>
<button onclick="addElements()">Next</button>
</div>
</body>
</html>
It would be better if you made the button element once and just toggled its visibility on demand.
There are also better strategies to compose dynamic html on your DOM instead of using innerHTML like using <template> or creating elements with document.createElement().
By the way, addressing specifically your issue here, I made a demo that adds the button in the main addElements() routine, and two functions: showButton() and hideButton() that will be called by the click event handlers added to the two radio options.
addElements();
function showButton(){
const target = document.getElementById('check');
if (target.classList.contains('hide'))
target.classList.remove('hide');
}
function hideButton(){
const target = document.getElementById('check');
if (!target.classList.contains('hide'))
document.getElementById('check').classList.add('hide');
}
function addElements(){
var added0 = "<p>Choose the filling method:</p><br>";
var added1 = "<input type='radio' value='Auto' id='auto' name='auto_manual'>I have ID</input>";
var added2 = "<input type='radio' value='Manually' id='manual' name='auto_manual'>Enter data manually</input><br>";
var added3 = "<p>Identification Code</p><br><input type=text id='ID'><br>";
var added4 = "<p>Enter your email address:</p><br><input type='email' id='mail' autocomplete='on'></input><br>";
var added5 = "<button onclick='fillIn()'>Continue</button>";
var added6 = "<button class='hide' onclick='checkData()' id='check'>Check</button>";
document.body.innerHTML +=
"<div id='added'>" + added0 + added1 + added2 + added3 + added4 + added5 + added6 + "</div>";
/*
Here adding the click event listener for the two radio options..
in the rest of your generated html you used the approach of defining handlers on html
so it's not clear why here you opted to do it programmatically for the radio options..
Anyway I only slightly changed the approach using addEventListener instead.
*/
var f0 = document.getElementById('auto');
var f1 = document.getElementById('manual');
f0.addEventListener('click', function() { showButton();});
f1.addEventListener('click', function() { hideButton();});
}
.hide{
display: none;
}
input[type=radio]{
cursor: pointer;
}

How to put required validation in javascript innerhtml input box

function edit_row(id)
{
document.getElementById("monthly_val"+id).innerHTML="<input type='text' id='monthly_text"+id+"' value='"+monthly+"' onkeyup='this.value=Comma(this.value)' 'required'>";
}
The above code is an example of my input field and i want to put required validation so that the data will not be saved when the field is empty.
Try this...
var a = document.getElementById("monthly"+id),
b = document.createElement("INPUT");
b.setAttribute("pattern", "regexp string");
b.setAttribute("formnovalidate", " false");
b.setAttribute("type", "text");
//add other attributes
a.appendChild(b);
/*
Just replace the regexp string*/
if you have textbox id then you can easily find and then you can check input empty or not. you need use this process before saving data.
document.getElementById("monthly_val" + id).innerHTML = "<input type='text' id='monthly_text" + id + "' value='" + monthly + "' onkeyup='this.value=Comma(this.value)'>";
if ($('#monthly_text' + id + '').val() == '') { alert('wala'); }
use this. it helps you

SessionStorage issues, jQuery

Please help, faced with difficulties while trying to store data via sessionStorage
I have a simple form and desire to read data from form inputs and append it to the table and store that data in the table during the session
HTML
Name: <input type="text" id="name"/>
Email: <input type="text" id="email"/>
Tel: <input type="text" id="tel"/>
Street: <input type="text" id="street"/>
City: <input type="text" id="city"/>
State: <input type="text" id="state"/>
Zip: <input type="text" id="zip"/>
<button id="myForm" type="button">Add Costumer</button>
JS
$(document).ready(function(){
if(sessionStorage.length>0){
display()
}
})
$("#myForm").on("click", function(){
save()
$(":input").val(""); //clean fields of the form
});
function save(){
var name= $("#name").val();
var email= $("#email").val();
var telephone= $("#tel").val();
var street= $("#street").val();
var city= $("#city").val();
var state= $("#state").val();
var zip= $("#zip").val();
var inputArray = [name, email, telephone, street, city, state, zip];
for(i in inputArray){//storing input data
sessionStorage.setItem(i, inputArray[i])
};
display()
}
function display(){
var restoredName = sessionStorage.getItem(0);
var restoredEmail = sessionStorage.getItem(1);
var restoredTel = sessionStorage.getItem(2);
var restoredStreet = sessionStorage.getItem(3);
var restoredCity = sessionStorage.getItem(4);
var restoredState = sessionStorage.getItem(5);
var restoredZip = sessionStorage.getItem(6);
//append filled information from the form to the table and 2 buttons - Update and Remove
$("#listContent table").append( "<tr>" +
"<td>" + restoredName + "</td>"+
"<td>" + restoredEmail + "</td>"+
"<td>" + restoredTel + "</td>"+
"<td>" + restoredStreet + "</td>"+
"<td>" + restoredCity + "</td>"+
"<td>" + restoredState + "</td>"+
"<td>" + restoredZip + "</td>"+
"<td>" + "<button>Update</button>" + "</td>" +
"<td>" + "<button>Remove</button>" + "</td>" +
"</tr>");
}
the issue is that only the last submit is stored and displayed in table, but not all submits that were performed during the session
I guess sessionStorage is rewrited every time user clicks submit with new input values. And I have no idea how to increase the storage with every new submit.
Please advise, how to fix this issue? thanks
The code you gave just write the input array in session storage.
If you want to store several inputArrays in session storage, the best way would be to generate an identifier, and to serialize your input array to store it.
The way you generate the identifier for your array is up to you. To serialize it, you could use
var dataToStore = JSON.stringify(inputArray);
Then you would use
sessionStorage.setItem(myGeneratedId, dataToStore);
Finally to read your data:
var myArraySerialized = sessionStorage.getItem(myGeneratedId);
var myArray = JSON.parse( myArraySerialized );
As JSON parse may fail it is a good idea to try...catch it.
The question is: Why are you using indexes? sessionStorage is a key-value object and the best way to use it is to set proper key, that you can access it later.
sessionStorage.setValue('Key', 'Value');
If you want to save everything from the array you'll need to stringify it:
sessionStorage.setValue('KeyName' JSON.stringify(Data));
And when you get it back use JSON.parse()
var dataArray=JSON.parse(SessionStorage.getItem('KeyName'));

Make checkboxes act like radio buttons in duplicatable input fields

I'm creating a duplicate-able div's containing check box's, at the moment on the original set of inputs, the check boxes act like radio buttons, but when duplicated it still only works on the first not the second.
Also on submit it only returns one value for the original form in the console, but no value for any duplicates.
Any help greatly appreciated.
JS Fiddle: http://jsfiddle.net/dawidvdh/EEd7c/
jQuery:
//Clone Tracking
var g_counter = 1;
var d_counter = 1;
var dependant = ["dependant"];
var group;
//Clone Tracking
//General Variables
var relation_input_groups = ["relation-group-1"];
//General Variables
//Generate variables
var relation_fields=[0];
var relation_input ="<label>Spouse</label>"+
"<input type='checkbox' value='spouse' class='relationship' name='relationship' />" +
"<label>own child</label>"+
"<input type='checkbox' value='ownchild' class='relationship' name='relationship' />" +
"<label>adopted</label>"+
"<input type='checkbox' value='adopted' class='relationship' name='relationship' />" +
"<label>stepchild</label>"+
"<input type='checkbox' value='stepchild' class='relationship' name='relationship' />" +
"<label>parent</label>"+
"<input type='checkbox' value='parent' class='relationship' name='relationship' />" +
"<label>inlaw</label>"+
"<input type='checkbox' value='inlaw' class='relationship' name='relationship' />" +
"<label>brother</label>"+
"<input type='checkbox' value='brother' class='relationship' name='relationship' />" +
"<label>other</label>"+
"<input type='checkbox' value='other' class='relationship' name='relationship' />";
//Generate variables
jQuery(document).ready(function(e)
{
//populate jquery generated fields
jQuery(relation_fields).each(function()
{
jQuery(relation_input).appendTo('#relation-group-1');
});
//populate jquery generated fields
//Cloning Function
jQuery('#clone').click(function()
{
clone_dependant();
});
function clone_dependant()
{
// Store the value of the previous Id to insert the cloned div..
var oldId = g_counter;
g_counter++;
currentdep ='dependant-'+g_counter;
// Clone the Dependant Div and set a new id
var $clonedDiv = jQuery('#dependant-1').clone(false).attr('id', 'dependant-'+g_counter);
var relation_newDiv = 'relation-group-'+ g_counter;
// Find div's inside the cloned object and set a new id's
$clonedDiv.find('#relation-group-1').attr('id',"relation-group-" + g_counter );
// You don't need to Loop thru the inputs to set the value
$clonedDiv.find('input').val('');
$clonedDiv.find('input:checkbox').removeAttr('checked');
// Insert the cloned object
$clonedDiv.insertAfter("#dependant-" + oldId);
relation_input_groups.push(relation_newDiv);
}
//Cloning Function
//Validation
//submit function
var $unique = $('input[type="checkbox"]');
$unique.click(function()
{
$unique.removeAttr('checked');
$(this).attr('checked', true);
});
var result = {};
var dependants;
var dep_counter = 0;
jQuery('#submit').click(function()
{
jQuery('.dependant').each(function(k, v)
{
dep_counter++
dependants = {};
result['dependant'+dep_counter] = [dependants];
dependants['relationship'] = $(v).find('.relationship:checked').val();
});
var jsonData = JSON.stringify(result);
console.log(jsonData);
});
});
and the HTML:
<div id="dependant-1" class="dependant">
<div id="label">relationship:</div> <div id="relation-group-1"></div>
</div>
<button id="clone">clone</button>
<button id="submit">submit</button>
Thanks in advance :)
See this : http://jsfiddle.net/EEd7c/1/
var $unique = $('input[type="checkbox"]');
$unique.live("click", function() {
$(this).siblings().removeAttr('checked');
$(this).attr('checked', true);
});
Yet Live is deprecated...
Or
$(document).on("click", 'input[type="checkbox"]', function() {
$(this).siblings().removeAttr('checked');
$(this).attr('checked', true);
});
The reason why it does not work is you are not attaching the click events to the new cloned elements.
$(document).on("click", 'input[type="checkbox"]', function() {
jQuery(this).siblings(":checked").removeAttr('checked');
});
var $unique = $('input[type="checkbox"]');
$unique.live('click',function() {
$(this).closest('div').find('input[type="checkbox"]').removeAttr('checked');
$(this).attr('checked', true);
});
Using live to register the event handler to dynamically created elements. $unique variable will contain only the initial set of checkboxes.

jquery uncertain error?

i am using this code to access all the hidden elements from a form:
function get_hidden_val(ids,form_id)
{
var get_check_val = document.getElementById(ids);
if(get_check_val.checked){
var div = $('<div></div>')
.appendTo('form#bulk_add_cart')
.attr('id',"bulk_"+form_id)
$("form#" +form_id).find('input[type="hidden"]').each(function(){
var value =$(this).val();
var name = $(this).attr("name");
var tags = "<input type='hidden' value='" + value + "' name='"+name+"'>";
$('div#' +form_id).append(tags);
});
}
else
{
$("form#bulk_add_cart").find('div#' +form_id).remove();
}
}
My problem is when I click the first checkbox it give me the result but when i click the second checkbox it doesn't and also the another problem is when i click first checkbox it shows total hidden elements but when i second time checked it, it show 4 less ?
Please suggest a solution.
Thanks
#user704302: Missing >, update var tags to --
var tags = "<input type='hidden' value='" + value + "' id='"+id+"'>";

Categories