change value when checked [closed] - javascript

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I am new into HTML DOM . I am trying to change value when check-box checked.
So here is my unfinished script:
<html>
<script type="text/javascript">
var val=12;
document.write("<p>"+val+"</p>");
function checkAddress()
{
var chkBox = document.getElementById('checkAddress');
if (chkBox.checked)
{
var val=val+2;
}
}
function checkAddress2()
{
var chkBox = document.getElementById('checkAddress2');
if (chkBox.checked)
{
var val=val+3;
}
}
function checkAddress3()
{
var chkBox = document.getElementById('checkAddress3');
if (chkBox.checked)
{
var val=val+4;
}
}
</script>
<p>Get value :<input type="checkbox" id="checkAddress" name="checkAddress" onclick="checkAddress()" value="1st"/>
Get value :<input type="checkbox" id="checkAddress2" name="checkAddress" onclick="checkAddress2()" value="2nd"/>
Get value :<input type="checkbox" id="checkAddress3" name="checkAddress" onclick="checkAddress3()" value="3rd"/>
Here, i just want to make this script: when checkbox click it will change the value auto.

First off your declaring val within the {} each time which means the value is lost.
Secondly, you don't do anything with val in order for it to be useful.
Finally, you could have one function instead of three where you pass the specific checkbox that was clicked.
Additionally,as stated in the comments you do not assign val to any elements (using .innerHtml, textarea, etc). Which means value is not seen.
<html>
<script type="text/javascript">
var val=12;
function resetCheckboxes()
{
document.getElementById("checkAddress").checked=false;
document.getElementById("checkAddress2").checked=false;
document.getElementById("checkAddress3").checked=false;
}
function checkAddress(chkBox)
{
var multiplyer = 1;
if (!chkBox.checked)
multiplyer = -1;
if(chkBox.id =="checkAddress")
val=val+ (multiplyer)*2;
else if(chkBox.id =="checkAddress2")
val=val+ (multiplyer)*3;
else if(chkBox.id =="checkAddress3")
val=val+ (multiplyer)*4;
document.getElementById("displayValue").innerHTML = "Val:"+val;
}
</script>
<body onLoad="resetCheckboxes()">
<div id="displayValue">Val:12</div>
<p>Get value :<input type="checkbox" id="checkAddress" name="checkAddress" onclick="checkAddress(this)" value="1st"/>
Get value :<input type="checkbox" id="checkAddress2" name="checkAddress" onclick="checkAddress(this)" value="2nd"/>
Get value :<input type="checkbox" id="checkAddress3" name="checkAddress" onclick="checkAddress(this)" value="3rd"/>
</body>
</html>

Related

Can't get if/else function to work with radio buttons

