I tried to build a validation form using JavaScript which handles these errors:
The Name field should not be empty
The phone number field can contain only numbers (exactly 10 numbers)
One option should be selected (radio)
At least one car from checkboxes is selected and at max 3 cars
But the problem with my code is it has not worked in all cases. I mean if I selected submit it shows me the error message just in the name field, not on other fields.
For example here -
here my HTML code
<body>
<div class="MainBackground">
<h1 id="title">Car Company</h1>
</div>
<div class="cars">
<form method="POST" name="form-car" id="form-car">
<p id="decription"> users' request</p>
<div id="name_div">
<label id="lable-name" for="name">Name: </label>
<input id="name" type="text" name="yourName" placeholder="Enter your name"> <br>
<span id="errorname"></span>
</div>
<br> <br>
<label id="lable-Phone" for="Phone">Phone:</label>
<input id="phone" type="text" name="phonefild" placeholder="Enter your Phone Number"> <br>
<span id="errorpass"></span>
<br> <br>
<label id="lable-age" for="Age">Age:</label>
<br>
<input type="radio" name="group1" value="T"> 18-25
<br>
<input type="radio" name="group1" value="A"> 26-35
<br>
<input type="radio" name="group1" value="O"> 35-55
<br>
<input type="radio" name="group1" value="AO"> 36-80
<br>
<input type="radio" name="group1" value="VO"> 80-95
<br>
<span id="radioerorr"></span>
<br> <br>
<label for="check">Choice cars to tested</label>
<br>
<input class="checkbox" type="checkbox" id="option1" name="car1" value="BMW">
<label for="vehicle1">BMW</label><br>
<input class="checkbox" type="checkbox" id="option2" name="car2" value="Ferrari">
<label for="vehicle2">Ferrari</label><br>
<input checkbox="checkbox" type="checkbox" id="option3" name="car3" value="Ford">
<label for="vehicle3">Ford</label><br>
<input class="checkbox" type="checkbox" id="option4" name="car4" value="Audi">
<label for="vehicle4">Audi</label><br>
<input class="checkbox" type="checkbox" id="option5" name="car5" value="Cadillac">
<label for="vehicle5">Cadillac</label><br>
<span id="checkboxerorr"></span>
<br> <br>
<div class="center">
<button onclick="return validition()" id="submit" type="submit" name="button">submit</button>
<button id="reset" type="reset" name="button">reset</button>
</div>
</form>
</div>
And here my javascript code
function validition() {
var phoneinpute = document.getElementById('phone').value;
var radios = document.getElementsByTagName('input');
var value;
var inputs = document.getElementsByTagName("input");
var count1 = 0;
var count2 = 0;
var regex = /(5|0)([0-9]{8})$/;
if (document.getElementById('name').value == "") {
document.getElementById('errorname').innerHTML = "name should not be empty";
document.getElementById('name').style.borderColor = "red";
return false;
} else if (document.getElementById('name').value != "") {
document.getElementById('errorname').innerHTML = "";
document.getElementById('name').style.borderColor = "green";
}
if (regex.test(phoneinpute)) {
document.getElementById('errorpass').innerHTML = "";
document.getElementById('phone').style.borderColor = "green";
//return true;
} else {
document.getElementById('errorpass').innerHTML = "Invalide phone number";
document.getElementById('phone').style.borderColor = "red";
return false;
}
for (var i = 0; i < radios.length; i++) {
if (radios[i].type == "radio" && radios[i].checked) {
count1++;
}
if (count1 == 1) {
document.getElementById('radioerorr').innerHTML = "";
break;
} else {
document.getElementById('radioerorr').innerHTML = "one option should be selected";
return false
}
}
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox" && inputs[i].checked) {
count2++;
}
if (count2 > 3 || count2 == 0) {
document.getElementById('checkboxerorr').innerHTML = "please choose at least one car and at most 3 cars";
return false
} else {
document.getElementById('checkboxerorr').innerHTML = "";
}
}
You are using return statements in your validations, if you return from your 1st validation (name box), the other code blocks will not execute. Use a local boolean to determine your return type and return that at the end of your function, that way, all of your validation code runs. Also, your radio button and checkbox validation logic is flawed, you set an error message on each iteration of the loop if count1 or count2 doesn't meet your conditions. Change it to something like the following:
function validition() {
let valid = true; //local boolean to return at the end of your function
var phoneinpute = document.getElementById('phone').value;
var radios = document.getElementsByTagName('input');
var value;
var inputs = document.getElementsByTagName("input");
var count1 = 0;
var count2 = 0;
var regex = /(5|0)([0-9]{8})$/;
//Name validation
if (document.getElementById('name').value == "") {
document.getElementById('errorname').innerHTML = "name should not be empty";
document.getElementById('name').style.borderColor = "red";
valid = false;
} else if (document.getElementById('name').value != "") {
document.getElementById('errorname').innerHTML = "";
document.getElementById('name').style.borderColor = "green";
}
//Phone number validation
if (regex.test(phoneinpute)) {
document.getElementById('errorpass').innerHTML = "";
document.getElementById('phone').style.borderColor = "green";
} else {
document.getElementById('errorpass').innerHTML = "Invalide phone number";
document.getElementById('phone').style.borderColor = "red";
valid = false;
}
//Radio button validation
for (var i = 0; i < radios.length; i++) {
if (radios[i].type == "radio" && radios[i].checked) {
count1++;
}
if (count1 == 1) {
document.getElementById('radioerorr').innerHTML = "";
break;
}
}
//check to see if you had a checked radio button, if not, add error
//and mark local boolean as false
if(count1 < 1){
document.getElementById('radioerorr').innerHTML = "one option should be selected";
valid = false;
}
//Checkbox validation
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox" && inputs[i].checked) {
count2++;
}
}
//Do your checkbox validation after the for loop
if (count2 > 3 || count2 == 0) {
document.getElementById('checkboxerorr').innerHTML = "please choose at least one car and at most 3 cars";
valid = false;
} else {
document.getElementById('checkboxerorr').innerHTML = "";
}
//return your local boolean value
return valid;
}
Related
how to validate all the section by at least choose one option. with my code, it just show the first "please select 1". so how to edit the code to show the all requirement like "pls choose at least one" at beside the section or below the submit button. I'm just a beginner, now learning for JavaScript. You are prefer to done with some code editor, to have a better understand for beginner. Here is my code :
var person = [];
person["person1"]=1;
person["person2"]=2;
person["person3"]=3;
person["person4"]=4;
person["person5"]=5;
var elec = [];
elec["elecuse"] = 0;
elec["elec1"] = 100*454.58;
elec["elec2"] = 200*454.58;
elec["elec3"] = 300*454.58;
elec["elec4"] = 400*454.58;
elec["elec5"] = 500*454.58;
elec["elec6"] = 600*454.58;
elec["elec7"] = 700*454.58;
elec["elec8"] = 800*454.58;
elec["elec9"] = 900*454.58;
function getNumberperson()
{
var numberperson=0;
var theForm = document.forms["energyform"];
var selectedPerson = theForm.elements["selectedperson"];
for(var i = 0; i < selectedPerson.length; i++)
{
if(selectedPerson[i].checked)
{
numberperson = person[selectedPerson[i].value];
}
}
return numberperson;
}
function getElectotal()
{
var electotal=0;
var theForm = document.forms["energyform"];
var selectedElec = theForm.elements["electricity"];
electotal = elec[selectedElec.value];
return electotal;
}
function recyclealu()
{
var recyclealu=0;
var theForm = document.forms["energyform"];
var yesalu = theForm.elements["yesalu"];
if(yesalu.checked==true)
{
recyclealu=-89.38;
}
return recyclealu;
}
function recycleplas()
{
var recycleplas=0;
var theForm = document.forms["energyform"];
var yesplas = theForm.elements["yesplas"];
if(yesplas.checked==true)
{
recycleplas=-35.56;
}
return recycleplas;
}
function checkAllRecycles() {
const recycleBoxes = document.querySelectorAll('input[type="checkbox"]');
if (recycleBoxes) {
recycleBoxes.forEach((recycleBox) => {
if (!recycleBox.checked) {
recycleBox.checked = 'checked';
}
})
}
calculateTotal();
}
function calculateTotal()
{
var totalco = getNumberperson()*getElectotal() + recyclealu() + recycleplas();
//display the result
document.getElementById('totalConsumption').innerHTML = +totalco;
}
//add a function to hide the result on page loading at the start
function hideTotal()
{
document.getElementById('totalConsumption').innerHTML = "0";
}
function vpeople()
{
var cp = document.getElementsByName('selectedperson');
for (var i = 0; i < cp.length; i++)
{
if (cp[i].type == 'radio')
{
if (cp[i].checked) {return true}
}
}
return false;
}
function velec()
{
var ce = document.getElementsByName('electricity');
for (var i = 0; i < ce.length; i++)
{
if (ce[i].type == 'radio')
{
if (ce[i].checked) {return true}
}
}
return false;
}
function vrcyalu()
{
var crcyalu = document.getElementsByName('yesalu');
for (var i = 0; i < crcyalu.length; i++)
{
if (crcyalu[i].type == 'checkbox')
{
if (crcyalu[i].checked) {return true}
}
}
return false;
}
function vrcyplas()
{
var crcyplas = document.getElementsByName('yesalu');
for (var i = 0; i < crcyplas.length; i++)
{
if (crcyplas[i].type == 'checkbox')
{
if (crcyplas[i].checked) {return true}
}
}
return false;
}
function allvalidate()
{
if(!vpeople())
{
alert("Please select1");
return false;
}
return true;
if(!vwaste())
{
alert("Please select2");
return false;
}
return true;
if(!velec())
{
alert("Please select3");
return false;
}
return true;
if(!vrcyalu())
{
alert("Please select4");
return false;
}
return true;
if(!vrcyplas())
{
alert("Please select5");
return false;
}
return true;
checkAllRecycles;
}
<body onload='hideTotal()'>
<div id="all">
<form action="/action_page.php" id="energyform" onsubmit="return false;">
<div>
<div class="cont_order">
<fieldset>
<legend>Carbon Footprint Calculator</legend>
<label >Number of Person Live in Household</label><br/>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person1" onclick="calculateTotal()" />1 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person2" onclick="calculateTotal()" />2 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person3" onclick="calculateTotal()" />3 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person4" onclick="calculateTotal()" />4 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person5" onclick="calculateTotal()" />5 </label>
<br/><br/>
<label><i class="fa fa-flash"></i>Energy Consumption Per Month</label>
<br/>
<label> Electricity    </label>
<select id="electricity" name='electricity' onchange="calculateTotal()">
<option value="elecuse">0</option>
<option value="elec1">100</option>
<option value="elec2">200</option>
<option value="elec3">300</option>
<option value="elec4">400</option>
<option value="elec5">500</option>
<option value="elec6">600</option>
<option value="elec7">700</option>
<option value="elec8">800</option>
<option value="elec9">900</option>
</select>
<br/><br/>
<label><i class="fa fa-flash"></i>Recycle </label>
<br/>
<label for='yesalu' class="alu"> Aluminium and Steel  </label>
<input type="checkbox" id="yesalu" name='yesalu' onclick="calculateTotal()" />
<br/>
<label for='yesplas' class="plas"> Plastic                          </label>
<input type="checkbox" id="yesplas" name='yesplas' onclick="calculateTotal()" />
<br/>
<button type="button" onclick="checkAllRecycles()">Select All</button>
<br/>
<p>Total CO2 produced per year per household:</p>
<div id="totalConsumption">0</div>
</fieldset>
</div>
<input type='submit' id='submit' value='Submit' onclick="allvalidate()" />
<input type='reset' id='reset' value='Reset' onclick="hideTotal()" />
</div>
</form>
</div>
</body>
thx you very much for helping me, stay safe.
hello please check this page :
https://stackoverflow.com/questions/13060313/checking-if-at-least-one-radio-button-has-been-selected-javascript
So I have this piece of HTML and JavaScript
function validate() {
const tabs = document.getElementsByClassName("tab");
const input = tabs[currentTab].querySelectorAll("input[type=tel], input[type=text], input[type=time], input[type=number], input[type=email]");
const radio = tabs[currentTab].querySelectorAll("input[type=radio]");
const select = tabs[currentTab].getElementsByTagName("select");
let valid = true;
if (radio.length == 0) {
for (let i = 0; i < input.length; i++) {
if (input[i].value == "") {
valid = false;
break;
}
}
for (let i = 0; i < select.length; i++) {
if (select[i].value == "") {
valid = false;
break;
}
}
} else if (radio[0].name == "phnum" && radio[0].checked) {
if (input[0].value == "" || input[1].value == "") {
valid = false;
}
} else if (radio[1].name == "phnum" && radio[1].checked) {
if (input[0].value == "" || input[1].value == "" || input[2].value == "") {
valid = false;
}
}
if (valid) {
document.getElementById("next").className = "prevNext";
}
}
<span id="radio">
<label for="phnum1" class="radio-container">
<input type="radio" name="phnum" id="phnum1" value="1" onchange="displayPhone(this);">1 Number
<span class="radio"></span>
</label>
<label for="phnum2" class="radio-container">
<input type="radio" name="phnum" id="phnum2" value="2" onchange="displayPhone(this);">2 Numbers
<span class="radio"></span>
</label>
<label for="phnum3" class="radio-container">
<input type="radio" name="phnum" id="phnum3" value="3" onchange="displayPhone(this);">3 Numbers
<span class="radio"></span>
</label>
</span>
</p><br>
<p id="ph1" class="disable">
<label for="phone-number1">Add a Phone Number: </label><input type="tel" name="phone-number1" id="phone-number1" class="input" placeholder="Add A Phone Number" required oninput="validate();">
</p>
<p id="ph2" class="disable">
<label for="phone-number2">Add a Phone Number: </label><input type="tel" name="phone-number2" id="phone-number2" class="input" placeholder="Add A Phone Number" required onchange="validate();">
</p>
<p id="ph3" class="disable">
<label for="phone-number3">Add a Phone Number: </label><input type="tel" name="phone-number3" id="phone-number3" class="input" placeholder="Add A Phone Number" required onchange="validate();">
</p>
that handles the input added by the user to make a button clickable if all necessary data is added. the problem is when i delete inside the input with back arrow key(the one above enter) the button remains active even if the condition for its activation no longer applies.
thank you guys for your time and help i really do appreciate it. :D
One thing I see - you're setting the class name if valid == true via document.getElementById("next").className = "prevNext";.
But nowhere are you removing that class name if valid == false.
That's probably why you aren't seeing the button disappear when you empty out the fields (if I understand your problem correctly).
if (!valid) { document.getElementById("next").className = ""; } is a quick and dirty way to get what you need.
This is my javascript function.
function shortCutValidation() {
//var txtObjList = document.getElementsByTagName("input");
//for (var i = 0; i < txtObjList.length; i++) {
// if (txtObjList[i].getAttribute("type") == "text" && this.value != "") {
// // success for i+1 textbox
// }
// else {
// $(txtObjList).closest(".errortext").css("display", "block");
// }
//}
var data = document.getElementsByClassName("w-input");
if (data.length > 0) {
console.log("yes you are in");
for (var i = 0; i < data.length; i++) {
var myvalue = document.getElementsByClassName("w-input");
if (myvalue[i].value == '') {
console.log("yes value is empty"+myvalue[i].value);
$(myvalue[i]).next(".errortext").css("display", "block");
}
else {
console.log("thats ok");
$(data[i]).next(".errortext").css("display", "none");
}
console.log(i);
}
}
}
This is my html code.
<div class="myformgrp w-clearfix w-col">
<div class="w-col w-col-2 w-col-medium-3 w-col-small-12">
<label for="firstname" class="verticle-centerinline">First Name </label>
</div>
<div class="w-col w-col-10 w-col-medium-9 w-col-small-12">
<input type="hidden" id="id" name="id" value="" />
<input type="text" class="w-input" name="fname" id="fname" />
<div class="errortext" style="display:none">required field</div>
</div>
</div>
<div class="myformgrp w-clearfix w-col">
<div class="w-col w-col-2 w-col-medium-3 w-col-small-12">
<label for="firstname" class="verticle-centerinline">Last Name </label>
</div>
<div class="w-col w-col-10 w-col-medium-9 w-col-small-12">
<input type="text" class="w-input" name="lname" id="lname" /><br />
<div class="errortext" style="display:none">required field</div>
</div>
</div>
The problem is that I can't validate all the text box at once
but my for loop is working as expected.
I use jQuery to call the shortCutValidation function.
All I want is when my blur event is called to validate all the text box at once and the error massage should be displayed.
Try This
function validateFormOnSubmit(contact) {
reason = "";
reason += validateName(contact.name);
reason += validateEmail(contact.email);
reason += validatePhone(contact.phone);
reason += validatePet(contact.pet);
reason += validateNumber(contact.number);
reason += validateDisclaimer(contact.disclaimer);
if (reason.length > 0) {
return false;
} else {
return false;
}
}
// validate required fields
function validateName(name) {
var error = "";
if (name.value.length == 0) {
name.style.background = 'Red';
document.getElementById('name-error').innerHTML = "The required field has not been filled in";
var error = "1";
} else {
name.style.background = 'White';
document.getElementById('name-error').innerHTML = '';
}
return error;
}
// validate email as required field and format
function trim(s) {
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error = "";
var temail = trim(email.value); // value of field with whitespace trimmed off
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (email.value == "") {
email.style.background = 'Red';
document.getElementById('email-error').innerHTML = "Please enter an email address.";
var error = "2";
} else if (!emailFilter.test(temail)) { //test email for illegal characters
email.style.background = 'Red';
document.getElementById('email-error').innerHTML = "Please enter a valid email address.";
var error = "3";
} else if (email.value.match(illegalChars)) {
email.style.background = 'Red';
var error = "4";
document.getElementById('email-error').innerHTML = "Email contains invalid characters.";
} else {
email.style.background = 'White';
document.getElementById('email-error').innerHTML = '';
}
return error;
}
// validate phone for required and format
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('phone-error').innerHTML = "Please enter a phone number";
phone.style.background = 'Red';
var error = '6';
} else if (isNaN(parseInt(stripped))) {
var error = "5";
document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters.";
phone.style.background = 'Red';
} else if (stripped.length < 10) {
var error = "6";
document.getElementById('phone-error').innerHTML = "The phone number is too short.";
phone.style.background = 'Red';
} else {
phone.style.background = 'White';
document.getElementById('phone-error').innerHTML = '';
}
return error;
}
function validatePet(pet) {
if ((contact.pet[0].checked == false) && (contact.pet[1].checked == false) && (contact.pet[2].checked == false)) {
document.getElementById('pet-error').innerHTML = "Pet required";
var error = "2";
} else {
document.getElementById('pet-error').innerHTML = '';
}
return error;
}
function validateNumber(number) {
var num = document.forms["contact"]["number"];
var y = num.value;
if (!isNaN(y)) {
//alert('va');
if (y < 0 || y > 50) {
//Wrong
number.style.background = 'Red';
document.getElementById("number-error").innerHTML = "Must be between 0 and 50.";
var error = "10";
} else {
//Correct
number.style.background = 'White';
document.getElementById("number-error").innerHTML = "";
}
return error;
} else {
document.getElementById("number-error").innerHTML = "Must be a number.";
var error = "3";
}
return error;
}
function validateDisclaimer(disclaimer) {
var error = "";
if (document.getElementById("disclaimer").checked === false) {
document.getElementById('disclaimer-error').innerHTML = "Required";
var error = "4";
} else {
document.getElementById('disclaimer-error').innerHTML = '';
}
return error;
}
.error {
color: #990000;
}
input::-webkit-input-placeholder {
color: white !important;
}
input:-moz-placeholder { /* Firefox 18- */
color: white !important;
}
input::-moz-placeholder { /* Firefox 19+ */
color: white !important;
}
input:-ms-input-placeholder {
color: white !important;
}
<form id="contact" name="contact" onsubmit="return validateFormOnSubmit(this)" action="" method="post">
<div>
<label>First Name</label>
<input placeholder="First Name" type="text" name="name" id="name" tabindex="1" autofocus />
<div id="name-error" class="error"></div>
</div>
<div>
<label>Nickname</label>
<input placeholder="Nickname" type="text" name="nickname" id="nickname" tabindex="2" autofocus />
</div>
<div>
<label>Email</label>
<input placeholder="Email" type="email" name="email" id="email" tabindex="3" autofocus />
<div id="email-error" class="error"></div>
</div>
<div>
<label>Phone</label>
<input placeholder="Phone" type="tel" name="phone" id="phone" tabindex="4" autofocus />
<div id="phone-error" class="error"></div>
</div>
<div>
<label>I prefer</label>
<input type="radio" name="pet" id="Dogs" tabindex="5" autofocus />Dogs
<input type="radio" name="pet" id="Cats" tabindex="6" autofocus />Cats
<input type="radio" name="pet" id="Neither" tabindex="7" autofocus />Neither
<div id="pet-error" class="error"></div>
</div>
<div>
<label>My favorite number between 1 and 50</label>
<input placeholder="Favorite number between 1 and 50" type="text" name="number" id="number" tabindex="8" autofocus />
<div id="number-error" class="error"></div>
</div>
<div>
<label>Disclaimer</label>
<input type="checkbox" name="disclaimer" id="disclaimer" tabindex="9" autofocus />I confirm that all the above information is true.
<div id="disclaimer-error" class="error"></div>
</div>
<div>
<button type="submit" name="submit" id="submit" tabindex="10">Send</button>
</div>
</form>
Happy Coding
I have a group of checkbox that indicates a house spaces, the last checkbox is for the house all space. I want to disable and uncheck other checkboxes when I check "All space" checkbox. what is its javascript code?
<html>
<label class="input-group-addon">
<input type="checkbox" value="1" id="rndr-lobby"
name="rndr-int-options" />
Lobby </label>
<label class="input-group-addon">
<input type="checkbox" value="1.4" id="rndr-room"
name="rndr-int-options" />
Room </label>
<label class="input-group-addon">
<input type="checkbox" value="1.5" id="rndr-living" name="rndr-int-options" />
Living </label>
<label class="input-group-addon">
<input type="checkbox" value="1.6" id="rndr-wc" name="rndr-int-options" />
WC </label>
<label class="input-group-addon">
<input type="checkbox" value="1.3" id="rndr-kitchen" name="rndr-int-options" />
Kitchen </label>
<label class="input-group-addon">
<input type="checkbox" value="1.3" id="rndr-office" name="rndr-int-options" />
Office </label>
<label class="input-group-addon">
<input type="checkbox" value="1.3" id="rndr-saloon" name="rndr-int-options" />
Saloon </label>
<label class="input-group-addon">
<input type="checkbox" value="1.3" id="rndr-all" name="rndr-int-options" onchange="AllCk();"/>
All sapce</label>
</html>
<script>
document.getElementById('rndr-all').onchange = function() {AllCk();};
var AllCk = function () {
var RndrLob = document.getElementById("rndr-lobby"),
RndrRoo = document.getElementById("rndr-room"),
RndrLiv = document.getElementById("rndr-living"),
RndrWc = document.getElementById("rndr-wc"),
RndrKit = document.getElementById("rndr-kitchen"),
RndrOff = document.getElementById("rndr-office"),
RndrSal = document.getElementById("rndr-saloon"),
RndrAll = document.getElementById('rnder-all').checked;
if (RndrAll === true) {
RndrLob.disabled = true; RndrLob.checked = false;
RndrRoo.disabled = true; RndrRoo.checked = false;
RndrLiv.disabled = true; RndrLiv.checked = false;
RndrWc.disabled = true; RndrWc.checked = false;
RndrKit.disabled = true; RndrKit.checked = false;
RndrOff.disabled = true; RndrOff.checked = false;
RndrSal.disabled = true; RndrSal.checked = false;
RndrAll.disabled = true; RndrAll.checked = false;
}
};
</script>
function AllCk() {
if (document.querySelector('#rndr-all').checked) {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox") {
if (inputs[i].id != "rndr-all") {
inputs[i].checked = false;
inputs[i].disabled = true;
}
}
}
} else {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox") {
if (inputs[i].id != "rndr-all") {
inputs[i].disabled = false;
}
}
}
}
}
// By Jquery, Put it in your AllCk() function
$("input[id='rndr-all']").is(":checked") ?
$("input[name='rndr-int-options']").not("#rndr-all").prop('checked', false).prop('disabled', true) :
$("input[name='rndr-int-options']").not("#rndr-all").prop('disabled', false);
Hope it helps you !
Assuming the fact that All sapce checkbox is the last checkbox in the series, your AllCk() function should be like this:
function AllCk(){
var spaces = document.getElementsByName("rndr-int-options");
for (var i = 0; i < spaces.length - 1; i++) {
if(spaces[i].checked)
spaces[i].checked = false;
}
}
I'm very new to Javascript and Jquery and am attempting to use this script externally to calculate the value of a users selections (Radio buttons and Checkboxes) and then output the value of the function into my HTML page (id cost) by pressing a button (id submit). This is what I have so far, I would be very appreciative if someone could help me understand why it isn't working.
function add() {
var val1 = 0;
for (i = 0; i < document.form1."radio-choice-v-1"; i++)
{
if (document.form1."radio-choice-v-1"[i].checked === true)
{
val1 = document.form1."radio-choice-v-1"[i].value;
}
}
var val2 = 0;
for (i = 0; i < document.form2."radio-choice-v-2"; i++)
{
if (document.form2.radio-"choice-v-2"[i].checked === true)
{
val2 = document.form2."radio-choice-v-2"[i].value;
}
}
var val3 = 0;
for (i = 0; i < document.form3."radio-choice-v-3"; i++)
{
if (document.form3."radio-choice-v-3"[i].checked === true)
{
val3 = document."form3.radio-choice-v-3"[i].value;
}
}
var val4 = 0;
for (i = 0; i < document.form4."radio-choice-v-4"; i++)
{
if (document.form4."radio-choice-v-4"[i].checked === true)
{
val4 = document.form4."radio-choice-v-4"[i].value;
}
}
var val5 = 0;
for (i = 0; i < document.form5."radio-choice-v-5"; i++)
{
if (document.form5."radio-choice-v-5"[i].checked === true)
{
val5 = document.form5."radio-choice-v-5"[i].value;
}
}
var val6 = 0;
for( i = 0; i < document.form6."checkselection"; i++ )
{
val6 = document.form6."checkselection"[i].value;
}
$("cost").html(" = " + (val1 + val2 + val3 + val4 + val5 + val6));
}
<form name="form1" id="form1">
<fieldset data-role="controlgroup">
<legend>Please select a case:</legend>
<input id="radio-choice-v-1a" name="radio-choice-v-1" value="40" CHECKED="checked" type="radio">
<label for="radio-choice-v-1a">Choice 1 (£40)</label>
<input id="radio-choice-v-1b" name="radio-choice-v-1" value="45" type="radio">
<label for="radio-choice-v-1b">Choice 2 (£45)</label>
<input id="radio-choice-v-1c" name="radio-choice-v-1" value="140" type="radio">
<label for="radio-choice-v-1c">Choice 3 (£140)</label>
</fieldset>
</form>
<form name="form6" id="form6">
<fieldset data-role="controlgroup">
<legend>Select your extras</legend>
<input type="Checkbox" name="checkselection" id="checkbox-extra-1" value="20">
<label for="checkbox-extra-1"> Selection 1 (£20) (recommended)</label>
<input type="Checkbox" name="checkselection" id="checkbox-extra-2" value="12">
<label for="checkbox-extra-2">Selection 2 (£12)</label>
<input type="Checkbox" name="checkselection" id="checkbox-extra-3" value="4">
<label for="checkbox-extra-3">Selection 3 (£4)</label>
<input type="Checkbox" name="checkselection" id="checkbox-extra-4" value="30">
<label for="checkbox-extra-4">Selection 4 (£30)</label>
</fieldset>
</form>
<form>
<input id="submit" type="button" value="Submit" onclick="add();">
</form>
£<u id="cost"></u>
There where quite a few problems with your code. Please have a look at the working example I created on JSFiddle for you:
http://jsfiddle.net/95SrV/1/
I had to comment out the val2+ because you did not have those other forms in the sample HTML you provided:
Pure JavaScript
var val1 = 0;
for (i = 0; i < document.form1["radio-choice-v-1"].length; i++) {
if (document.form1["radio-choice-v-1"][i].checked === true) {
val1 = document.form1["radio-choice-v-1"][i].value;
}
}
However, if you do want to full use jQuery you could use the following code instead:
Full jQuery
var val1 = 0;
$('[name="radio-choice-v-1"]').each(function() {
currentItem = $(this);
if (currentItem.is(":checked")) {
val1 = currentItem.val();
}
});
Try with this one. Make sure all elements will be available like "radio-choice-v-2".
function add() {
var val1 = 0;
for (var i = 0; i < document.form1["radio-choice-v-1"].length; i++)
{
if (document.form1["radio-choice-v-1"][i].checked === true)
{
val1 = document.form1["radio-choice-v-1"][i].value;
}
}
var val2 = 0;
for (i = 0; i < document.form2["radio-choice-v-2"].length; i++)
{
if (document.form2["radio-choice-v-2"][i].checked === true)
{
val2 = document.form2["radio-choice-v-2"][i].value;
}
}
var val3 = 0;
for (i = 0; i < document.form3["radio-choice-v-3"].length; i++)
{
if (document.form3["radio-choice-v-3"][i].checked === true)
{
val3 = document.form3["form3.radio-choice-v-3"][i].value;
}
}
var val4 = 0;
for (i = 0; i < document.form4["radio-choice-v-4"].length; i++)
{
if (document.form4["radio-choice-v-4"][i].checked === true)
{
val4 = document.form4["radio-choice-v-4"][i].value;
}
}
var val5 = 0;
for (i = 0; i < document.form5["radio-choice-v-5"].length; i++)
{
if (document.form5["radio-choice-v-5"][i].checked === true)
{
val5 = document.form5["radio-choice-v-5"][i].value;
}
}
var val6 = 0;
for( i = 0; i < document.form6["checkselection"].length; i++ )
{
if (document.form6["checkselection"][i].checked === true) //Are you missing check here
val6 += document.form6["checkselection"][i].value; // += added here
}
$("#cost").html(" = " + (val1 + val2 + val3 + val4 + val5 + val6));
}
</script>
<form name="form1" id="form1">
<fieldset data-role="controlgroup">
<legend>Please select a case:</legend>
<input id="radio-choice-v-1a" name="radio-choice-v-1" value="40" CHECKED="checked" type="radio">
<label for="radio-choice-v-1a">Choice 1 (£40)</label>
<input id="radio-choice-v-1b" name="radio-choice-v-1" value="45" type="radio">
<label for="radio-choice-v-1b">Choice 2 (£45)</label>
<input id="radio-choice-v-1c" name="radio-choice-v-1" value="140" type="radio">
<label for="radio-choice-v-1c">Choice 3 (£140)</label>
</fieldset>
</form>
<form name="form6" id="form6">
<fieldset data-role="controlgroup">
<legend>Select your extras</legend>
<input type="Checkbox" name="checkselection" id="checkbox-extra-1" value="20">
<label for="checkbox-extra-1"> Selection 1 (£20) (recommended)</label>
<input type="Checkbox" name="checkselection" id="checkbox-extra-2" value="12">
<label for="checkbox-extra-2">Selection 2 (£12)</label>
<input type="Checkbox" name="checkselection" id="checkbox-extra-3" value="4">
<label for="checkbox-extra-3">Selection 3 (£4)</label>
<input type="Checkbox" name="checkselection" id="checkbox-extra-4" value="30">
<label for="checkbox-extra-4">Selection 4 (£30)</label>
</fieldset>
</form>
<form>
<input id="submit" type="button" value="Submit" onclick="add();">
</form>
£<u id="cost"></u>