How to show 0.00 when check box not checked? - javascript

How to display 0.00 in the totalcost field when check box not checked ?
<form id="form1">
<input type="checkbox" id='game0' value="9.99" onclick="UpdateCost()">Game 1 ( 9.99)<br>
<input type="checkbox" id='game1' value="19.99" onclick="UpdateCost()">Game 2 (19.99)<br>
<input type="checkbox" id='game2' value="27.50" onclick="UpdateCost()">Game 3 (27.50)<br>
<input type="checkbox" id='game3' value="45.65" onclick="UpdateCost()">Game 4 (45.65)<br>
<input type="checkbox" id='game4' value="87.20" onclick="UpdateCost()">Game 5 (87.20)<br>
<input type="checkbox" id='game5' value="87.20" onclick="UpdateCost()">Game 5 (87.20)<br>
<input type="text" id="totalcost" value="">
</form>
<script type="text/javascript">
var clickHandlers = (function () {
var form1 = document.getElementById("form1"),
totalcost = document.getElementById("totalcost"),
// if this is always the last input in the form, we could avoid hitting document again with
// totalcost = form1[form1.length - 1];
sum = 0;
form1.onclick = function (e) {
e = e || window.event;
var thisInput = e.target || e.srcElement;
if (thisInput.nodeName.toLowerCase() === 'input') {
if (thisInput.checked) {
sum += parseFloat(thisInput.value);
} else {
if (thisInput.type.toLowerCase() === 'checkbox') {
sum -= parseFloat(thisInput.value);
}
}
totalcost.value = (sum > 0) ? sum.toFixed(2) : "";
}
}
return null;
}());
</script>

Specify default value for the input:
<input type="text" id="totalcost" value="0.00">
Set the default value to 0.00:
totalcost.value = (sum > 0) ? sum.toFixed(2) : "0.00";
DEMO
var clickHandlers = (function () {
var form1 = document.getElementById("form1"),
totalcost = document.getElementById("totalcost"),
// if this is always the last input in the form, we could avoid hitting document again with
// totalcost = form1[form1.length - 1];
sum = 0;
form1.onclick = function (e) {
e = e || window.event;
var thisInput = e.target || e.srcElement;
if (thisInput.nodeName.toLowerCase() === 'input') {
if (thisInput.checked) {
sum += parseFloat(thisInput.value);
} else {
if (thisInput.type.toLowerCase() === 'checkbox') {
sum -= parseFloat(thisInput.value);
}
}
totalcost.value = (sum > 0) ? sum.toFixed(2) : "0.00";
}
}
return null;
}());

Related

How can I take certain inputs from a user on a website and pass those values as specific parameters in my javascript function?