I have looked all over this site (and Google) for an answer to my problem but I can only seem to find bits and pieces, nothing specific.
I am primarily playing around with JavaScript and HTML but am not trying to use jquery right now.
So, with that said, this is what I'm trying to do: I would like the user to enter two numbers, select an operation (add, subtract, multiply, divide) out of a list of four radio buttons, and then click a button which is linked to a function that does the math and then presents it in a text box on the page. How would I do this using only HTML and JavaScript? I have gotten everything to work up until the point I add the radio buttons.
The code is as follows:
<script>
function operationForm (form) {
var x = document.operationForm.getElementById("numberOne");
var y = document.operationForm.getElementById("numberTwo");
var operation;
var answer;
if (document.operationForm.addSelect.checked === true) {
answer = x + y;
document.operationForm.answerBox.value = answer;
} else if (document.operationForm.subtractSelect.checked === true) {
answer = x - y;
document.operationForm.answerBox.value = answer;
} else if (document.operationForm.multiplySelect.checked === true) {
answer = x * y;
document.operationForm.answerBox.value = answer;
} else(document.operationForm.divideSelect.checked === true) {
answer = x / y;
document.operationForm.answerBox.value = answer;
}
}
</script>
<h1>Let's calculate!</h1>
<form name="operationForm">
<p>
<label>Enter two numbers, select an operation, and then click the button below.
<p>
<label>Number One:
<input type="text" name='numbers' id="numberOne">
<br>
<br>Number Two:
<input type="text" name='numbers' id="numberTwo">
<p>
<input type="radio" name="operations" id="addSelect" value=''>Add
<input type="radio" name="operations" id="subtractSelect" value=''>Subtract
<input type="radio" name="operations" id="multiplySelect" value=''>Multiply
<input type="radio" name="operations" id="divideSelect" value=''>Divide
<label>
<p>
<input type="button" value=" Calculate " onClick='operationForm(form);'>
<p>
<label>Your answer is:
<input type="text" name="answerBox">
If anyone has any fixes or can point me in the right direction of the correct syntax for handling radio buttons, functions linking to them, and onClick events linking to those functions, it would be extremely appreciated.
Consider replacing the <input type="button" value=" Calculate " onClick='operationForm(form);'> with <input type="button" value=" Calculate " onClick='operationForm();'>. Next change the function operationForm to accept no parameters. Then add id to your input answer box. Next for each if statement in the function use the elementById function to get the radios and the answerBox. For example, the first if should be
if (document.getElementById("addSelect").checked) {
answer = x + y;
document.getElementById("answerBox").value = answer;
}
This works:
JavaScript:
<script type="text/javascript">
function operationForm(){
var form = document.forms['operation_form'];
var x = form['numberOne'].value*1;
var y = form['numberTwo'].value*1;
var operation = null;
var answer = null;
if (form['addSelect'].checked == true) {
answer = x + y;
} else if (form['subtractSelect'].checked == true) {
answer = x - y;
} else if (form['multiplySelect'].checked == true) {
answer = x * y;
} else if (form['divideSelect'].checked == true) {
answer = x / y;
}
form['answerBox'].value = answer;
}
</script>
HTML:
<form name="operation_form">
<label>Enter two numbers, select an operation, and then click the button below.</label>
<br/>
<label>Number One:</label><input type="number" name='numberOne' />
<br/>
<br/>Number Two:</label><input type="number" name='numberTwo' />
<br/>
<input type="radio" name="operations" id="addSelect" value='' />Add
<input type="radio" name="operations" id="subtractSelect" value='' />Subtract
<input type="radio" name="operations" id="multiplySelect" value='' />Multiply
<input type="radio" name="operations" id="divideSelect" value='' />Divide
<br/>
<input type="button" value=" Calculate " onclick="operationForm();" />
<br/>
<label>Your answer is:</label><input type="text" name="answerBox">
</form>
Fixes between this and your example:
There are a ton of things wrong with the code you provided. I will update this answer shortly with as many as I can remember.
Update:
Please remember this is meant to be helpful and not punishing. So keep in mind that while listening to the attached feedback, I want you to learn this stuff.
Notes on your HTML:
1.) The biggest problem is none of the <label> elements have closing</label> tags.
Although, none of your html elements have any closing tags.
This will group all of the elements inside one big parent <label>.
So when the browser auto-closes the unclosed tags at the end of the document, this causes a hodgepodge of mixed up child elements. Close your elements.
2.) The first two text boxes have the same name="numbers" attribute. You can only do that with radio type inputs.
3.) Your <form> name="" attribute can NOT have the same name as the JavaScript function you are trying to call. They are stored in the same browser namespace so it causes an error.
Notes on your JavaScript:
1.) Your checked === true is an exact comparison. This will almost never evaluate to be truthful. Use checked == true, or better yet, just use if( my_element.checked ){}. Sometimes .checked will equal a string like this: .checked = 'checked'. So even though 'checked'==true it will never be truthful for 'checked'===true. The === means Exactly Equal. So only true===true.
2.) Your var x = document.opera.. ... .mberOne"); will store the whole <input> element into the x variable. You need to have ...mberOne").value; so just the value of the <input> is stored, not the whole html element.
3.) The only object that has a getElementById() method is the document. You can't use that from a document form object.
4.) You have to convert your x any y input values to numbers. If not, 5 + 5 will give you 55 instead of 10 because they are treated as strings. I multiplied them by * 1 to do that. I also changed the <input type='text' attribute to type='number' just to be safe.
5.) You can assign your answerBox.value just one time at the end of the function instead of doing it once per if(){} bracket. It will work the same but it's just much more readable.
6.) I used the syntax of form['numberOne'] instead of form.numberOne but they both work the same. It is referencing the element name (not necessarily the id) as it exists inside the form. <form> is the only object that lets you do this, whereas a <div> or <p> does not.

jQuery : how to access the name of the element [duplicate]

