Javascript Radio / Checkbox Problems - javascript

I have this simple script. I'm trying to get the checked values and add them to a running total that's in the diabled input box. I know it's getting checked option but it's not updating to the input box and I'm not sure why. Can anyone help me?
<html>
<head>
<script type="text/javascript">
function updateForm()
{
var type = document.pizzaForm.pizzaType;
var toppings = document.pizzaForm.toppings;
var pizzaType;
var toppings;
for(var i = 0; i <= type.length; i++)
{
if(type[i].checked)
{
total = type[i].value;
}
}
for(var i = 0; i <= toppings.length; i++)
{
if(toppings[i].checked)
{
toppings += toppings[i].value;
}
}
var total = pizzaType + toppings;
pizzaForm.total.value = total;
}
</script>
</head>
<body>
<h1>Order Pizza Here:</h1>
<form action="" method="get" name="pizzaForm">
What Type of Pizza Would You Like? <br />
<input type="radio" name="pizzaType" value="10.00" onchange="updateForm()" />Vegetarian<br />
<input type="radio" name="pizzaType" value="20.00" onchange="updateForm()" />Meat Lovers<br />
<br />
<br />
Extra Toppings: <br />
<input type="checkbox" name="toppings" value="2.00" onchange="updateForm()" />Extra Cheese <br />
<input type="checkbox" name="toppings" value="3.00" onchange="updateForm()" />Mushrooms <br />
<input type="checkbox" name="toppings" value="4.00" onchange="updateForm()" />Anchovies <br />
<br />
Total <input type="text" disabled="disabled" name="total" />
</form>
</body>
</html>