I have a function that works properly in the console when I run it:
function sumArray(arr) {
var res = 0;
for (var i = 0; i < arr.length; i++) {
res += arr[i];
}
return res;
}
function totalLength(thk, ...dim) {
if (thk === 7) {
thk = .1793;
}
if (thk === 10) {
thk = .1345;
}
if (thk === 11) {
thk = .1196;
}
if (thk === 12) {
thk = .1046;
}
if (thk === 13) {
thk = .0897;
}
if (thk === 14) {
thk = .0747;
}
if (thk === 16) {
thk = .0598;
}
if (thk === 18) {
thk = .0478;
}
if (thk === 19) {
thk = .0418;
}
if (thk === 20) {
thk = .0359;
}
if (thk === 22) {
thk = .0299;
}
if (thk === 24) {
thk = .0239;
}
if (thk === 26) {
thk = .0179;
}
if (thk === 28) {
thk = .0149;
}
var bendDeduction = (arguments.length - 2) * (1.55 * thk);
var dimSum = sumArray(dim);
var lengthMinusBend = dimSum - bendDeduction;
return lengthMinusBend;
}
But I am having a lot of trouble setting up boxes for number inputs on a website to accept user inputs and pass them as the parameters in the totalLength() function.
For the thk parameter I set up this box:
<label for="thk">Thickness or Gauge:</label>
<input type="number" id="thk" name="thk">
For the ...dim parameter I set up 8 boxes for up to 8 bends like this:
<label for="bend1" id="1" name="bend1">Bend 1:</label>
<input type="number" name="bend1">
Then I just want to return the output either as an alert when I press a submit button.
I am brand new to everything and in the process of learning but I saw an opportunity for a solution at my current job and I have been trying for a while now to just get everything right. thank you for any help
The issue is that you are thinking about this a bit backwards. You should be setting up event handling callback functions that can run at specific moments in time, like when a user supplies input to a form field or when a key is pressed. At those moments, you can get the data from the form fields directly and don't need them passed to functions.
Here's an example (see inline comments for details):
// Get references to inputs you'll need later
const input1 = document.getElementById("num1");
const input2 = document.getElementById("num2");
// Set up an input event handler for the form field
// The input event fires whenever the field recieves
// input (could be through direct keyboard data entry
// or through a paste operation...doesn't matter how
document.getElementById("num1").addEventListener("input", processInput);
document.getElementById("num2").addEventListener("input", processInput);
function processInput(){
// There's no need to pass anything to this funciton because
// it can just get the values it needs at this point in time
console.clear();
console.log("num1 x num2 = ", num1.value * num2.value);
}
<input type="number" id="num1" value="1">
<input type="number" id="num2" value="1">
Also, your long if statement is unnecessary. If you define two arrays (one for the possible inputs and one for the corresponding possible outputs), you can just find the index of the input in the first array and then get the item at that same index in the second array.
Here's an example of that:
// Two arrays: one for the inputs and one for the corresponding outputs
let thkIn = [7,10,11,12,13,14,16,18,19,20,22,24,26,28];
let thkOut = [.1793,.1345,.1196,.1046,.0897,.0747,.0598,.0478,.0418,.0359,.0299,.0239,.0179,.0149];
// Let's say the input was 16....
// Get the index position in the first array of where 16 is:
let inPosition = thkIn.indexOf(16); // 6
// Get the corresponding output
console.log(thkOut[inPosition]);
Working Demo - https://jsfiddle.net/disingh123/qf6x4r1c/4/
<form class="" id='my-form'>
<div class="form-control">
<label for="thk">Thickness or Gauge:</label>
<input type="number" id="thk" name="thk">
</div>
<div class="form-control">
<label for="thk">Bend 1:</label>
<input type="number" id="thk" name="bend1">
</div>
<div class="form-control">
<label for="thk">Bend 2:</label>
<input type="number" id="thk" name="bend2">
</div>
<div class="form-control">
<label for="thk">Bend 3:</label>
<input type="number" id="thk" name="bend3">
</div>
<div class="form-control">
<label for="thk">Bend 4:</label>
<input type="number" id="thk" name="bend4">
</div>
<div class="form-control">
<label for="thk">Bend 5:</label>
<input type="number" id="thk" name="bend5">
</div>
<div class="form-control">
<label for="thk">Bend 6:</label>
<input type="number" id="thk" name="bend6">
</div>
<div class="form-control">
<label for="thk">Bend 7:</label>
<input type="number" id="thk" name="bend7">
</div>
<div class="form-control">
<label for="thk">Bend 8:</label>
<input type="number" id="thk" name="bend8">
</div>
<button type="submit">
Submit
</button>
</form>
document.addEventListener('DOMContentLoaded', function () {
const formRef = document.getElementById('my-form');
formRef.addEventListener('submit', function (event) {
event.preventDefault();
const formData = new FormData(event.target);
const formObject = Object.fromEntries(formData);
const bendArray = []
for (const [key, value] of Object.entries(formObject)) {
if (key.indexOf('bend') !== -1) {
bendArray.push(Number.parseInt(value))
}
}
alert(totalLength(Number.parseInt(formObject['thk']), bendArray))
});
});
function sumArray(arr) {
var res = 0;
for (var i = 0; i < arr.length; i++) {
res += arr[i];
}
return res;
}
function totalLength(thk, dim) {
if (thk === 7) {
thk = .1793;
}
if (thk === 10) {
thk = .1345;
}
if (thk === 11) {
thk = .1196;
}
if (thk === 12) {
thk = .1046;
}
if (thk === 13) {
thk = .0897;
}
if (thk === 14) {
thk = .0747;
}
if (thk === 16) {
thk = .0598;
}
if (thk === 18) {
thk = .0478;
}
if (thk === 19) {
thk = .0418;
}
if (thk === 20) {
thk = .0359;
}
if (thk === 22) {
thk = .0299;
}
if (thk === 24) {
thk = .0239;
}
if (thk === 26) {
thk = .0179;
}
if (thk === 28) {
thk = .0149;
}
var bendDeduction = (arguments.length - 2) * (1.55 * thk);
var dimSum = sumArray(dim);
var lengthMinusBend = dimSum - bendDeduction;
return lengthMinusBend;
}
On pressing submit button you can call a function using onClick event of JS.
function onSubmit() {
// And get Value of the input fields using
let thk = document.getElementById('thk');
// like these the values can be accessed. and passed on to the other functions
// ........
let getTotalLength = totalLength(thk,...);
}
Reference : https://www.w3schools.com/jsref/prop_text_value.asp