This question already has answers here:
How to reach the element itself inside jQuery’s `val`?
(4 answers)
Closed last year.
Pls see the following html code
<input id="product_code1" name="Samsung"><br>
<input id="product_code2" name="Apple"><br>
<input id="product_code3" name="Huawei"><br>
<input id="product_code4" name="Motorola"><br>
and the jquery code
$( "input[id*='product']" ).val( 'test' );
the result will display 4 textbox with the value of 'test' as default, but now i like to display 4 textbox with the value of the product name, means first textbox will display 'Samsung', 2nd textbox will display 'Apple' & so on, so what command should i put in the jquery code ? pls advise.
Just use .val(fn):
$("input[id^='product_']").val(function() {
return this.name;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="product_code1" name="Samsung"><br>
<input id="product_code2" name="Apple"><br>
<input id="product_code3" name="Huawei"><br>
<input id="product_code4" name="Motorola"><br>
For each input element it will invoke the function that will return the value to set.
Bonus
To make it even more concise you could consider a helper function, e.g.:
jQuery.prop = function(name) {
return function() {
return this[name];
}
};
Then, the code becomes:
$("input[id^='product_']").val($.prop('name'));
Try this:
$("input[id*='product']").each(function() {
$this = $(this);
$this.val($this.attr("name"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="product_code1" name="Samsung"><br>
<input id="product_code2" name="Apple"><br>
<input id="product_code3" name="Huawei"><br>
<input id="product_code4" name="Motorola"><br>
$("input[id*='product']").each(function () {
var $this = $(this);
$this.val($this.prop("name"));
});
JSFiddle

second javascript not working on my contact form

Ok, all, I have a few questions.
How can I have my total have a $ and how can I move up next to the word Total: ( so it will be side by side)
Once I get a total price, is there a way where I can divide it by 2 to get 1/2 of the price into another field called 'deposit' before copying that to add to another field called 'balance':
I cannot get the date fields to copy
To note this is where I found how to add up the radio buttons ( Here)
This is what I have so far.
This is my form:
Session Date: <input type="text" name="field1" id="f1" />
Session Type payment :
<input type="radio" name="sessiontypepayment" id="sessiontypepayment1" value="100.00" onclick="FnCalculate(this,'extrapeople');"> Mini Session $100.00
<input type="radio" name="sessiontypepayment" id="sessiontypepayment2" value="250.00" onclick="FnCalculate(this,'extrapeople');"> Full Session $250.00
Extra people :
<input type="radio" name="extrapeople" id="extrapeople1" value="25.00" onclick="FnCalculate(this,'sessiontypepayment');"> 1 person $25.00
<input type="radio" name="extrapeople" id="extrapeople2" value="50.00" onclick="FnCalculate(this,'sessiontypepayment');"> 2 people $50.00
<input type="radio" name="extrapeople" id="extrapeople3" value="75.00" onclick="FnCalculate(this,'sessiontypepayment');"> 3 people $75.00
<input type="radio" name="extrapeople" id="extrapeople4" value="100.00" onclick="FnCalculate(this,'sessiontypepayment');"> 4 people $100.00
Total Amount: <div id="total"></div>
Deposit Amount:
Balance Amount:
balance due BY: <input type="text" name="field2" id="f2" />
This is my script what I have so far.
<script type="text/javascript">
$(document).ready(function(){
$("#f1").keyup(function(){
var f2Text = $('#f2').val() + $(this).val();
$('#f2').val(f2Text );
});
});
</script>
<script>
function FnCalculate(id,name)
{
var total=0;
if(document.getElementById(name+"1").checked == true)
{
total = parseInt(document.getElementById(name+"1").value);
}
if(document.getElementById(name+"2").checked == true)
{
total = parseInt(document.getElementById(name+"1").value);
}
total = total + parseInt(id.value);
document.getElementById("total").innerHTML = total;
}
</script>
I would really love help on this please.
First, get rid of all the onclick="FnCalculate(this,'xx');" bits on your inputs.
Then replace your <script>s with this:
<script type="text/javascript">
$(document).ready(function() {
$("#f1").keyup(function() {
$('#f2').val($(this).val());
});
var inputs = $('input[name="sessiontypepayment"], input[name="extrapeople"]');
$(inputs).click(function() {
var total = 0;
$(inputs).filter(':checked').each(function() {
total = total + parseInt($(this).val());
})
$('#total').html('$' + total);
$('#deposit').html('$' + (total / 2));
});
});
</script>
Unsure what you mean by "how can I move up next to the word Total" but I suspect changing <div id="total"></div> to <span id="total"></span> will solve your problem. Either that, or apply some css to the div:
#total {
display: inline;
}
I added the calculation for the deposit, you'll need to add <div id="deposit"></div> to your page somewhere...
You will need jquery. Add this in between <head>...</head>:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
First, you should have your defaults set to checked='checked' for HTML radio buttons that you want checked initially. I would put default text into <div id='total'>$125.00</div>, as well. You might as well use jQuery for what it's made for and not put Events into your HTML at all. .val() returns a String. To cast a String to an integer put + in front of it. To cast to a floating point Number use parseFloat().
$(function(){
$('#f1,[name=sessiontypepayment],[name=extrapeople]').change(function(){
$('#total').text('$'+(parseFloat($('[name=sessiontypepayment]:checked').val())+parseFloat($('[name=extrapeople]:checked').val())).toFixed(2));
$('#f2').val($('#f1').val());
});
});
To divide by 2 it's /2
As a newbie you should get into the practice of using external <script src so it will get cached into your Browser Memory, for faster load time when your Client revisits your site.

Unable to Limit the user input in JavaScript [duplicate]

This question already has answers here:
How to impose maxlength on textArea in HTML using JavaScript
(16 answers)
Closed 8 years ago.
I tried limiting the user input but it wasn't successful, please guide me where I am making mistake.
JS
<script type="text/javascript">
function countLength() {
var maxLength=10;
var length = document.getElementById("txt").value.length;
if(length>10) {
return false;
}
}
</script>
HTML code
<form name="formA" id="formA" action="#" >
<textarea id="txt" name="txt" onkeyup="countLength()"></textarea>
</form>
Your code basically replicates the maxlength attribute, which seems to work (and I don't think is being deprecated?). Just use that.
<input type='text' name='mytext' maxlength='10'>
return false on onkeyup does nothing (as you've probably noticed). I've seen solutions where someone would just alter the value of the textarea, perform a substring operation, and assign that new value back.
Try this:
function countLength() {
var maxLength=10;
var ta = document.getElementById("txt");
var length = ta.value.length;
if(length>maxLength) {
ta.value = ta.value.substr(0, maxLength);
return false;
}
}

BMI Calculator... except BMI won't show up [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
Good evening, everyone :>
I am currently trying to finalize code for a simple BMI calculator. The trouble is that it won't show me a BMI reading when I input my height and weight in my browser. I'm 99% certain that my HTML is solid, it's just the Javascript that seems to be causing problems. Any input I can get on this matter would be appreciated. Thanks!
<!DOCTYPE HTML>
<html>
<head>
<title>BMI Calculator</title>
<script type="text/javascript">
/* <![CDATA[ */
function calculate() {
var height = document.getElementById("height");
var weight = document.getElementById("weight") * 703;
var denom = Math.pow(height, 2);
var totalbmi = weight/denom;
var bmi = document.getElementById("bmi");
if (isFinite(bmi)) {
bmi.innerHTML = totalbmi.toFixed(2);
}
}
/* ]]> */
</script>
<style type="text/css">
<!--
.result {font-weight: bold; }
-->
</style>
</head>
<body>
<form name="details">
<table>
<tr>
<td>Height<br />
(in Inches)</td>
<td><input type="text" size="3" id="height" onChange="calculate();"/></td>
</tr>
<tr>
<td>Weight<br />
(in Pounds)</td>
<td><input type="text" size="3" id="weight" onChange="calculate();"/></td>
</tr>
<tr>
<td><input type="button" value="My BMI" onClick="calculate();"/></td>
</tr>
</table>
</table>
<table width="270">
<tr>
<td width="104">Your BMI is:</td>
<td width="154"><input type="text" id="totalbmi"></span></td>
</tr>
</table>
</form>
</body>
</html>
It's not going to update anything because you have var bmi = document.getElementById("bmi");
when it should be var bmi = document.getElementById("totalbmi");
document.getElementById() returns the HTML node, not the text inside it. To get the actual weight and height values provided by the user, you should use document.getElementById("height").value.
As nathanjosiah pointed out as well, you're referring to a "bmi" node where you probably meant "totalbmi". You're also confusing your 'bmi' and 'totalbmi' variables.
function calculate() {
var height = document.getElementById("height").value;
var weight = document.getElementById("weight").value * 703;
var denom = Math.pow(height, 2);
var totalbmi = weight/denom;
var bmi = document.getElementById("totalbmi");
if (isFinite(totalbmi)) {
bmi.value = totalbmi.toFixed(2);
}
}
EDIT: As others pointed out, you want to set the .value of an input in order to change its displayed content. <input> elements are empty, so setting one's .innerHTML property doesn't work.
document.getElementById() returns a reference to the (matching) DOM element itself, not to its value. To get/set the value use the .value property.
Also you are trying to set the result to a field with id "bmi" when the actual field has the id "totalbmi", and you are trying to set that field's .innerHTML (which input elements don't have) instead of its .value.
So taking those problems into account:
function calculate() {
var height = document.getElementById("height").value;
var weight = document.getElementById("weight").value * 703;
var denom = Math.pow(height, 2);
var totalbmi = weight/denom;
document.getElementById("totalbmi").value =
isFinite(totalbmi) ? totalbmi.toFixed(2) : "";
}
(Where if the results fail the isFinite test I'm setting the output field to an empty string rather than leaving whatever value was in it before.)
In the following line you id is totalbmi, but you are using document.getElementById("bmi");
<input type="text" id="totalbmi">
Also, to set the value of the input you would do
bmi.value = totalbmi.toFixed(2)
instead of
bmi.innerHTML = totalbmi.toFixed(2)

Categories

Resources