How to get the value of variable using the value of textbox? - javascript

<input class="red" id="LR2" type="text" value="1" >
<p id="demo"></p> <br>
This is my JS code:
<script>
var price3 = 7; <br>
var price4 = 8; <br>
var selectValue = function RedAlert(data) { <br>
if( $("#LR2").val() = 0) { <br>
var price1 = 5; <br>
} <br>
else { <br>
var price2 = 6; <br>
} <br>
} <br>
var total = selectValue + price3 + price4; <br>
document.getElementById("LR2").innerHTML = <br>
"The total is: " + total; <br>
</script> <br>

maybe
$("#LR2").val() = 0
should be :
$("#LR2").val() == 0
also not sure if the value isn't a string... maybe should cast to number like :
Number( $("#LR2").val() ) == 0

Try this
var selectValue = 0;
if( $("#LR2").val() == 0) {
selectValue = 5;
}
else {
selectValue = 6;
}

Related

Form doesn't remove alert from the first input box when the input being an empty string is changed to false

I am doing an assignemnt for school to showcase our knowledge of javascript. It is doing everything I want it to except when I adjust the first input from an empty string to a value it still has the display of first name required. I was also wondering if anyone had insight as to how to display the needed inputs when the other buttons I have clicked are cliked as I don't want the other functions to run unless all inputs are filled in the form. Thanks!
//Function to validate form inputs
function validate() {
var fname = document.getElementById("t1").value;
var lname = document.getElementById("t2").value;
var phoneNumber = document.getElementById("t3").value;
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var isValid = true;
if (fname == "") {
document.getElementById("t1result").innerHTML = " First Name is required";
isValid = false;
} else {
document.getElementById("t2result").innerHTML = "";
}
if (lname == "") {
document.getElementById("t2result").innerHTML = " Last Name is required";
isValid = false;
} else {
document.getElementById("t3result").innerHTML = "";
}
if (phoneNumber == "") {
document.getElementById("t3result").innerHTML = " Phone number is required";
isValid = false;
} else {
document.getElementById("t3result").innerHTML = "";
}
if (prodOne == "") {
document.getElementById("t4result").innerHTML = " Product 1 is required";
isValid = false;
} else {
document.getElementById("t4result").innerHTML = "";
}
if (prodTwo == "") {
document.getElementById("t5result").innerHTML = " Product 2 is required";
isValid = false;
} else {
document.getElementById("t5result").innerHTML = "";
}
if (prodThree == "") {
document.getElementById("t6result").innerHTML = " Product 3 is required";
isValid = false;
} else {
document.getElementById("t6result").innerHTML = "";
}
}
//Function to calculate cost of all 3 products prior to tax
function calculate() {
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var totalCost = parseInt(prodOne) + parseInt(prodTwo) + parseInt(prodThree)
document.getElementById('totalAmount').innerHTML = "The total cost of the three products before tax is: $" + totalCost;
}
//Function to calculate cost of all 3 products with tax
function taxIncluded() {
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var totalCost = parseInt(prodOne) + parseInt(prodTwo) + parseInt(prodThree)
var totalCostTaxed = parseFloat(totalCost) * 0.13 + parseFloat(totalCost)
document.getElementById('totalAmountTax').innerHTML = "The total cost of the three products with tax is: $" + totalCostTaxed;
}
<form id="f1" method="get" action="secondpage.html">
First Name: <input type="text" id="t1"><span class="result" id="t1result"></span>
<br><br> Last Name: <input type="text" id="t2"><span class="result" id="t2result"></span>
<br><br>Phone Number: <input type="text" id="t3"><span class="result" id="t3result"></span>
<br><br>Product 1 amount: <input type="text" id="t4"><span class="result" id="t4result"></span>
<br><br>Product 2 amount: <input type="text" id="t5"><span class="result" id="t5result"></span>
<br><br>Product 3 amount: <input type="text" id="t6"><span class="result" id="t6result"></span>
<br><br><input type="button" id="btn1" value="Validate" onclick="validate()">
<br><br><input type="button" id="btn1" value="Calculate" onclick="calculate()">
<br><br><input type="button" id="btn1" value="Calculate with Tax" onclick="taxIncluded()">
<div>
<p id="totalAmount">Total Amount</p>
</div>
<div>
<p id="totalAmountTax">Tax</p>
</div>
</form>
//Function to validate form inputs
function validate() {
var fname = document.getElementById("t1").value;
var lname = document.getElementById("t2").value;
var phoneNumber = document.getElementById("t3").value;
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var isValid = true;
if (fname == "") {
document.getElementById("t1result").innerHTML = " First Name is required";
isValid = false;
} else {
document.getElementById("t1result").innerHTML = "";
}
if (lname == "") {
document.getElementById("t2result").innerHTML = " Last Name is required";
isValid = false;
} else {
document.getElementById("t3result").innerHTML = "";
}
if (phoneNumber == "") {
document.getElementById("t3result").innerHTML = " Phone number is required";
isValid = false;
} else {
document.getElementById("t3result").innerHTML = "";
}
if (prodOne == "") {
document.getElementById("t4result").innerHTML = " Product 1 is required";
isValid = false;
} else {
document.getElementById("t4result").innerHTML = "";
}
if (prodTwo == "") {
document.getElementById("t5result").innerHTML = " Product 2 is required";
isValid = false;
} else {
document.getElementById("t5result").innerHTML = "";
}
if (prodThree == "") {
document.getElementById("t6result").innerHTML = " Product 3 is required";
isValid = false;
} else {
document.getElementById("t6result").innerHTML = "";
}
}
//Function to calculate cost of all 3 products prior to tax
function calculate() {
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var totalCost = parseInt(prodOne) + parseInt(prodTwo) + parseInt(prodThree)
document.getElementById('totalAmount').innerHTML = "The total cost of the three products before tax is: $" + totalCost;
}
//Function to calculate cost of all 3 products with tax
function taxIncluded() {
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var totalCost = parseInt(prodOne) + parseInt(prodTwo) + parseInt(prodThree)
var totalCostTaxed = parseFloat(totalCost) * 0.13 + parseFloat(totalCost)
document.getElementById('totalAmountTax').innerHTML = "The total cost of the three products with tax is: $" + totalCostTaxed;
}
<form id="f1" method="get" action="secondpage.html">
First Name: <input type="text" id="t1"><span class="result" id="t1result"></span>
<br><br> Last Name: <input type="text" id="t2"><span class="result" id="t2result"></span>
<br><br>Phone Number: <input type="text" id="t3"><span class="result" id="t3result"></span>
<br><br>Product 1 amount: <input type="text" id="t4"><span class="result" id="t4result"></span>
<br><br>Product 2 amount: <input type="text" id="t5"><span class="result" id="t5result"></span>
<br><br>Product 3 amount: <input type="text" id="t6"><span class="result" id="t6result"></span>
<br><br><input type="button" id="btn1" value="Validate" onclick="validate()">
<br><br><input type="button" id="btn1" value="Calculate" onclick="calculate()">
<br><br><input type="button" id="btn1" value="Calculate with Tax" onclick="taxIncluded()">
<div>
<p id="totalAmount">Total Amount</p>
</div>
<div>
<p id="totalAmountTax">Tax</p>
</div>
</form>
you were getting wrong element in your function validate in first condition , in else condition you were getting t2result instead of t1, hope this will work now.

