Validate the radio button list by adding a for loop???
I cannot figure out how to create a for loop to validate my subscriptions for the HTML radio buttons; Free, Basic, Premium.
Line 39 for JS problem.
Line 128 for HTML reference.
See snippet below:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>javascript form validation</title>
<script type="text/javascript">
function checkme() {
//alert("function fires");
var error = "";
if(document.getElementById('myname').value == "") {
error = "Please enter your name.\n";
}
if(document.getElementById('state').selectedIndex==0) {
error += "Please choose a state.\n";
}
if(document.getElementById('address').value== "") {
error += "Please complete address.\n";
}
if(document.getElementById('city').value== "") {
error += "Please complete city.\n";
}
if(document.getElementById('zip').value== "") {
error += "Please complete address.\n";
}
if(document.getElementById('phone').value== "") {
error += "Please enter phone number.\n";
}
if(document.getElementById('email').value== "") {
error += "Please enter email.\n";
}
if(document.getElementById('comments').value== "") {
error += "Please enter comments.\n";
}
if(!document.getElementById('radio')!=null){
error += "Please select subscription.\n";
// ????
}
if(!document.getElementById('terms')!=null){
error += "Please accept terms.\n";
}
// Do not add logic below this comment
if(error=="") {
return true;
}
else {
alert(error);
return false;
}
}
</script>
<!-- styles for form -->
<style type="text/css">
fieldset {width: 400px;}
/* zero ul and li */
fieldset ul, fieldset li{
border:0; margin:0; padding:0; list-style-type:none;
}
/* li is a block level element. give margin bottom for spacing. */
fieldset li
{
margin-bottom: 10px;
}
/* label is a inline element. convert to inline block to prevent wrapping to next line but still apply width. */
fieldset label{
width:140px;
display: inline-block;
}
/* set radio button labels back to default */
label.radios
{
width:100%;
display: inline;
}
/* take lblnotes out of document flow, aligns to top */
#lblnotes {float: left;}
</style>
</head>
<body>
<fieldset>
<legend>Sign-up Form</legend>
<form id="the_form" name="the_form" action="FormProcessor.html" method="get" onsubmit="return checkme();">
<ul>
<li><label for="myname">Name</label>
<input type="text" name="myname" id="myname" size="30" />
</li>
<li><label for="address">Street Address</label>
<input type="text" name="address" id="address" size="30" />
</li>
<li><label for="city">City</label>
<input type="text" name="city" id="city" size="30" />
</li>
<li><label for="state">State</label>
<select name="state" id="state">
<option value="none">choose a state</option>
<option value="MN">Minnesota</option>
<option value="WI">Wisconsin</option>
</select>
</li>
<li><label for="zip">Zip</label>
<input type="text" name="zip" id="zip" size="30" />
</li>
<li><label for="phone">Phone Number</label>
<input type="text" name="phone" id="phone" size="30" />
</li>
<li><label for="email">Email</label>
<input type="text" name="email" id="email" size="30" />
</li>
<li><label for="comments" id="lblnotes">Commments</label>
<textarea name="comments" id="comments" cols="20" rows="5"></textarea>
</li>
<li><label>Subscription</label> <label for="free" class="radios">Free</label>
<input type="radio" name="subscription" id="free"/>
<label for="basic" class="radios">Basic</label>
<input type="radio" name="subscription" id="basic"/>
<label for="premium" class="radios">Premium</label>
<input type="radio" name="subscription" id="premium"/>
</li>
<li>
<label for="terms">Do you agree to terms?</label>
<input type="checkbox" name="terms" id="terms"/>
</li>
<li><label for="submit"> </label>
<button type="submit" id="submit">Send</button> </li>
</ul>
</form>
</fieldset>
</body>
</html>
You may use the name of the radio button instead:
var radiobuttons = document.getElementsByName(radioButtonName);
for(var opt in radiobuttons ) {
//validate...
}
Simplest approach would be to set required attribute at input, textarea, select elements
var elems = document.forms["the_form"]
.querySelectorAll("input:not([type=submit]), select, textarea");
for (var i = 0; i < elems.length; i++) {
elems[i].setAttribute("required", true)
}
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>javascript form validation</title>
<script type="text/javascript">
</script>
<!-- styles for form -->
<style type="text/css">
fieldset {width: 400px;}
/* zero ul and li */
fieldset ul, fieldset li{
border:0; margin:0; padding:0; list-style-type:none;
}
/* li is a block level element. give margin bottom for spacing. */
fieldset li
{
margin-bottom: 10px;
}
/* label is a inline element. convert to inline block to prevent wrapping to next line but still apply width. */
fieldset label{
width:140px;
display: inline-block;
}
/* set radio button labels back to default */
label.radios
{
width:100%;
display: inline;
}
/* take lblnotes out of document flow, aligns to top */
#lblnotes {float: left;}
</style>
</head>
<body>
<fieldset>
<legend>Sign-up Form</legend>
<form id="the_form" name="the_form" action="FormProcessor.html" method="get" onsubmit="return checkme();">
<ul>
<li><label for="myname">Name</label>
<input type="text" name="myname" id="myname" size="30" />
</li>
<li><label for="address">Street Address</label>
<input type="text" name="address" id="address" size="30" />
</li>
<li><label for="city">City</label>
<input type="text" name="city" id="city" size="30" />
</li>
<li><label for="state">State</label>
<select name="state" id="state">
<option value="none">choose a state</option>
<option value="MN">Minnesota</option>
<option value="WI">Wisconsin</option>
</select>
</li>
<li><label for="zip">Zip</label>
<input type="text" name="zip" id="zip" size="30" />
</li>
<li><label for="phone">Phone Number</label>
<input type="text" name="phone" id="phone" size="30" />
</li>
<li><label for="email">Email</label>
<input type="text" name="email" id="email" size="30" />
</li>
<li><label for="comments" id="lblnotes">Commments</label>
<textarea name="comments" id="comments" cols="20" rows="5"></textarea>
</li>
<li><label>Subscription</label> <label for="free" class="radios">Free</label>
<input type="radio" name="subscription" id="free"/>
<label for="basic" class="radios">Basic</label>
<input type="radio" name="subscription" id="basic"/>
<label for="premium" class="radios">Premium</label>
<input type="radio" name="subscription" id="premium"/>
</li>
<li>
<label for="terms">Do you agree to terms?</label>
<input type="checkbox" name="terms" id="terms"/>
</li>
<li><label for="submit"> </label>
<button type="submit" id="submit">Send</button> </li>
</ul>
</form>
</fieldset>
</body>
</html>
You can iterate over the radio buttons with the name subscriptions to find which if any is checked. Check the sample here (getRadioVal function): http://www.dyn-web.com/tutorials/forms/radio/get-selected.php
Related
I am required to complete an assignment that shows basic Javascript form processing. The objective is to have a "details.html" page which checks that all input fields are valid (e.g. Names are all text). I have tried to complete both documents but they just don't seem to be linking correctly:
Nothing is triggering the "validateForm()" function, and any input just passes through on submission, what have I done wrong?
function validateForm() {
var firstname = document.getElementById("fName").value;
var lastname = document.getElementById("lName").value;
var email = document.getElementById("email").value;
var address = document.getElementById("address").value;
var postCode = document.getElementById("pCode").value;
var accepted = document.getElementById("accept").checked;
var allLetters = /^[a-zA-z]+$/i;
var allNumbers = /^[0-9]+$/;
var validEmail = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var validAddress = new RegExp(allNumbers.source + "|" + allLetters.source);
if (address.match(validAddress) && firstname.match(allLetters) && lastname.match(allLetters) && email.match(validEmail) && address != "" && postCode.match(allNumbers) && accepted) {
return true;
} else {
window.alert("Error! Invalid input in form. Please try again.");
return false;
}
}
.header {
background-color: tomato;
color: white;
padding: 2px;
}
.focusPage {
width: 70%;
margin-left: auto;
margin-right: auto;
background-color: lightgrey;
min-height: 600px;
height: 600px;
height: auto !important;
}
.userDetails {
width: 90%;
margin-left: auto;
margin-right: auto;
background-color: white;
border: 2px solid black;
font-size: 20px;
font-family: Arial, Helvetica, sans-serif;
padding-top: 20px;
padding-bottom: 20px;
}
.inputs {
float: right;
direction: ltr;
margin-right: 5px;
}
.acceptTerms {
font-size: 15px;
font-family: "Times New Roman", Times, serif;
}
p {
font-size: 20px;
font-family: Verdana, Geneva, Tahoma, sans-serif;
}
.thePage {
background-color: black;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="someName" content="someContent">
<title> Home </title>
<script type="text/javascript" src="myScripts.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body class="thePage">
<div>
<div class="focusPage">
<div class="header">
<h1>Welcome user!</h1>
</div>
<p>This form will allow you to enter your personal details for storage in our database.</p>
<p>Be sure to read our User Agreement before submitting your details</p>
<ul class="userDetails">
<form class="userForm" onsubmit="validateForm()" method="post">
<li><label for="inputNames" required>First Name - </label>
<label for="inputs"><input type="text" class="inputs" id="fname" name="fname"></label></li>
<li><label for="inputNames">Last Name - </label>
<label for="inputs" required><input type="text" class="inputs" id="lname" name="lname"></li>
<li><label for="inputNames">Email - </label>
<label for="inputs" required><input type="email" class="inputs" id="email" name="email"></li>
<li><label for="inputNames">Address number - </label>
<label for="inputs" required><input type="text" class="inputs" id="address" name="address"></li>
<li><label for="inputNames">Post code - </label>
<label for="inputs" required><input type="text" class="inputs" id="pCode" name="pCode"></li>
<li><label for="inputNames">Additional Detail - </label></li>
<textarea rows="5" cols="50" class="textfield" placeholder="Add detail here..."></textarea>
<div class="agreement">
<input type="checkbox"> <label class="acceptTerms" id="accept">I Accept the User Agreement</label>
</div>
<input type="submit" value="Submit">
</form>
</ul>
</div>
</div>
</body>
</html>
JS: you have mentioned wrong IDs, remember they are case sensitive.
var firstname = document.getElementById("fname").value;
var lastname = document.getElementById("lname").value;
HTML: You have mentioned required in label tag which won't work, add it to input tag.
<form class="userForm" onsubmit="validateForm()">
<li><label for="inputNames" >First Name - </label>
<label for="inputs"><input type="text" class="inputs" id="fname" name="fname" required></label></li>
<li><label for="inputNames">Last Name - </label>
<label for="inputs" ><input type="text" class="inputs" id="lname" name="lname" required></li>
<li><label for="inputNames">Email - </label>
<label for="inputs" ><input type="email" class="inputs" id="email" name="email" required></li>
<li><label for="inputNames">Address number - </label>
<label for="inputs" ><input type="text" class="inputs" id="address" name="address" required></li>
<li><label for="inputNames">Post code - </label>
<label for="inputs" ><input type="text" class="inputs" id="pCode" name="pCode" required></li>
<li><label for="inputNames">Additional Detail - </label></li>
<textarea rows="5" cols="50" class="textfield" placeholder="Add detail here..."></textarea>
<div class="agreement">
<input type="checkbox" required> <label class="acceptTerms" id="accept">I Accept the User Agreement</label>
</div>
<input type="submit" value="Submit">
</form>
I want to create a function in javascript whereby I check whether is the radio is being checked if so I will display the cost that is I assign in javascript itself to HTML.
The following is my HTML and javascript:
function priceCalculator(){
var price_dict = {
"Small":22, "Medium":28, "Large":35,
}
var length = Object.keys(price_dict).length;
for(var i=0;i<length;i++){
var dis = document.getElementsByName('Size')[i].value;
if(document.getElementsByName('Size').checked){
document.getElementById("DisplayPrice").innerHTML = price_dict[dis];
}
}
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Pizza Order Form</title>
<style>
form {
font-family: Arial, Helvetica, sans-serif;
vertical-align: central;
border: 5px solid black;
margin:0px auto;
width:650px;
padding-left:0.5em;
}
fieldset{
width:600px;
box-sizing:border-box;
border-radius: 20px;
}
.deliver > p > label {
width: 70px;
display: inline-block;
}
.deliver > p > input {
width: 130px;
display: inline-block;
}
#DisplayPrice{
background-color: yellow;
}
</style>
</head>
<body >
<form>
<h1>Pizza order Form</h1>
<p>
<label for="Pizza Type">Pizza Type:</label>
<select name="pizza type">
<option value="Please select" selected>Please select...</option>
<option value="Aloha Chicken">Aloha Chicken</option>
<option value="Beef Pepperoni">Beef Pepperoni</option>
<option value="Chicken Delight">Chicken Delight</option>
<option value="Deluxe Cheese">Deluxe Cheese</option>
</select>
<label for="Quantity">Quantity</label>
<input name="quantity" type="number" min="1" max="4" />
</p>
<!--Size-->
<fieldset >
<legend>Size:</legend>
<input type="radio" name="Size" value="Small" onclick="priceCalculator()" />Small
<input type="radio" name="Size" value="Medium" onchange="priceCalculator()"/>Medium
<input type="radio" name="Size" value="Large" onload="priceCalculator()"/>Large
</fieldset>
<!--Crust-->
<fieldset>
<legend>Crust:</legend>
<input type="radio" name="Crust"value="Thin" />Thin
<input type="radio" name="Crust" value="Thick" />Thick
<input type="radio" name="Crust" value="Deep Dish" />Deep Dish
</fieldset>
<!--Toppings-->
<fieldset>
<legend>Toppings:</legend>
<input type="radio" name="Toppings" value="Mushrooms" />Mushrooms
<input type="radio" name="Toppings" value="Sausage" />Sausage
<input type="radio" name="Toppings" value="Olives" />Olives
</fieldset>
<!--Addons-->
<p>
<label for="Addons">Addons</label>
<select name="Addons" multiple>
<option value="Side of Buffalo Wings">Side of Buffalo Wings</option>
<option value="Garlic Bread">Garlic Bread</option>
</select>
</p>
<div id="DisplayPrice"></div>
<!--Delivery section-->
<fieldset class="deliver">
<legend>Deliver to:</legend>
<p>
<label for="Name">Name:</label>
<input type="text" name="name" required/>
</p>
<p>
<label for="Address">Address:</label>
<textarea rows="2" cols="30" required></textarea>
<label for="Postal Code">Postal Code:</label>
<input type="text" name="Postal Code" maxlength="6" required/>
</p>
<p>
<label for="Phone Number">Phone#: </label>
<input type="tel" name="Phone#" maxlength="8" pattern="^[896]\d{7}" required/>
</p>
<p>
<label for="email">Email:</label>
<input type="email" form="email" required />
</p>
<p>
<label for=" Date">Date:</label>
<input type="date" name="Date" min="1 November 2017" max="31 December 2017" required/>
<label for="time">Time: </label>
<input type="time" value="10:00" name="Time" min="10:00" max="22:00" step="15" required/>
</p>
</fieldset>
<p>
<input type="submit" value="submit">
<input type="reset" value="reset">
</p>
</form>
<script src="pizzaScript.js"></script>
</body>
</html>
Also, I would like to know is the use of onclick is correct?
Thx in advance m8s!
remember that getElementsByName returns a collection therefore it is not correct to do a getElementsByName('Size').checked it would be correct to access an element of a list getElementsByName('Size')[i].checked
Your event where you assign the function should change for all three, do not load as you have right now.
Also, if you declare values that will always be used price_dict and will not change in your program, you should declare it outside the function.
Your code can be greatly reduced if you pass the item from the html on the onchange
var price_dict = {
"Small":22, "Medium":28, "Large":35,
}
function priceCalculator(elm){
document.getElementById("DisplayPrice").innerHTML = price_dict[elm.value];
}
<fieldset >
<legend>Size:</legend>
<input type="radio" name="Size" value="Small" onchange="priceCalculator(this)" />Small
<input type="radio" name="Size" value="Medium" onchange="priceCalculator(this)"/>Medium
<input type="radio" name="Size" value="Large" onchange="priceCalculator(this)"/>Large
</fieldset>
<div id="DisplayPrice"></div>
You can loop through the elements and find the correct price from the dictionary.
var sizeElements = Array.from(document.getElementsByName('Size'));
var value = sizeElements.length && sizeElements.find(r => r.checked).value;
Working example given below
For the onClick vs onChange: You should probably use onClick. You can read more about it at this question: What the difference between .click and .change on a checkbox
function priceCalculator(){
var price_dict = {
"Small":22, "Medium":28, "Large":35,
}
var sizeElements = Array.from(document.getElementsByName('Size'));
var value = sizeElements.length && sizeElements.find(r => r.checked).value;
return price_dict[value] // use returned price elsewhere
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Pizza Order Form</title>
<style>
form {
font-family: Arial, Helvetica, sans-serif;
vertical-align: central;
border: 5px solid black;
margin:0px auto;
width:650px;
padding-left:0.5em;
}
fieldset{
width:600px;
box-sizing:border-box;
border-radius: 20px;
}
.deliver > p > label {
width: 70px;
display: inline-block;
}
.deliver > p > input {
width: 130px;
display: inline-block;
}
#DisplayPrice{
background-color: yellow;
}
</style>
</head>
<body >
<form>
<h1>Pizza order Form</h1>
<p>
<label for="Pizza Type">Pizza Type:</label>
<select name="pizza type">
<option value="Please select" selected>Please select...</option>
<option value="Aloha Chicken">Aloha Chicken</option>
<option value="Beef Pepperoni">Beef Pepperoni</option>
<option value="Chicken Delight">Chicken Delight</option>
<option value="Deluxe Cheese">Deluxe Cheese</option>
</select>
<label for="Quantity">Quantity</label>
<input name="quantity" type="number" min="1" max="4" />
</p>
<!--Size-->
<fieldset >
<legend>Size:</legend>
<input type="radio" name="Size" value="Small" onclick="priceCalculator()" />Small
<input type="radio" name="Size" value="Medium" onclick="priceCalculator()"/>Medium
<input type="radio" name="Size" value="Large" onclick="priceCalculator()"/>Large
</fieldset>
<!--Crust-->
<fieldset>
<legend>Crust:</legend>
<input type="radio" name="Crust"value="Thin" />Thin
<input type="radio" name="Crust" value="Thick" />Thick
<input type="radio" name="Crust" value="Deep Dish" />Deep Dish
</fieldset>
<!--Toppings-->
<fieldset>
<legend>Toppings:</legend>
<input type="radio" name="Toppings" value="Mushrooms" />Mushrooms
<input type="radio" name="Toppings" value="Sausage" />Sausage
<input type="radio" name="Toppings" value="Olives" />Olives
</fieldset>
<!--Addons-->
<p>
<label for="Addons">Addons</label>
<select name="Addons" multiple>
<option value="Side of Buffalo Wings">Side of Buffalo Wings</option>
<option value="Garlic Bread">Garlic Bread</option>
</select>
</p>
<div id="DisplayPrice"></div>
<!--Delivery section-->
<fieldset class="deliver">
<legend>Deliver to:</legend>
<p>
<label for="Name">Name:</label>
<input type="text" name="name" required/>
</p>
<p>
<label for="Address">Address:</label>
<textarea rows="2" cols="30" required></textarea>
<label for="Postal Code">Postal Code:</label>
<input type="text" name="Postal Code" maxlength="6" required/>
</p>
<p>
<label for="Phone Number">Phone#: </label>
<input type="tel" name="Phone#" maxlength="8" pattern="^[896]\d{7}" required/>
</p>
<p>
<label for="email">Email:</label>
<input type="email" form="email" required />
</p>
<p>
<label for=" Date">Date:</label>
<input type="date" name="Date" min="1 November 2017" max="31 December 2017" required/>
<label for="time">Time: </label>
<input type="time" value="10:00" name="Time" min="10:00" max="22:00" step="15" required/>
</p>
</fieldset>
<p>
<input type="submit" value="submit">
<input type="reset" value="reset">
</p>
</form>
<script src="pizzaScript.js"></script>
</body>
</html>
Here is a JSFiddle:
http://jsfiddle.net/5Lz3zd9y/7/
HTML:
<div class="ui-bar ui-bar-a ui-widget-content">dog</div>
<input class="blankLettersMobile" type="text" value="" size="1" maxlength="1">
<input class="givenLettersMobile" type="text" value="e" disabled>
<input class="blankLettersMobile" type="text" value="" size="1" maxlength="1">
<input class="blankLettersMobile" type="text" value="" size="1" maxlength="1">
<input class="blankLettersMobile" type="text" value="" size="1" maxlength="1">
<input type="text" value="sign in">
CSS:
.givenLettersMobile {
width: 40px;
height: 40px;
text-align:center;
font-style:italic;
font-weight:bold;
text-decoration:underline;
line-height: 50%;
}
.blankLettersMobile {
width: 40px;
height: 40px;
text-align:center;
font-style:italic;
line-height: 50%;
}
In regards to the JSFiddle using JQuery Mobile, I'm trying to figure out how to get all the text input boxes aligned left to right instead of stacked top to bottom while also trying to reduce the width of the text input boxes (without affecting the width of other input boxes like username, password, etc...). Something more like how these text input boxes behave from the desktop version of the website:
Any thoughts on how to accomplish this?
input[type='text'].givenLettersMobile
{
width: 40px !important;
height: 40px !important;
text-align:center !important;
}
Here is what worked for me:
http://jsfiddle.net/5Lz3zd9y/43/
html:
<div class="ui-bar ui-bar-a ui-widget-content">dog</div>
<ul class="letters">
<li>
<input type="text" value="" size="1" maxlength="1">
</li>
<li>
<input type="text" value="e" size="1" disabled>
</li>
<li>
<input type="text" value="" size="1" maxlength="1">
</li>
<li>
<input type="text" value="" size="1" maxlength="1">
</li>
<li>
<input type="text" value="" size="1" maxlength="1">
</li>
</ul>
<input type="text" value="sign in">
CSS:
.letters li {
display: inline-block;
}
I've made a form with a few items. Each item has a value.
Now my question is, how can I add the values from these items (when you check them) to the total value?
See JSFiddle
<form id="AddValuesForm" action="">
<fieldset id="AddValuesFormPart1">
<legend>Add Values</legend>
<ul>
<li>
<ul id="AddValueList">
<li id="AddValueItem1">
<input id="value1" type="checkbox" name="value1" value="" tabindex="10"/> <label for="value1">Cheesecake</label>
<input class="v1" id="value1" type="text" name="value1" value="1.25" disabled="disabled" maxlength="10"/>
</li>
<li id="AddValueItem2">
<input id="value2" type="checkbox" name="value2" value="" tabindex="20"/> <label for="value2">Banana Pie</label>
<input class="v2" id="value2" type="text" name="value2" value="1.50" disabled="disabled" maxlength="10"/>
</li>
<li id="AddValueItem3">
<input id="value3" type="checkbox" name="value3" value="" tabindex="30"/> <label for="value3">Chocolate Muffin</label>
<input class="v3" id="value3" type="text" name="value3" value="1.00" disabled="disabled" maxlength="10"/>
</li>
</ul>
</li>
<li>
<ul id="AddValueTotalList">
<li id="AddValueTotal">
<label for="total">Total:</label><input class="t" id="total" type="text" name="total" value="0.00" disabled="disabled" maxlength="10"/>
</li>
</ul>
</li>
<li id="ValueSubmit"><input id="AddValuesItem10" type="submit" name="submit" value="Submit Add Values Form" tabindex="100"/></li>
</ul>
</fieldset>
</form>
Note: without the use of jQuery.
This should do it:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<style type="text/css">
ul{list-style-type:none;}
ul#AddValueList{float:left;}
.v1, .v2, .v3
{
width:35px;
text-align:right;
color:#000;
}
.v1{margin:0px 0px 0px 50px;}
.v2{margin:0px 0px 0px 56px;}
.v3{margin:0px 0px 0px 19px;}
.t
{
width:35px;
text-align:right;
color:#000;
margin:20px 0px 0px 118px;
}
#ValueSubmit,
#AddValueTotalList
{
clear:left;
}
#ValueSubmit input{margin:20px 0px 0px 0px;}
</style>
<script type="text/javascript">
var totalcounter = 0;
totaltracker = function (event) {
var targetelement = (typeof event.target != "undefined") ? event.target : event.srcElement;
var multipler = 0;
if (targetelement.checked) {
multipler++;
} else {
multipler--;
}
var targetvalue = document.getElementById(targetelement.id + 'a');
var idtotal = document.getElementById("total");
if (idtotal) idtotal.value = parseFloat(idtotal.value) + (multipler * parseFloat(targetvalue.value));
};
function totalloader () {
var elements = document.getElementsByTagName('INPUT');
for (var i=0; i<elements.length; i++) {
var thisElement = elements[i];
if (thisElement.getAttribute("type") == "checkbox") {
if (typeof thisElement.addEventListener != "undefined") {
thisElement.addEventListener("click", totaltracker, true);
} else if (typeof thisElement.attachEvent != "undefined") {
thisElement.attachEvent("onclick", totaltracker);
}
}
}
}
</script>
<title>Add Values in Form</title>
</head>
<body onLoad="totalloader();">
<form id="AddValuesForm" action="">
<fieldset id="AddValuesFormPart1">
<legend>Add Values</legend>
<ul>
<li>
<ul id="AddValueList">
<li id="AddValueItem1">
<input id="value1" type="checkbox" name="value1" value="" tabindex="10"/>
<label for="value1">Cheesecake</label>
<input class="v1" id="value1a" type="text" name="value1" value="1.25" disabled="disabled" maxlength="10"/>
</li>
<li id="AddValueItem2">
<input id="value2" type="checkbox" name="value2" value="" tabindex="20"/> <label for="value2">Banana Pie</label>
<input class="v2" id="value2a" type="text" name="value2" value="1.50" disabled="disabled" maxlength="10"/>
</li>
<li id="AddValueItem3">
<input id="value3" type="checkbox" name="value3" value="" tabindex="30"/> <label for="value3">Chocolate Muffin</label>
<input class="v3" id="value3a" type="text" name="value3" value="1.00" disabled="disabled" maxlength="10"/>
</li>
</ul>
</li>
<li>
<ul id="AddValueTotalList">
<li id="AddValueTotal">
<label for="total">Total:</label><input class="t" id="total" type="text" name="total" value="0.00" disabled="disabled" maxlength="10"/>
</li>
</ul>
</li>
<li id="ValueSubmit"><input id="AddValuesItem10" type="submit" name="submit" value="Submit Add Values Form" tabindex="100"/></li>
</ul>
</fieldset>
</form>
</body>
</html>
I have changed the id of the disabled value field to more easier equate from the check box to the value to be totaled.
I have added an onload to the body tag.
I have added a script section to do the work.
var t=0;
for (i=1; i<=3; i++) {
t = t + document.getElementById('value' + i).value;
}
document.getElementById('total').value = t;
Please use the code Below
function recalculate(obj, id) {
var total = parseFloat(document.getElementById('total').value);
var amount = parseFloat(document.getElementById(id).value);
if (obj.checked) {
total += amount;
} else {
if (total >= 0) {
total -= amount;
}
}
document.getElementById('total').value = total;
}
</script>
<form id="AddValuesForm" action="">
<fieldset id="AddValuesFormPart1">
<legend>Add Values</legend>
<ul>
<li>
<ul id="AddValueList">
<li id="AddValueItem1">
<input id="value1" type="checkbox" name="value1" value="" tabindex="10" onchange="recalculate(this, 'txtValue1');"/> <label for="value1">Cheesecake</label>
<input class="v1" id="txtValue1" type="text" name="value1" value="1.25" disabled="disabled" maxlength="10"/>
</li>
<li id="AddValueItem2">
<input id="value2" type="checkbox" name="value2" value="" tabindex="20" onchange="recalculate(this, 'txtValue2');"/> <label for="value2">Banana Pie</label>
<input class="v2" id="txtValue2" type="text" name="value2" value="1.50" disabled="disabled" maxlength="10"/>
</li>
<li id="AddValueItem3">
<input id="value3" type="checkbox" name="value3" value="" tabindex="30" onchange="recalculate(this, 'txtValue3');"/> <label for="value3">Chocolate Muffin</label>
<input class="v3" id="txtValue3" type="text" name="value3" value="1.00" disabled="disabled" maxlength="10"/>
</li>
</ul>
</li>
<li>
<ul id="AddValueTotalList">
<li id="AddValueTotal">
<label for="total">Total:</label><input class="t" id="total" type="text" name="total" value="0.00" disabled="disabled" maxlength="10"/>
</li>
</ul>
</li>
<li id="ValueSubmit"><input id="AddValuesItem10" type="submit" name="submit" value="Submit Add Values Form" tabindex="100"/></li>
</ul>
</fieldset>
</form>
Using JQuery JSFIDDLE:
$(document ).ready(function() {
console.log( "ready!" );
$('input[type=checkbox]').click(function() {
if($(this).is(':checked')) {
$('#total').val( parseFloat($('#total').val())+parseFloat($(this).parent().find('input[type=text]').val()));
} else {
$('#total').val( parseFloat($('#total').val())-parseFloat($(this).parent().find('input[type=text]').val()));
}
});
});
here i use a same address option in my page
when i click on checkbox for same address my other input must disable
my code:
<ul><input type="checkbox" name="same-address" /> Click for same address <br />Enter Address here: <input type="text" name="address" /> Enter City here: <input type="text" name="city" /> </ul>
Try this
$('#same').click(function () {
if ($(this).is(':checked')) {
$(this).parents('ul').find('li input[type="text"],select').attr('disabled', 'disabled');
} else {
$(this).parents('ul').find('li input[type="text"],select').removeAttr('disabled')
}
});
DEMO Fiddle
You can use attribute equals selector to select the input by type and use .prop to update the disabled state of your input:
$('input[type="checkbox"]').click(function() {
$('input[type="text"]').prop('disabled',this.checked);
});
Fiddle Demo
You can use input selector for selecting all the input elements and in conjunction use Prop for disabling the controls.
$('input[type="checkbox"]').click(function() {
$('input[type="text"]').prop('disabled',this.checked);
})
Please try with the below code snippet.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$('.SameAsBillingAddress').on('click',function(){
if($(this).prop('checked'))
{
$('.Address2').prop('disabled', true);
}
else
{
$('.Address2').prop('disabled', false);
}
});
});
</script>
</head>
<body>
<div>
<ul>
<div style="height:30px; width:80%; margin-left:30px; clear:both;">
<input name="" type="checkbox" value="" class="SameAsBillingAddress" />Same as Billing Address</div>
<li>
<label>House No.:</label>
<input type="text" name="house no" class="Address2" placeholder="House No" />
</li>
<li>
<label>Street:</label>
<input type="text" name="street" class="Address2" placeholder="Your Street" />
</li>
<li>
<label>City</label>
<input type="text" name="city" class="Address2" placeholder="Your City" />
</li>
<li>
<label>Zip:</label>
<input type="text" name="zip" class="Address2" placeholder="Your Zip" />
</li>
<li>
<label>Country:</label>
<select class="Address2">
<option>India</option>
</select>
</li>
<li style="float:right;">
<label></label>
<input type="submit" name="save" class="Address2" value="Save Details" />
</li>
</ul>
</div>
</body>
</html>