You have a few basic Javascript errors:
your for loops look like:
for(var i = 0; i <= type.length; i++)
this means they will go from 0 to length (including length) = length + 1
It should be:
for(var i = 0; i < type.length; i++)
see the diffference? <= is now <. (off by one error?)
you are using toppings variable twice. (javascript is really bad with this and lets you shoot yourself in the foot.) Also you should be initialisng all values.
var type = document.pizzaForm.pizzaType;
var toppings = document.pizzaForm.toppings;
var pizzaTypeValue = 0;
var toppingsValue = 0;
I've also added Value to the variables that hold numbers rather than elements. Other might prefix this or some such convention to remember it holds a value not a list of elements.
the values in markup are strings use parseFloat( to turn them into floats:
pizzaTypeValue += parseFloat(type[i].value);
also note the += means: add this to me. Equivalent to pizzaTypeValue = pizzaTypeValue + ....
there is no real need for the total variable. just add a comment if you want to remember it is the total.
See this jsFiddle: http://jsfiddle.net/F53ae/ to see it in action.

Here is the working code. I put it in jsfiddle for you. The main problem was that you had two variables named toppings. Also, in the first loop, you were setting the "total" variable, when you meant to set the other total. Check it out.
http://jsfiddle.net/eXPAj/1/

Related

Javascript: Displaying output dependent on which checkedboxes pressed?

I am creating a web app that will take 2 sets of user input, i.e. Age and Weight and display an outcome dependent on what box is ticked on each.
What is the best way to do this?
I.e. if one age and weight is selected I wish to display one value, but if a different combo is selected I wish to display another?
I ask this as I know it can be done using multiple if statements, but I assume there is a better way.
Current Code:
<!DOCTYPE html>
<html>
<body>
<h1>Health Calculator</h1>
<p>Select age</p>
<form action="age.asp" method="get">
<input type="checkbox" name="Age" value="under25"> Under 25<br>
<input type="checkbox" name="Age" value="over25"> Over 25<br>
</form>
<p>Select Weight</p>
<form action="weight.asp" method="get">
<input type="checkbox" name="Probability" value="under80"> Under 80kg<br>
<input type="checkbox" name="Probability" value="over80"> Over 80kg<br>
</form>
<br>
<button onclick= "analyseHealth"> Analyse health </button> <br>
<script>
function analyseHealth(age, weight){
//LOGIC RELATING TO CHECK BOXES
}
</script>
</body>
</html>
This is not finished but I think you can guess the rest.
http://codepen.io/anon/pen/RPpjBm
function analyseHealth()
{
var ages = document.getElementsByName('Age');
var probs = document.getElementsByName('Probability');
var age = undefined;
for(var i = 0; i < ages.length; i++)
{
if(ages[i].checked)
{
age = ages[i].value;
}
}
var probability = undefined;
for(var i = 0; i < probs.length; i++)
{
if(probs[i].checked)
{
probability = probs[i].value;
}
}
switch(age){
case 'under80': break;
}
}
Better than if might be switch. First you get the checked radio buttons which might be the better choice here.

How do I get the value of checkboxes in jquery having common names.?

I have the following series of checkboxes coming from the datatables in the form like below:
<input id="list-chk_1" type="checkbox" />
<input id="list-chk_2" type="checkbox" />
<input id="list-chk_3" type="checkbox" />
How can I separate that id from list-chk. Do I have to include data-id parameter?
As per my understanding, Try that
$('input[id^="list-chk"]').click(function(){
$(this).attr("id"); //Getting click control ID
$(this).val(); //Getting Value
});
You can use split if you know the ID always has that format.
var ins = document.getElementsByTagName('input');
for (var i = 0; i < ins.length; i++) {
document.write(ins[i].id.split('_')[1]);
}
// jQuery
$('input').each(function() {
$('body').append(this.id.split('_')[1]);
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="list-chk_1" type="checkbox" />
<input id="list-chk_2" type="checkbox" />
<input id="list-chk_3" type="checkbox" />
Split will make an array from the given string, splitting it where you tell it to.
"list-chk_1".split('_') // results in ["list-chk", "1"]
Other methods could be using var idnr = this.id.replace('list-chk_', '');

How to dynamically add text fields to a form based on a number the user puts in

I'm attempting to make a form that asks the user for a number of units, then asks whether or not they would like those units to be provisioned, and depending on the answer, generates text fields corresponding with the number of units the typed in, along with a text field asking for an account number.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script>
<script type="text/javascript">
function Getunits(value) {
var units = document.getElementById('units');
for(count=0; count<=units; count++) {
$("<input type='text'>").appendTo("inpane");
}
document.getElementByTag('futureacc').InnerHTML='What is your account number? <input type="text" value="accountnum">';
}
</script>
</head>
<body>
<div id="container">
<form method="post" action="sendcontact.php">
<div id="unitammount" class="inpane">
Number of units ordered: <input type="text" name="units" id="units"/><br />
</div>
<div id="futureacc" class="inpane">
Are these units to be provisioned? <input type="radio" name="select" value="yes" onClick="Getunits('units.value')"/> Yes <input type="radio" name="select" value="no"/> No
</div>
Obviously I would like the new text fields to appear inside the futureacc div and inpane div respectively.
I don't know whether it's the loop that doesn't do anything or that I'm not appending correctly but as I currently have it this does nothing...
Any help would be greatly appreciated.
You had a number of errors with your code. It was confusing because you were mixing jQuery and pure Javascript. It's generally better to just use jQuery if you've decided to use it anyway. Your loop should have been iterating while it was smaller than units.val(), not while it was smaller than or equal to units. innerHTML is spelled with a lowercase "i," and your appendTo selector needed a period before the class name. I went ahead and cleaned up your code so it should work now!
HTML:
<div id="container">
<form method="post" action="sendcontact.php">
<div id="unitammount" class="inpane">
Number of units ordered: <input type="text" name="units" id="units"/>
</div><br>
<div id="futureacc" class="inpane">
Are these units to be provisioned? <input type="radio" name="select" value="yes" onClick="getUnits()"/> Yes <input type="radio" name="select" value="no"/> No <br>
</div>
</form>
</div>​
Javascript:
function getUnits() {
var units = $("#units").val();
for (var count = 0; count < units; count++) {
$("<input type='text' /><br>").appendTo("#futureacc");
}
$("#futureacc").append('<br>What is your account number? <input type="text" placeholder="accountnum">');
}​
WORKING DEMO
var units = document.getElementById('units');
needs to be
var units = document.getElementById('units').value;
you are passing value to onclick but it is a string will not give you exact value anyway you are not using it in you function so it doesnt have any side effect.
also you need to some error check to make sure that user has entered a number
with
for(count=0; count<=units; count++)
You are adding 1 more text box than user entered value. so if user has entered 4 you are creating 5 <= should be changed to <
This is wrong
onClick="Getunits('units.value')"
Instead use this:
onClick="Getunits(units.value)"
try this
$(document).ready(function(){
$('input[name=select]').click(function(){
if($(this).val() ==='yes'){
var numberOfTextboxes = $('#units').val();
for(var i =0; i<numberOfTextboxes; i++){
$('#unitammount').append('<input type="text" />');
}
}
});
});
See the fiddle

Find and compare elements with matching attribute values in Jquery

How do I go on about selecting elements which has the same attribute values in jquery. And then comparing which of those 2 has a greater value.
Here is what I have so far. The problem that I'm having with this is that I don't really get any output if the first number in the pair is the larger one.
<script>
$(function(){
var j = [];
$('.loo').each(function(index){
var grp = $(this).attr('data-x');
var num = $(this).val();
var id = $(this).attr('id');
var pair_val = pair_value(grp);
var pair_id = pair_identity(id);
console.log(get_max(num, pair_val, id, pair_id));
});
function get_max(num1, num2, id1, id2){
var decide = 0;
if(num1 > num2){
decide = id1;
}else{
decide = id2;
}
return decide;
}
function pair_value(conn){
var pair = $("input[data-x="+ conn +"]").val(); //my problem is here
return pair;
}
function pair_identity(conn){
var pair_id = $("input[data-x="+ conn +"]").attr('id'); //my problem is here
return pair_id;
}
});
</script>
Html:
<p>
<input type="text" id="e" name="e" class="loo" value="1" data-x="a">
</p>
<p>
<input type="text" id="f" name="f" class="loo" value="10" data-x="a">
</p>
<p>
<input type="text" id="g" name="g" class="loo" value="37" data-x="b">
</p>
<p>
<input type="text" id="h" name="h" class="loo" value="25" data-x="b">
</p>
<p>
<input type="text" id="i" name="i" class="loo" value="11" data-x="c">
</p>
<p>
<input type="text" id="j" name="j" class="loo" value="12" data-x="c">
</p>
var highest = new Array();
$('.loo').each(function(){
if(!highest[$(this).data('x')] || parseInt($(this).val()) > highest[$(this).data('x')] )
highest[$(this).data('x')] = parseInt($(this).val());
});
This will loop through all instances of .loo and checks if there is no entry yet or if the current saved value is lower than the current elements value, in that case it will update the array entry.
This will leave you with an array containing all max values for all possible values of data-x
EDIT
excuse me, some syntax errors were present.
EDIT 2
shorter version
http://jsfiddle.net/kkbkb/1/
The problem you're no doubt having is that you are comparing character strings (obtained with .val()), not numbers. This has a very different behviour - effectively deciding which one is alphabetically before another.
Change this line:
if(num1 > num2){
to
if(parseInt(num1,10) > parseInt(num2,10)){

How can I read the value of a radio button in JavaScript?

<html>
<head>
<title>Tip Calculator</title>
<script type="text/javascript"><!--
function calculateBill(){
var check = document.getElementById("check").value;
/* I try to get the value selected */
var tipPercent = document.getElementById("tipPercent").value;
/* But it always returns the value 15 */
var tip = check * (tipPercent / 100)
var bill = 1 * check + tip;
document.getElementById('bill').innerHTML = bill;
}
--></script>
</head>
<body>
<h1 style="text-align:center">Tip Calculator</h1>
<form id="f1" name="f1">
Average Service: 15%
<input type="radio" id="tipPercent" name="tipPercent" value="15" />
<br />
Excellent Service: 20%
<input type="radio" id="tipPercent" name="tipPercent" value="20" />
<br /><br />
<label>Check Amount</label>
<input type="text" id="check" size="10" />
<input type="button" onclick="calculateBill()" value="Calculate" />
</form>
<br />
Total Bill: <p id="bill"></p>
</body>
</html>
I try to get the value selected with document.getElementById("tipPercent").value, but it always returns the value 15.
In HTML, Ids are unique. Try changing the id attributes to tipPercent1, tipPercent2, etc.
Both radio buttons have the same ID - this is incorrect in HTML, as IDs should be unique. The consequence is that document.getElementById cannot be used.
Try document.getElementsByName and loop through the resulting array to find out which one is checked and what its value is.
<input type="radio" id="tipPercent" name="tipPercent" value="15" />
<input type="radio" id="tipPercent" name="tipPercent" value="20" />
First of all, id's are required to be unique identifiers, so giving two elements the same id will make problems. document.getElementById("tipPercent") after all tries to get one element, so which of those two different input elements should it return?
Second, you can only check if a radio input is checked or not, so you will need to loop through all those inpud fields and check which one is checked to get the current value.
You have two equal ids "tipPercent". getElementById returns only one first result
You should use different ids for each radio. Try something like follows:
<script type="text/javascript">
//a variable that will hold the index number of the selected radio button
for (i=0;i<document.f1.tipPercent.length;i++){
if (document.document.f1.tipPercent[i].checked==true)
var tipPercent= document.f1.tipPercent[i].value;
}
</script>
You may want to change the calculateBill() function with the following:
function calculateBill() {
var tipPercent = 0;
var check = document.getElementById("check").value;
var radioElements = document.getElementsByName("tipPercent");
for (var i = 0; i < radioElements.length; i++) {
if (radioElements[i].checked)
tipPercent = parseInt(radioElements[i].value);
}
var tip = check * (tipPercent / 100)
var bill = 1 * check + tip;
document.getElementById('bill').innerHTML = bill;
}
Note the use of document.getElementsByName(), as Oded suggested in another answer.
You should also remove the id attribute from your radio buttions:
<input type="radio" name="tipPercent" value="15" />
<input type="radio" name="tipPercent" value="20" />
The following is a screenshot showing that the above function works fine with the 20% radio button:
How can I read the value of a radio button in JavaScript? http://img695.imageshack.us/img695/6214/tipcalc.png
The id of an element has to be unique, so you can't have two elements with the same id.
When you try to get all radio buttons as a single element, you will get one of them. Which one you get is entirely up to how the browser choose to handle the incorrect id's that you have set. You could get either of the elements, or null, depending on the implementation. In this case you happen to use a browser that gets the first element.
Give the elements their own id:
Average Sevice: 15%<input type="radio" id="tipPercent15" name="tipPercent" value="15" />
<br />
Excellent Sevice: 20%<input type="radio" id="tipPercent20" name="tipPercent" value="20" />
Getting the value attribute from the element will only get the value that you have specified for each of them. Instead you used the checked attribute:
var tipPercent;
if (document.getElementById("tipPercent15").checked) tipPercent = 15;
if (document.getElementById("tipPercent20").checked) tipPercent = 20;

Categories