I have this script
<script>
function trigger(){
var x = document.getElementById('xcoord');
var y = document.getElementById('ycoord');
var box = document.getElementById('touch');
if (x.value >= 325 || x.value <= 300 && y.value >= 55 || y.value <= 25) {
$('#touch').value('passed');
}
}
</script>
here is the html
<input onchange="trigger()" required type="number" id="xcoord" name="xcoord">
<input onchange="trigger()" required type="number" id="ycoord" name="ycoord">
<input required type="text" id="touch" name="touch">
i need a value to be displayed everytime the value of the xcoord and ycoord suits the condition, but no value is printed even the condition is true.
You have mixed plain JavaScriptwith JQuery.
Put value to input box with JavaScript
box.value = 'passed';
CodeSnippet
function trigger(){
var x = document.getElementById('xcoord');
var y = document.getElementById('ycoord');
var box = document.getElementById('touch');
if (x.value >= 325 || x.value <= 300 && y.value >= 55 || y.value <= 25) {
box.value = 'passed';
}
}
<input onchange="trigger()" required type="number" id="xcoord" name="xcoord">
<input onchange="trigger()" required type="number" id="ycoord" name="ycoord">
<input required type="text" id="touch" name="touch">
Put value to input box with JQuery
$('#touch').val('passed'); //Although you already have the box variable
CodeSnippet
function trigger(){
var x = document.getElementById('xcoord');
var y = document.getElementById('ycoord');
var box = document.getElementById('touch');
if (x.value >= 325 || x.value <= 300 && y.value >= 55 || y.value <= 25) {
$('#touch').val('passed');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input onchange="trigger()" required type="number" id="xcoord" name="xcoord">
<input onchange="trigger()" required type="number" id="ycoord" name="ycoord">
<input required type="text" id="touch" name="touch">
tl;dr;
Since you started code with plain JavaScriptyou confused how to change the value with jQuerysyntax.
JavaScript box.value = 'passed';
jQuery $('#touch').val('passed');
You are using the jQuery Library. Use better than jQuery methods.
$("#xcoord , #ycoord").on("keyup", function(){
var x = $('#xcoord').val();
var y = $('#ycoord').val();
$('#touch').val((x >= 325 || x <= 300) && (y >= 55 || y <= 25)?'passed':'');
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input required type="number" id="xcoord" name="xcoord" value="0">
<input required type="number" id="ycoord" name="ycoord" value="0">
<input required type="text" id="touch" name="touch">
it should be
$('#touch').val('passed');
Related
I created two input fields where they should substract from each other keeping a max value at 100.
Currently it substracted value is shown in the second value. I want it to be interchangeable. Irrespective of whether I put in first or second input field, the answer shows in the other.
Could someone help?
function updateDue() {
var total = parseInt(document.getElementById("totalval").value);
var val2 = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val2) { val2 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val2;
var val1 = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val1) { val1 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val1;
}
<input type="hidden" id="totalval" name="totalval" value="100" onchange="updateDue()">
<div>
Enter Value:
<input type="text" name="inideposit" class="form-control" id="inideposit" onchange="updateDue()">
</div>
<div>
Substracted:
<input type="text" name="remainingval" class="form-control" id="remainingval" onchange="updateDue()">
</div>
The simple way to achieve this would be to group the inputs by class and attach a single event handler to them. Then you can take the entered value from 100, and set the result to the field which was not interacted with by the user. To do that in jQuery is trivial:
$('.updatedue').on('input', function() {
var total = parseInt($('#totalval').val(), 10) || 0;
var subtracted = total - (parseInt(this.value, 10) || 0);
$('.updatedue').not(this).val(subtracted);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="totalval" name="totalval" value="100" />
<div>
Enter Value:
<input type="text" name="inideposit" class="updatedue form-control" id="inideposit" />
</div>
<div>
Subtracted:
<input type="text" name="remainingval" class="updatedue form-control" id="remainingval" />
</div>
You can easily validate this so that outputs < 0 and > 100 can be discounted, if required.
Edit your code as below
function updateDue(box) {
var total = parseInt(document.getElementById("totalval").value);
if(box == 1){
var val = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val) { val = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val;
}else if(box == 2){
var val = parseInt(document.getElementById("remainingval").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val) { val = 0; }
var ansD = document.getElementById("inideposit");
ansD.value = total - val;
}
}
<input type="hidden" id="totalval" name="totalval" value="100" onchange="updateDue(0)">
<div>
Enter Value:
<input type="text" name="inideposit" class="form-control" id="inideposit" onchange="updateDue(1)">
</div>
<div>
Substracted:
<input type="text" name="remainingval" class="form-control" id="remainingval" onchange="updateDue(2)">
</div>
EDIT2: I removed the input validations, so now values don't get corrupted.
Added more functions to onkeyup method. However, if for eg, I enter three values, for Widht, GSM and Weight, Length will be calculated but since all functions are in on key up, along with length, other values change as well.
How do I make it so that when Length is being calculated, other values don't alter?
EDIT: For eg, if value for Length, Width and GSM is provided, then value for Weight will be assigned { formula: Length * Width * GSM/3100 }
if value for Width, GSM and Weight are given, then Length should be calculated { formula: (Weight * 3100) / width * GSM }
and so on.
I have four input boxes, What I want is when the user puts in any of the three boxes the fourth value should generate automatically in the fourth box.
Right now my code works when there is a fixed box in which we have to get the fourth value
New HTML:
<!DOCTYPE html>
<html>
<head>
<title>Paper Calc 2</title>
<script type="text/javascript" src = "js/test.js"></script>
<link rel="stylesheet" type="text/css" href="css/CALC.css">
<meta charset="utf-8">
</head>
<body>
<div class="container-fluid">
<div id = "case_one" class="calcoptions sizemod">
<h5>1. To find the weight (in <b>Kilograms</b>) of a ream containing 500 sheets of a given size in <b>inches</b> and <b>Gram-Weight.</b></h5>
<br>
<div class="row">
<div class="col-md-6">
Length: <input type="number" step="0.01" name="length_in" id="length" placeholder="Length(inch)" onkeyup="fun(); fun2(); fun3();">inch
<br><br>
Width: <input type="number" step="0.01" name="width_in" id="width" placeholder="Width(inch)" onkeyup="fun(); fun2(); fun4();">inch
<br><br>
GSM: <span class="extraSpace"> </span><input type="number" step="0.01" name="length_in" id="GSM" placeholder="GSM" onkeyup="fun(); fun3(); fun4();"> <!-- <button type = "button" name = "calc2" class = 'btnclass' id="cal2" onclick="func2()"> calc2-->
</button>
<br><br>
Weight: <input type="number" step = "0.01" name="Weight_Kg" id = "weight" onkeyup="fun2(); fun3(); fun4();"> <!-- KG <button type = "button" name = "calc1" id="cal1" class = 'btnclass' onclick="func1()">
calc1 -->
</button>
<br><br>
</div>
<p id='err'></p>
</body>
</html>
New JS:
function fun()
{
var l = document.getElementById('length').value;
var w = document.getElementById('width').value;
var g = document.getElementById('GSM').value;
if (l && w && g)
{
var wt = document.getElementById('weight');
var calculate = (eval(l)*eval(w)*eval(g))/3100;
wt.value = calculate.toFixed(2);
}
};
function fun2()
{
var l = document.getElementById('length').value;
var w = document.getElementById('width').value;
var wt = document.getElementById('weight').value;
if (l && w && wt)
{
var g = document.getElementById('GSM');
var calculate = (eval(wt)*3100)/(eval(l)*eval(w));
g.value = calculate.toFixed(2);
}
};
function fun3()
{
var l = document.getElementById('length').value;
var wt = document.getElementById('weight').value;
var g = document.getElementById('GSM').value;
if (l && g && wt)
{
var w = document.getElementById('width');
var calculate = (eval(wt)*3100)/(eval(l)*eval(g));
w.value = calculate.toFixed(2);
}
};
function fun4()
{
var w = document.getElementById('width').value;
var wt = document.getElementById('weight').value;
var g = document.getElementById('GSM').value;
if (w && g && wt)
{
var l = document.getElementById('length');
var calculate = (eval(wt)*3100)/(eval(w)*eval(g));
l.value = calculate.toFixed(2);
}
};
function calculateWeightInInches() {
var Length = document.getElementById("txt_weight").value;
var width = document.getElementById("txt_width").value;
var GSM = document.getElementById("txt_GSM").value;
var calculate = (Length * width * GSM) / 3100;
var result = document.getElementById("txt_Result");
// if (Length < 0)
// {
// document.getElementById('err').innerHTML = 'Incorrect Length!';
// }
error = document.getElementById('err_1');
if (calculate < 0 || width > 300 || width < 1 || GSM < 5 || GSM > 800 || Length < 1 || Length > 99) {
result.value = 0;
error.style.display = 'block';
} else {
result.value = calculate.toFixed(2);
error.style.display = 'none';
}
}
<div class="container-fluid">
<div id="case_one" class="calcoptions sizemod">
<h5>1. To find the weight (in <b>Kilograms</b>) of a ream containing 500 sheets of a given size in <b>inches</b> and <b>Gram-Weight.</b></h5>
<br>
<div class="row">
<div class="col-md-6">
Length: <input type="number" step="0.01" name="length_in" id="txt_weight" placeholder="Length(inch)" min="1" max="99" onkeyup="calculateWeightInInches();">inch
<br><br> Width: <input type="number" step="0.01" name="width_in" id="txt_width" placeholder="Width(inch)" min="1" max='300' onkeyup="calculateWeightInInches();">inch
<br><br> GSM: <span class="extraSpace"> </span><input type="number" min="5" max="800" step="0.01" name="length_in" id="txt_GSM" placeholder="GSM" onkeyup="calculateWeightInInches();">
<br><br> Weight: <input type="number" step="0.01" name="Weight_Kg" id="txt_Result" readonly="readonly">KG
<br><br>
</div>
<div class="col-md-6">
<p id="err_1" style="display: none;">
Valid Range: <br> L = 1 to 99 inch <br> W = 1 to 99 inch <br> GSM = 5 to 800 <br><br> Formula: (Length * width * GSM) / 3100
</p>
</div>
</div>
</div>
<div id="case_two" class="calcoptions sizemod">
I am trying by putting another function in onkeyup but it ruins the code.
[because values keep changing]
Any help would be appreciated!
function calculateWeightInInches() {
var Length = document.getElementById("txt_weight").value;
var width = document.getElementById("txt_width").value;
var GSM = document.getElementById("txt_GSM").value;
var calculate = (Length * width * GSM) / 3100;
var result = document.getElementById("txt_Result");
// if (Length < 0)
// {
// document.getElementById('err').innerHTML = 'Incorrect Length!';
// }
error = document.getElementById('err_1');
if(calculate < 0 || width > 300 || width < 1 || GSM < 5 || GSM > 800 || Length < 1 || Length > 99)
{
result.value = 0;
error.style.display = 'block';
}
else
{
if(Length && width && GSM) {
var GSMElement = document.getElementById("txt_GSM");
var lengthElement = document.getElementById("txt_weight");
var widthElement = document.getElementById("txt_width");
var elementsArray = [GSMElement,widthElement,lengthElement]
elementsArray.forEach(function(ele){
ele.addEventListener('change', function() {
result.value = calculate.toFixed(2);
error.style.display = 'none';
})
})
}
}
}
I have two text input for the user to type numbers, and I would like the page to output the total of these two numbers in another text input
<input id="attendance_1" onchange="parseInt(document.getElementById('attendance_output').value) += parseInt(this.value);" type="text" name="attendance_1" value="" />
<input id="attendance_2" onchange="parseInt(document.getElementById('attendance_output').value) += parseInt(this.value);" type="text" name="attendance_2" value="" />
// The results of adding the two text values should go here
<input id="attendance_output" type="text" value="" />
I get the error:
ReferenceError: invalid assignment left-hand side
I suggest putting the code of your onchange in a function and just calling that function onclick. It makes things way more easy to debug.
Example
function addValue(field) {
parseInt(document.getElementById('attendance_output').value) += parseInt(field.value);
}
<input id="attendance_1" onchange="addValue(this)" type="text" name="attendance_1" value="" />
<input id="attendance_2" onchange="parseInt(document.getElementById('attendance_output').value) += parseInt(this.value);" type="text" name="attendance_2" value="" />
// The results of adding the two text values should go here
<input id="attendance_output" type="text" value="" />
But the problem is, that your calculation is not assigned to anything. You take the field value, parse it and try to and a value to the parse result.
I guess you want to add that value to the field value and assign it?!
function addValue(field) {
var val = parseInt(document.getElementById('attendance_output').value);
val += parseInt(field.value);
document.getElementById('attendance_output').value = val;
}
Try below code. it should work.
your code is not working because += sign in expression.
<input id="attendance_1" onchange="document.getElementById('attendance_output').value=parseInt(document.getElementById('attendance_output').value) + parseInt(this.value);" type="text" name="attendance_1" value="" />
<input id="attendance_2" onchange="document.getElementById('attendance_output').value=parseInt(document.getElementById('attendance_output').value) + parseInt(this.value);" type="text" name="attendance_2" value="" />
// The results of adding the two text values should go here
<input id="attendance_output" type="text" value="" />
So this is really basic JS with typechecks
function addValue(field) {
parseInt(document.getElementById('attendance_output').value) += parseInt(field.value);
}
<input id="attendance_1" onchange="addValue(this)" type="text" name="attendance_1" value="" />
<input id="attendance_2" onchange="parseInt(document.getElementById('attendance_output').value) += parseInt(this.value);" type="text" name="attendance_2" value="" />
// The results of adding the two text values should go here
<input id="attendance_output" type="text" value="" />
But the problem is, that your calculation is not assigned to anything. You take the field value, parse it and try to and a value to the parse result.
I guess you want to add that value to the field value and assign it?!
function addValue(field) {
var oVal = parseInt(document.getElementById('attendance_output').value);
var iVal = parseInt(field.value);
if(!oVal || Number.isNaN(oVal)) {
oVal = 0;
}
if(!iVal || Number.isNaN(iVal)) {
iVal = 0;
}
oVal = oVal + iVal;
document.getElementById('attendance_output').value = oVal;
}
try this. :) it will not work properly if the user input string, so i think it should have validation.
function addValue() {
var num1 = document.getElementById('attendance_1').value;
var num2 = document.getElementById('attendance_2').value;
if (num1 === ''){
num1 = 0;
}
if(num2 === ''){
num2 = 0;
}
var sum = parseInt(num1) + parseInt(num2);
document.getElementById('attendance_output').value = sum;
}
you can make the textbox accept only numbers, by using jquery
$(document).ready(function() {
$("#attendance_1, #attendance_2").keydown(function (e) {
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
(e.keyCode == 65 && ( e.ctrlKey === true || e.metaKey === true ) ) ||
(e.keyCode >= 35 && e.keyCode <= 40)) {
return;
}
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});
Use this code inside
onchange="document.getElementById('attendance_output').value=+document.getElementById('attendance_output').value+ +this.value"
Hope it will be useful for you :)
This may be an option. I removed the inline JS completely. Went from onchange to an oninput handler, which will only do the calculation if the values given are actually numbers not strings.
var inpt = document.querySelectorAll('.attendance');
var out = document.getElementById('attendance_output');
var onInput = function(e) {
if(/\d/.test(this.value)) {
var sum = [].slice.call(inpt).reduce(function(a, b) {
if (a.value.length && b.value.length) {
return +a.value + +b.value;
} else {
return +a.value || +b.value;
}
})
out.value = sum || this.value;
} else {
out.value = "";
}
}
inpt.forEach(function(el) {
el.addEventListener('input', onInput, false)
})
<input class="attendance" type="text" name="attendance_1" value="" /> <span>+</span>
<input class="attendance" type="text" name="attendance_2" value="" />
<br><br>
<input id="attendance_output" type="text" value="" disabled />
I am trying to take two numbers from html and using javascript return sum of both but my num1 and num2 contains HTMLInputElement??
html:
<head>
<script type ="text/javascript" src="functions.js"></script>
</head>
<body>
Value 1: <input type="text" id="tb1" name="tb1"><br/>
Value 2: <input type="text" id="tb2" name="tb2"><br/>
Result: <input type="text" id="tb3" name="tb3"><br/>
<button onclick="validateForm()" Type="button" id="b1" name="b1">Go</button>
</body>
javascript:
function validateForm() {
var x = document.getElementById("tb1");
var y = document.getElementById("tb2");
if (x == null || x == "" || y == null || y == "")
{
alert("Value cannot be empty");
return false;
}
else {
//myAdd(x,y);
alert(x + y);
var num1 = parseFloat(x);
var num2 = parseFloat(y);
var total = num1 + num2;
document.getElementById("tb3").innerHTML = total;
}
}
You are not parsing and adding values from those two inputs, but objects itself. Because of that your if statement block would never run, as you are comparing object to null.Also and you can't set innerHTML of an input,have to use .value.Check the snippet below
parseFloat(x) //you must parseFloat(x.value),
document.getElementById("tb3").value = total; //you have to use .value instead of .innerHTML with input
function validateForm() {
var x = document.getElementById("tb1").value;
var y = document.getElementById("tb2").value;
if (x == null || x === "" || y == null || y === "") {
alert("Value cannot be empty");
return false;
} else {
//myAdd(x,y);
var num1 = parseFloat(x);
var num2 = parseFloat(y);
var total = num1 + num2;
document.getElementById("tb3").value = total;
}
}
Value 1:
<input type="text" id="tb1" name="tb1">
<br/>Value 2:
<input type="text" id="tb2" name="tb2">
<br/>Result:
<input type="text" id="tb3" name="tb3">
<br/>
<button onclick="validateForm()" Type="button" id="b1" name="b1">Go</button>
I am by no means a programmer but I managed to get this to work in Chrome but I get "NaN" when I try it on IE (11 if that matters).
It basically takes 4 criteria and does some math to give a price quote.Can anyone help with this?
<html>
<head>
<title>instant inspection quote tool</title>
<SCRIPT Language="JavaScript">
function calculateFee(frm){
var building = frm.building.value
var distance = frm.distance.value
var age = frm.age.value
var sqft = frm.sqft.value
var total = 0
building = Number(building)
distance = Number(distance)
age = Number(age)
sqft = Number(sqft)
total = Number(total)
total = building + distance + age + sqft
frm.total.value = total
}
</script>
</head>
<body>
<h1>Inspection Fee Calculator</h1>
<form method="post" action="">
Select the type of home
<br><input type="radio" name="building" value="375"> detached
<br><input type="radio" name="building" value="350"> semi-detached
<br><input type="radio" name="building" value="350"> condo or freehold townhome - end unit
<br><input type="radio" name="building" value="325"> condo or freehold townhome - interior unit
<br><input type="radio" name="building" value="299"> condo apartment
<br><br>Is the home within 50 kms of Ottawa?
<br><input type="radio" name="distance" value="0"> yes
<br><input type="radio" name="distance" value="25"> no
<br><br>Is the home less than 50 years old?
<br><input type="radio" name="age" value="0"> yes
<br><input type="radio" name="age" value="25"> no
<br><br>Is the home less than 2000 square feet?
<br><input type="radio" name="sqft" value="0"> yes
<br><input type="radio" name="sqft" value="25"> no
<br><br>
<input type="button" name="button" value="Calculate Fee" onClick="calculateFee(this.form)">
<table>
<tr>
<td align="right">Total Inspection fee:</td>
<td>
<input type="text" name="total" size="30" maxlength="30">
</td>
</tr>
</table>
</form>
</body>
</html>
Try this - note: querySelector and querySelectorAll do not work in IE < 8 and in 8 only in standards mode
Live Demo
function calculateFee(frm) {
var total = 0,
rads = frm.querySelectorAll('input:checked'); // get all checked radios
for (var i = 0; i < rads.length; i++) {
var num = Number(rads[i].value);
total += isNaN(num) ? 0 : num;
}
frm.total.value = total;
}
For individual radio values use the name - however getting the value directly it will fail if the radio is not checked
var building = frm.querySelector("input[name=building]:checked");
if (building) total += Number(building.value);
To validate, hook up the form's onsubmit
function validate(frm) {
var rads = frm.querySelectorAll('input:checked'); // get all checked radios
if (rads.length<4) {
alert("Please select one of each");
return false; // cancel form
}
return true;
}
window.onload=function() {
document.forms[0].onsubmit=function() {
return validate(this);
}
}
If none of the values are "checked" off then the values are undefined try adding this...
function getRadioValue( radioElement ){
for (var i=0; i < radioElement.length; i++){
if ( radioElement[i].checked ){
return radioElement[i].value;
}
}
}
Replace previous code with this...
var building = getRadioValue( frm.building ) || 0;
var distance = getRadioValue( frm.distance ) || 0;
var age = getRadioValue( frm.age ) || 0;
var sqft = getRadioValue( frm.sqft ) || 0;
var total = 0
Try this:
var building = frm.querySelector("[name=building]:checked");
var distance = frm.querySelector("[name=distance]:checked");
var age = frm.querySelector("[name=age]:checked");
var sqft = frm.querySelector("[name=sqft]:checked");
building = (building && building.value) || 0;
distance = (distance && distance.value) || 0;
age = (age && age.value) || 0;
sqft = (sqft && sqft.value) || 0;