My JavaScript isn't responding to my HTML and CSS properly (namely buttons and <form> tags)

I am currently working on a donate page for a site that I'm working on in my free time. It's been going smoothly up until last week when I encountered a problem. My JS isn't responding properly to my HTML and I can't fix it. Here's my HTML:
var donateAmount = document.getElementById("selectedAmount");
if (donateAmount.value == "amount0") {
var totalAmount = 0;
} else if (donateAmount.value == "amount1") {
var totalAmount = 10;
} else if (donateAmount.value == "amount2") {
var totalAmount = 50;
} else if (donateAmount.value == "amount3") {
var totalAmount = 100;
} else if (donateAmount.value == "amount4") {
var totalAmount = 500;
};
function donateIsPressed() {
if (totalAmount >= = 0) {
alert("Thank you for your donation of " + totalAmount "$!")
} else {
alert("You didn't select anything!")
};
};
<form id="selectedAmount" name="selectedAmount">
<input type="radio" name="donateRadio" value="amount0"> 0 Dollars </input> <br>
<input type="radio" name="donateRadio" value="amount1"> 10 Dollars </input> <br>
<input type="radio" name="donateRadio" value="amount2"> 50 Dollars </input> <br>
<input type="radio" name="donateRadio" value="amount3"> 100 Dollars </input> <br>
<input type="radio" name="donateRadio" value="amount4"> 500 Dollars </input>
</form>
<div onclick='donateIsPressed ();' class="donateButton" id="processDonation"> test donate button </div>
The HTML is pretty simple, there's a tag with multiple options, and a button that's supposed to start the transaction. What the JS is supposed to do is to check what option is selected, then set the "totalAmount" variable to whatever is selected. Then it's supposed to give an answer depending on what totalAmount's value is. However, none of it works, and I'm currently getting nowhere with fixing. So I would appreciate it if one of you guys could point me in the right direction
Thanks in advance.
Try this.
function donateIsPressed() {
var donateAmount = document.querySelector('input[name="donateRadio"]:checked');
if (donateAmount) {
if (donateAmount.value == "amount0") {
var totalAmount = 0;
} else if (donateAmount.value == "amount1") {
var totalAmount = 10;
} else if (donateAmount.value == "amount2") {
var totalAmount = 50;
} else if (donateAmount.value == "amount3") {
var totalAmount = 100;
} else if (donateAmount.value == "amount4") {
var totalAmount = 500;
};
}
if (totalAmount >= 0) {
alert("Thank you for your donation of " + totalAmount + "$!")
} else {
alert("You didn't select anything!")
};
};
<form id="selectedAmount" name="selectedAmount">
<input type="radio" name="donateRadio" value="amount0"> 0 Dollars </input> <br>
<input type="radio" name="donateRadio" value="amount1"> 10 Dollars </input> <br>
<input type="radio" name="donateRadio" value="amount2"> 50 Dollars </input> <br>
<input type="radio" name="donateRadio" value="amount3"> 100 Dollars </input> <br>
<input type="radio" name="donateRadio" value="amount4"> 500 Dollars </input>
</form>
<div onclick='donateIsPressed ();' class="donateButton" id="processDonation"> test donate button </div>
I tried to solve your problem :
First I changed buttons value
Then I implement this logic :
var donateAmount = document.getElementById("selectedAmount");
var totalAmount = -1
function donateIsPressed() {
var radios = donateAmount.elements["donateRadio"];
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) { // radio checked?
totalAmount = parseInt(radios[i].value); // if so, hold its value in val
break; // and break out of for loop
}
}
if (totalAmount >= 0) {
alert("Thank you for your donation of " + totalAmount + "$!")
} else {
alert("You didn't select anything!")
};
};
<form id="selectedAmount" name="selectedAmount">
<input type="radio" name="donateRadio" value="0"> 0 Dollars </input> <br>
<input type="radio" name="donateRadio" value="10"> 10 Dollars </input> <br>
<input type="radio" name="donateRadio" value="50"> 50 Dollars </input> <br>
<input type="radio" name="donateRadio" value="100"> 100 Dollars </input> <br>
<input type="radio" name="donateRadio" value="500"> 500 Dollars </input>
<div onclick='donateIsPressed ();' class="donateButton" id="processDonation"> test donate button </div>
</form>
//Globals
let procesDonation, selectedAmount;
const data = {amount0: 0, amount1: 10, amount2: 50, amount3: 100, amount4: 500};
//Setup
const setup = () => {
//Id's should be unique and so can be set gobal
processDonation = document.querySelector('#processDonation');
selectedAmount = document.querySelector('#selectedAmount');
processDonation.addEventListener('click', donateOnClick);
};
//Functions
const donateOnClick = (event) => {
if(selectedAmount == null) return;
const target = event.currentTarget;
if(target.nodeName == 'DIV') {
const selectedButton = selectedAmount.querySelector('[name="donateRadio"]:checked');
const key = selectedButton?.value;
const amount = getAmount(key);
donateMessage(amount);
}
};
const getAmount = (key) => {
if(data == null || key == null || !Object.keys(data).includes(key)) return;
return data[key] || 0;
}
const donateMessage = (amount) => {
if(amount == null) return;
const message = amount > 0 ? `Thank you for your donation of ${amount}$!"` : `You didn't select anything!`;
alert(message);
}
window.addEventListener('load', setup);
<form id="selectedAmount" name="selectedAmount">
<input type="radio" name="donateRadio" value="amount0" checked> <label>0 Dollars</label> <br>
<input type="radio" name="donateRadio" value="amount1"> <label>10 Dollars</label> <br>
<input type="radio" name="donateRadio" value="amount2"> <label>50 Dollars</label> <br>
<input type="radio" name="donateRadio" value="amount3"> <label>100 Dollars</label> <br>
<input type="radio" name="donateRadio" value="amount4"> <label>500 Dollars</label>
</form>
<div class="donateButton" id="processDonation"> test donate button </div>
var totalAmount = 0;
var donateAmount = document.getElementById("selectedAmount");
function donateIsPressed() {
if (donateAmount.value == "amount1") {
var totalAmount = 10;
} else if (donateAmount.value == "amount2") {
var totalAmount = 50;
} else if (donateAmount.value == "amount3") {
var totalAmount = 100;
} else if (donateAmount.value == "amount4") {
var totalAmount = 500;
};
if (totalAmount >= 0) { // extra = here, removed
alert("Thank you for your donation of " + totalAmount "$!")
} else {
alert("You didn't select anything!")
};
};