I need to show an alert box when the user does not input any number

I don't know what I am doing wrong regarding the MaxN function. The max number is showing up correctly. However, when I have to show an alert message in case a user does not input any numbers it shows in the alert "NaN" instead of the required message.
Here is my code:
JS FILE:
function getFirstNumber()
{
var value1 = document.getElementById("fnumber").value;
var fn = parseInt(value1);
return fn;
}
function getSecondNumber()
{
var value2 = document.getElementById("snumber").value;
var sn = parseInt(value2);
return sn;
}
function getThirdNumber()
{
var value3 = document.getElementById("tnumber").value;
var tn = parseInt(value3);
return tn;
}
function MaxN()
{
var fn = getFirstNumber();
var sn = getSecondNumber();
var tn = getThirdNumber();
if (fn == "" && sn == "" && tn =="") {
alert('Please input at least one number');
} else if (fn >= sn && fn >= tn){
alert(fn);
} else if (sn >= fn && sn >= tn){
alert(sn);
} else {
alert(tn);
}
}
HTML FILE:
<html>
<head>
<script type="text/javascript" src="javafile_exercise.js"></script>
</head>
<body>
<div>
<span>First number: </span><input type="text" id="fnumber" />
</div>
<div>
<span>Second number: </span><input type="text" id="snumber" />
</div>
<div>
<span>Third number: </span><input type="text" id="tnumber" />
</div>
<br>
<button type="button" onclick="MaxN()">Max Number</button>
</br>
</body>
</html>
Version 1
You are showing the message only if
fn == "" and sn == "" and tn ==""
That means all of the three text fields has to be empty. Using OR statement, should fix your problem.
Than your message should appear, if one of the text field is empty.
At the moment you are calling the function, even if on is empty and so its value i NaN.
Edit fix:
if ((fn == "") || (sn == "") || (tn ==""))
{
alert('One of the text field is empty');
}
Version 2
Another way to approach this, is returning 0 when the text field is empty. With this way you will always have a number, even if the text field is empty.
var value1 = document.getElementById("fnumber").value;
if (value1 == null)
{
return 0;
}
else
{
var fn = parseInt(value1);
return fn;
}
You mean this??
function getFirstNumber()
{
var value1 = document.getElementById("fnumber").value;
var fn = parseInt(value1);
return fn;
}
function getSecondNumber()
{
var value2 = document.getElementById("snumber").value;
var sn = parseInt(value2);
return sn;
}
function getThirdNumber()
{
var value3 = document.getElementById("tnumber").value;
var tn = parseInt(value3);
return tn;
}
function MaxN()
{
var fn = getFirstNumber();
var sn = getSecondNumber();
var tn = getThirdNumber();
if(!isNaN(fn)&&!isNaN(sn)&&!isNaN(tn)){
if (fn == "" && sn == "" && tn =="") {
alert('Please input at least one number');
} else if (fn >= sn && fn >= tn){
alert(fn);
} else if (sn >= fn && sn >= tn){
alert(sn);
} else {
alert(tn);
}
}
else
alert("Please Enter Numbers Only!!");
}
<html>
<head>
<script type="text/javascript" src="javafile_exercise.js"></script>
</head>
<body>
<div>
<span>First number: </span><input type="text" id="fnumber" />
</div>
<div>
<span>Second number: </span><input type="text" id="snumber" />
</div>
<div>
<span>Third number: </span><input type="text" id="tnumber" />
</div>
<br>
<button type="button" onclick="MaxN()">Max Number</button>
</br>
</body>
</html>
It will work if you change your logic, your input values are not numbers when nothing is written inside, so you should use isNaN.
function getFirstNumber()
{
var value1 = document.getElementById("fnumber").value;
var fn = parseInt(value1);
return fn;
}
function getSecondNumber()
{
var value2 = document.getElementById("snumber").value;
var sn = parseInt(value2);
return sn;
}
function getThirdNumber()
{
var value3 = document.getElementById("tnumber").value;
var tn = parseInt(value3);
return tn;
}
function MaxN()
{
var fn = getFirstNumber();
var sn = getSecondNumber();
var tn = getThirdNumber();
if (isNaN(fn) && isNaN(sn) && isNaN(tn)) {
alert('Please input at least one number');
} else if (fn >= sn && fn >= tn){
alert(fn);
} else if (sn >= fn && sn >= tn){
alert(sn);
} else {
alert(tn);
}
}
<div>
<span>First number: </span><input type="text" id="fnumber" />
</div>
<div>
<span>Second number: </span><input type="text" id="snumber" />
</div>
<div>
<span>Third number: </span><input type="text" id="tnumber" />
</div>
<br>
<button type="button" onclick="MaxN()">Max Number</button>
</br>
EDIT using a different kind of logic by turning NaN to 0 at the beginning of the function
function getFirstNumber()
{
var value1 = document.getElementById("fnumber").value;
var fn = parseInt(value1);
return fn;
}
function getSecondNumber()
{
var value2 = document.getElementById("snumber").value;
var sn = parseInt(value2);
return sn;
}
function getThirdNumber()
{
var value3 = document.getElementById("tnumber").value;
var tn = parseInt(value3);
return tn;
}
function MaxN()
{
var fn = isNaN(getFirstNumber()) ? 0 : getFirstNumber() ;
var sn = isNaN(getSecondNumber()) ? 0 : getSecondNumber() ;
var tn = isNaN(getThirdNumber()) ? 0 : getThirdNumber() ;
if (fn == 0 && sn == 0 && tn == 0) {
alert('Please input at least one number');
} else if (fn >= sn && fn >= tn){
alert(fn);
} else if (sn >= fn && sn >= tn){
alert(sn);
} else {
alert(tn);
}
}
<div>
<span>First number: </span><input type="text" id="fnumber" />
</div>
<div>
<span>Second number: </span><input type="text" id="snumber" />
</div>
<div>
<span>Third number: </span><input type="text" id="tnumber" />
</div>
<br>
<button type="button" onclick="MaxN()">Max Number</button>
</br>
Last but not least.
What you should do is.
use HTML input type number e.g. <input type="number" min="0"
max="1000" step="1" />
use JavaScript Validation API (methods checkValidity(), setCustomValidity())
do read carefully the different types of results that can occur during validation
customError Set to true, if a custom validity message is set.
patternMismatch Set to true, if an element's value does not match its pattern attribute.
rangeOverflow Set to true, if an element's value is greater than its max attribute.
rangeUnderflow Set to true, if an element's value is less than its min attribute.
stepMismatch Set to true, if an element's value is invalid per its step attribute.
tooLong Set to true, if an element's value exceeds its maxLength attribute.
typeMismatch Set to true, if an element's value is invalid per its type attribute.
valueMissing Set to true, if an element (with a required attribute) has no value.
valid Set to true, if an element's value is valid.
How about something like this ...
function getNumber(id, number, ERRMessage) {
var result = false;
var elm = document.getElementById(id);
try {
var number = parseInt(value2);
var result = true;
} catch (ex) {
ERRMessage = ex.message;
}
return result;
}
function MaxN(s) {
//create id array
var ids = s.split(" ");
//init result array
var numbers = []
//get the numbers from the form
for (var i = 0; i < s.length; i++) {
if (getNumber(ids[i], number,ERR)) {
numbers.push(number)
} else {
console.log(ERR);
}
}
// do we have 3 numbers at least
if (numbers.length < 3) { // maybee not
alert(tn);
return;
} else {// we have 3 numbers
alert("Yippiee"); // get exited
console.log(numbers)
// get the maximum of the numbers
var max = numberts[0];
for (var i = 0; i < s.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
alert("MAXIMUM is" + max) // show result
}
}
robust, reusable and flexible just shovel the ids of the input fields in the function. It will also show the maximum of the 3 numbers which was missing i guess.
example call :
var s = "fnumber snumber tnumber";
MaxN(s);

jquery- How to automatically insert colon after entering 2 numeric digits

I want a to have a text box which accepts HH:MM(hours/minutes) format. So, when the user enters the value for HH, it should automatically insert a colon after that and let the user enter value for MM.
I do not want to use any plugin for this.
How do i do this?
thanks
HTML:
<input class="time" type="text"/><br/>
<input class="time" type="text"/><br/>
<input class="time" type="text"/>
JS:
var time = document.getElementsByClassName('time'); //Get all elements with class "time"
for (var i = 0; i < time.length; i++) { //Loop trough elements
time[i].addEventListener('keyup', function (e) {; //Add event listener to every element
var reg = /[0-9]/;
if (this.value.length == 2 && reg.test(this.value)) this.value = this.value + ":"; //Add colon if string length > 2 and string is a number
if (this.value.length > 5) this.value = this.value.substr(0, this.value.length - 1); //Delete the last digit if string length > 5
});
};
Fiddle
If you have multiple inputs
<input class="test-input" placeholder="hh:mm" value=""/>
<input class="test-input" placeholder="hh:mm" value=""/>
<input class="test-input" placeholder="hh:mm" value=""/>
<input class="test-input" placeholder="hh:mm" value=""/>
<input class="test-input" placeholder="hh:mm" value=""/>
Jquery Version:
$(document).on('ready',function(){
$('.test-input').on('keyup',keyUpHandler);
});
function keyUpHandler(e){
var element = this;
var key = e.keyCode || e.which;
insertTimingColor(element,key)
}
function insertTimingColor(element,key){
var inputValue = element.value;
if(element.value.trim().length == 2 && key !== 8){
element.value = element.value + ':';
}
}
fiddle - jquery
Vanilla JS version
document.body.addEventListener('keyup',keyUpHandler,false);
function keyUpHandler(e){
var evt = e || window.event;
var target = evt.target || evt.srcElement;
var key = e.keyCode || e.which;
//check if it is our required input with class test input
if(target.className.indexOf('test-input') > -1){
insertTimingColor(target,key)
}
}
function insertTimingColor(element,key){
var inputValue = element.value;
if(element.value.trim().length == 2 && key !== 8){
element.value = element.value + ':';
}
}
fiddle - js
$('id or class or parent id').on('keypress','class or id', function (e){
var key = e.keyCode || e.which;
if(this.value.trim().length == 2 && key !==8 && this.value.search
(':') != -1)
this.value = this.value + ':';
});
$('id or class or parent id').on('keyup click','class or id', function (e){
if(this.value.length >= 3)
this.selectionStart = this.selectionEnd = this.value.length;
});
$('id or class or parent id').on('paste','class or id', function (e){
e.preventDefault();
});
Try it.
jQuery("#textboxId").keypress(function(){
if(jQuery("#textboxId").val().length)==2{
var value=jQuery("#textboxId").val();
jQuery("#textboxId").val(value+":");
}
});
Try the following code:
HTML:
<input type="text" id = "timeInput" maxlength = 14>
Javascript:
$("#timeInput").focusin(function (evt) {
$(this).keypress(function () {
content=$(this).val();
content1 = content.replace(/\:/g, '');
length=content1.length;
if(((length % 2) == 0) && length < 10 && length > 1){
$('#timeInput').val($('#timeInput').val() + ':');
}
});
});
DEMO
$(document).ready(function() {
var global_flag = true;
$("#texboxId").on('keyup', function() {
var cur_val = $(this).val();
var cur_length = cur_val.length;
var flag = true;
if (cur_length > 5) {
cur_val = cur_val.substring(0, 5);
$(this).val(cur_val);
} else {
if (cur_length > 2) {
global_flag = false;
} else if (global_flag == false && cur_length < 2) {
global_flag = true;
}
if (cur_length == 2 && global_flag) {
if (window.event.keyCode != 8) {
$(this).val(cur_val + ":");
}
}
if (cur_length == 5) {
if (cur_val.match(/^(([0-1][0-9]){0,2}|(2[0-3]){0,2}){0,2}:([0-5][0-9]){0,2}$/)) {} else {
$(this).val("");
$(this).attr('placeholder', "HH:MM");
}
}
}
});
});
The code below should do the trick for you. Now all you will need to do is add some validation, like only allowing numeric key press values.
<input id="time-input" placeholder="hh:mm" type="text">
$(document).ready(function(){
$("#time-input").keypress(function(){
$this = $(this);
if($this.val().length == 2){
$this.val($this.val() + ":");
}
});
});
http://jsfiddle.net/g9nahpax/

Issue with displaying the correct output. JS radio button selection and addition

So I have this code:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js">
</script>
<input type="radio" id="radiobtn1" name="bubbles" onclick="CalculatePrice();"> Less Than 10 Bubbles<br />
<input type="radio" id="radiobtn2" name="bubbles" onclick="CalculatePrice();"> 10 Bubbles<br />
<input type="radio" id="radiobtn3" name="bubbles" onclick="CalculatePrice();"> More than 10 Bubbles<br />
<br />
<input type="radio" id="radiobtn4" name="hours" onclick="CalculatePrice();"> 1 Hour<br />
<input type="radio" id="radiobtn5" name="hours" onclick="CalculatePrice();"> 2 Hours<br />
<input type="radio" id="radiobtn6" name="hours" onclick="CalculatePrice();"> Any Longer<br />
<br />
<input type="checkbox" id="radiobtn7" name="bubbles" onclick="CalculatePrice();"> Inflatable Goals<br />
<input type="checkbox" id="radiobtn8" name="bubbles" onclick="CalculatePrice();"> Icey Cold Bottled Water<br />
<input type="checkbox" id="radiobtn9" name="bubbles" onclick="CalculatePrice();"> Photo and Video Package<br />
<script>
function CalculatePrice() {
var a, b;
var c = 0;
var d = 0;
var e = 0;
var price;
if($(radiobtn1).is(':checked')) {
a = 0;
// alert(a);
}
else if($(radiobtn2).is(':checked')) {
a = 1;
//alert(a);
}
else if($(radiobtn3).is(':checked')) {
a = 0;
//alert(a);
}
if($(radiobtn4).is(':checked')) {
b = 350;
//alert(b);
}
else if($(radiobtn5).is(':checked')) {
b = 450;
//alert(b);
}
else if($ (radiobtn6).is(':checked')) {
b = 0;
// alert(b);
}
if($(radiobtn7).is(':checked')) {
c = 50;
//alert(b);
}
else if($(radiobtn8).is(':checked')) {
d = 20;
//alert(b);
}
else if($ (radiobtn9).is(':checked')) {
e = 50;
// alert(b);
}
if(a == 0)
{
price = 0;
document.getElementById('output').innerHTML = "Contact Us For Pricing.";
//alert(price);
}
else if (b == 0)
{
price = 0;
// alert(price);
}
else
{
price = b;
price = price + new Number(c) + new Number(d) + new Number(e);
if(price != undefined)
{
price = "$" + price;
//document.getElementById('output').innerHTML = '$';
document.getElementById('output').innerHTML = price;
}
else if(a == 0)
{
document.getElementById('output').innerHTML = "Contact Us For Pricing.";
}
}
}
</script>
<br /><br />
<div id="output" style="font-weight:normal;color:#000000;letter-spacing:0pt;word-spacing:-2pt;font-size:36px;text-align:left;font-family:helvetica, sans-serif;line-height:1;"></div>
I am having trouble with the output of CalculatePrice() displaying $NaN or not adding the checkboxes. I have looked over it many times and still can't seem to work out what the issue is. I have all the checkboxes being added if they were selected but it only seems to add 1 and then not the rest. Not sure what to do!
Any help would be appreciated! Thanks.
Two things:
Change code similar to $(radiobtn1) to $("#radiobtn1"). You're referencing an id, and that's the syntax you use to do so.
Instead of calling the function from within the html, call it from the JS using jQuery's .change() function.
jQuery
$('input').change(function(){
CalculatePrice();
});
function CalculatePrice() {
var a, b;
var c = 0;
var d = 0;
var e = 0;
var price;
if ($("#radiobtn1").is(':checked')) {
a = 0;
//alert(a);
} else if ($("#radiobtn2").is(':checked')) {
a = 1;
//alert(a);
} else if ($("#radiobtn3").is(':checked')) {
a = 0;
//alert(a);
}
if ($("#radiobtn4").is(':checked')) {
b = 350;
//alert(b);
} else if ($("#radiobtn5").is(':checked')) {
b = 450;
//alert(b);
} else if ($("#radiobtn6").is(':checked')) {
b = 0;
// alert(b);
}
if ($("#radiobtn7").is(':checked')) {
c = 50;
//alert(b);
} else if ($("#radiobtn8").is(':checked')) {
d = 20;
//alert(b);
} else if ($("#radiobtn9").is(':checked')) {
e = 50;
// alert(b);
}
if (a == 0) {
price = 0;
document.getElementById('output').innerHTML = "Contact Us For Pricing.";
//alert(price);
} else if (b == 0) {
price = 0;
// alert(price);
} else {
price = b;
price = price + new Number(c) + new Number(d) + new Number(e);
if (price != undefined) {
price = "$" + price;
//document.getElementById('output').innerHTML = '$';
document.getElementById('output').innerHTML = price;
} else if (a == 0) {
document.getElementById('output').innerHTML = "Contact Us For Pricing.";
}
}
}
Fiddle
The math is still a little strange, so I'd check that.

Checking the value of 4 input boxes simultaneously instead of one-by-one

How can the code below be modified, such that I would be able to check the value and add a class to the 4 input boxes if my validate_date(date) is false, simultaneously as opposed to checking each field one-by-one, exiting the function each and every time as its current setup is?
I am using some jQuery, so I am jQuery friendly
date1 = document.getElementById('date1').value
if (date1) {
if (validate_date(date1) == true) {
date1 = parseDate(date1)
} else {
$("#date1").addClass("invalid")
return
}
} else {
date1 = null
}
date2 = document.getElementById('date2').value
if (date2) {
if (validate_date(date2) == true) {
date2 = parseDate(date2)
} else {
$("#date2").addClass("invalid")
return
}
} else {
date2 = null
}
date3 = document.getElementById('date3').value
if (date3) {
if (validate_date(date3) == true) {
date3 = parseDate(date3)
} else {
$("#date3").addClass("invalid")
return
}
} else {
date3 = null
}
date4 = document.getElementById('date4').value
if (date4) {
if (validate_date(date4) == true) {
date4 = parseDate(date4)
} else {
$("#date4").addClass("invalid")
return
}
} else {
date4 = null
}
function validate_date(str) {
var t = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
if (t === null) return false;
var d = parseInt(t[1]),
m = parseInt(t[2], 10),
y = parseInt(t[3], 10);
//below should be more acurate algorithm
if (m >= 1 && m <= 12 && d >= 1 && d <= 31) {
return true;
}
return false;
}
Here is what you want:
JsFiddle: http://jsfiddle.net/RqyDT/1/
HTML:
<form class="validation" action="your_page.html">
<p>
<label for="date1">Date 1</label>
<input type="text" name="date1" class="date"/>
</p>
<p>
<label for="date2">Date 2</label>
<input type="text" name="date2" class="date"/>
</p>
<p>
<label for="date1">Date 3</label>
<input type="text" name="date3" class="date"/>
</p>
<p>
<label for="date2">Date 4</label>
<input type="text" name="date4" class="date"/>
</p>
<p>
<input type="submit" value="Submit"/>
</p>
</form>
CSS:
.invalid{color:red;}
JavaScript:
function validate_date(str) {
var t = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
if (t === null) return false;
var d = parseInt(t[1]),
m = parseInt(t[2], 10),
y = parseInt(t[3], 10);
//below should be more acurate algorithm
if (m >= 1 && m <= 12 && d >= 1 && d <= 31) {
return true;
}
return false;
}
$(document).ready(function(){
$(".validation").submit(function(){
//Initialize
var valid_fields = true;
$('label').removeClass("invalid");
//Loop through date input
$(".date").each(function(){
var date_val = $(this).val();
//If validation function return false, add class "invalid" to the label
if (validate_date(date_val) == false) {
$('label[for="'+ $(this).attr('name') +'"]').addClass('invalid');
valid_fields = false;
}
});
//Return true or false, depends of the form validation
return valid_fields;
});
});
Your code is a little confusing, as such I made some quick adjustments as I'm unsure if you're using a framework. Here is a basic model of what I believe you are asking. it will look for elements with the ids "date1", "date2"... until it gets to date4 and will stop. For each element it gets the value, validates the value, if valid it parses it and sets that data into the value of the parent element. Otherwise it adds the "invalid" class. Was unsure what the else on the if(value) clause was supposed to do, but I did kept it there in case you were doing something farther down that I was unaware of.
Another way would be to check elements by tag name and filter out ones with the name/id value that contains "date" but i figured this was more direct.
var base = 'date';
for(var i=1;i<=4;i++)}
var el = document.getElementById(base+i);
var value = el.value;
if (value) {
if (validate_date(value) == true) {
el.value = parseDate(value)
} else {
el.className = (el.className.length > 0) ? el.className + " invalid" : "invalid";
}
} else {
el.value = "";
}
}

Categories

Resources