Auto substract both values from 100

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>

Javascript : Cant get radio button value in var

I am trying to do arithmetic operation based on radio button value.
<html>
<body>
<br>Enter first number:
<input type="text" id="txt1" name="text1">Enter second number:
<input type="text" id="txt2" name="text2">
<form>
<input type="radio" name="oper" value="1" checked>Add
<br>
<input type="radio" name="oper" value="2">Multiply
<br>
<input type="radio" name="oper" value="3">Subtract
</form>
<p id="demo"></p>
<script>
function myFunction() {
var y = document.getElementById("txt1").value;
var z = document.getElementById("txt2").value;
var o = getCheckedRadioValue("oper");
if(+o == 1)
var x = +y + +z;
if(+o == 2)
var x = +y * +z;
if(+o == 3)
var x = +y - +z;
document.getElementById("demo").innerHTML = x;
</script>
<button onclick="myFunction()">Calculate</button>
<br/>
</body>
</html>
You might be have problem with getCheckedRadioValue function.
To get the radio button check box values using jQuery
var o = $("input:radio[name='oper']:checked").val();
Try to Execute like this
<script>
function myFunction() {
var y = document.getElementById("txt1").value;
var z = document.getElementById("txt2").value;
var o = $("input:radio[name='oper']:checked").val();
if(+o == 1)
var x = +y + +z;
if(+o == 2)
var x = +y * +z;
if(+o == 3)
var x = +y - +z;
// alert(x);
document.getElementById("demo").innerHTML = x;
}
</script>
<br/>
</body>
</html>
Thanks.
Try Like this :
Enter first number:
Enter second number:
<form>
<input type="radio" name="oper" value= 1 checked />Add
<br>
<input type="radio" name="oper" value=2 />Multiply
<br>
<input type="radio" name="oper" value=3 />Subtract
</form>
<p id="demo"></p>
<button id="submit">Calculate</button>
$( "#submit" ).click(function() {
var y = $("#txt1").val();
var z = $("#txt2").val();
var selected = $("input[type='radio']:checked");
var o =selected.val();
if(o == 1)
var x = +y + +z;
if(o == 2)
var x = +y * +z;
if(o == 3)
var x = +y - +z;
$("#demo").html(x);
});

Counting number of inputs filled

I have 4 inputs on a form and I want to do a calculation based on the number of inputs filled.
I have come up with this and it works in IE but not in FF. FF doesnt seem to like the multiple document.getElementById. Any help would be appreciated.
<script type="text/javascript" language="javascript">
function countlines(what) {
var headline = 1 ;
var oneline = 1 ;
var twoline = 1 ;
var webline = 1 ;
var valhead = document.getElementById('adverttexthead').value;
if (/^\s*$/g.test(valhead) || valhead.indexOf('\n') != -1)
{var headline = 0};
var valone = document.getElementById('adverttextone').value;
if (/^\s*$/g.test(valone) || valone.indexOf('\n') != -1)
{var oneline = 0};
var valtwo = document.getElementById('adverttexttwo').value;
if (/^\s*$/g.test(valtwo) || valtwo.indexOf('\n') != -1)
{var twoline = 0};
var valweb = document.getElementById('adverttextweb').value;
if (/^\s*$/g.test(valweb) || valweb.indexOf('\n') != -1)
{var webline = 0};
(document.getElementById('webcost').value = "$" + ((headline + oneline + twoline + webline) * 16.50).toFixed(2));
(document.getElementById('totallines').value = headline + oneline + twoline + webline);
}
</script>
HTML
<input name="adverttexthead" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<br>
<input name="adverttextone" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<br>
<input name="adverttexttwo" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<br>
<input name="adverttextweb" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<input name="totallines" id="totallines" size="4" readonly="readonly" type="text">
<input name="webcost" id="webcost" size="6" readonly="readonly" type="text">
You could put the inputs in a form and do like so:
function countFormElements(formNumber){
var fn = !formNumber ? 0 : formNumber;
var frm = document.getElementsByTagName('form')[fn], n = 0;
for(var i=0,l=frm.length; i<l; i++){
if(frm.elements[i].value !== '')n++;
}
return n;
}
console.log(countFormElements());
You did not set the 'id' attribute on some elements
You reinitialized your variables in the 'if' clauses.
Working code:
<input id="adverttexthead" name="adverttexthead" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<br>
<input id="adverttextone" name="adverttextone" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<br>
<input id="adverttexttwo" name="adverttexttwo" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<br>
<input id="adverttextweb" name="adverttextweb" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<input id="totallines" name="totallines" size="4" readonly="readonly" type="text">
<input id="webcost" name="webcost" size="6" readonly="readonly" type="text">
function countlines(what) {
var headline = 1;
var oneline = 1;
var twoline = 1;
var webline = 1;
var valhead = document.getElementById('adverttexthead').value;
if (/^\s*$/g.test(valhead) || valhead.indexOf('\n') != -1) {
headline = 0
};
var valone = document.getElementById('adverttextone').value;
if (/^\s*$/g.test(valone) || valone.indexOf('\n') != -1) {
oneline = 0
};
var valtwo = document.getElementById('adverttexttwo').value;
if (/^\s*$/g.test(valtwo) || valtwo.indexOf('\n') != -1) {
twoline = 0
};
var valweb = document.getElementById('adverttextweb').value;
if (/^\s*$/g.test(valweb) || valweb.indexOf('\n') != -1) {
webline = 0
};
(document.getElementById('webcost').value = "$" + ((headline + oneline + twoline + webline) * 16.50).toFixed(2));
(document.getElementById('totallines').value = headline + oneline + twoline + webline);
}
Here is a working jsFiddle: http://jsfiddle.net/YC6J7/1/
You'll need to set the id attribute for the inputs as well as the name, otherwise getElementById works inconsistently cross browser.
For instance:
<input id="adverttexthead" name="adverttexthead" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
(Technically name is optional for purposes of document.getElementById, since id is accepted pretty universally, but you'll probably want to keep it so your forms submit correctly.)
For more details, see: Document.getElementById() returns element with name equal to id specified

Categories