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)){
Related
I have 2 <p> tags and an input field, wrapped in a while loop
<p id="price"></p>
<input id="quantity" oninput="calculate(<?php echo $cprice; ?>)" type="text" name="quantity">
<p id="total"></p>
I want to use JavaScript to perform arithmetic.
I want to multiply price and quantity and display the result in total. Without the while loop, it works but with the while loop, it only updates the first field.
function calculate(price) {
var quantity = document.getElementById('quantity').value;
var result = document.getElementById('total');
var myResult = price * quantity;
document.getElementById('total').innerHTML = myResult;
}
I don't know how to dynamically update the total tag with js
You need to change your IDs to class since IDs must be unique.
See example which is assuming price is alway there
I choose to not use nextElement since you can easily add other stuff to the html without it
I also made the code unobtrusive instead of having inline handlers
document.querySelectorAll(".quantity").forEach(function() {
this.oninput = function() {
var q = document.querySelectorAll(".quantity"),
p = document.querySelectorAll(".price"),
total = 0;
q.forEach(function(qt, index) {
var price = +p[index].innerText,
quantity = +qt.value;
if (!isNaN(quantity)) total += price * quantity;
})
document.getElementById('total').innerHTML = total;
}
})
<p class="price">1</p>
<input class="quantity" type="text" name="quantity">
<p class="price">2</p>
<input class="quantity" type="text" name="quantity">
<p class="price">3</p>
<input class="quantity" type="text" name="quantity"><br/>
Total:<p id="total"></p>
IDs need to be unique. If there are duplicates, document.getElementById will return the first one.
Instead of using IDs, use DOM navigation methods. You can pass in this to get a reference to the input element, then find the output element after it.
function calculate(price, input) {
var quantity = input.value;
var result = input.nextElementSibling;
var myResult = price * quantity;
result.innerHTML = myResult;
}
<p class="price">Price = 30</p>
<input class="quantity" oninput="calculate(30, this)" type="text" name="quantity">
<p class="total"></p>
<p class="price">Price = 45</p>
<input class="quantity" oninput="calculate(45, this)" type="text" name="quantity">
<p class="total"></p>
I tried to create an online calculation form using javascript, everything is ok except radio buttons.
Scenario:
x(select list) =
item1 - value="11.2"
item2 - value="7.6"
item3 - value="7"
y=(input number)
z=(input number)
coverkind=(radio button)
if 1 selected >> coverkind = z*800
if 2 selected >> coverkind = ((y/16)+1)*8*z
totalprice= (x*y*z)+(1000*z)+coverkind
my work till now:
<html>
<head>
<script type="text/javascript">
function getselectionPrice() {
var elt = document.getElementById("selectionone");
var selectionPrice = elt.options[elt.selectedIndex].value;
var y = document.getElementById("y").value;
var z = document.getElementById("z").value;
var ser = (selectionPrice * y * z);
var dz = z*1000;
var coverkind = document.getElementById("cover").value;
if (coverkind == 'soft') {
var SizePrice = (z * 800);
} else {
var SizePrice = ((y / 16) + 1) * 8 * z;
}
var finalPrice = ser + dz;
document.getElementById("totalPrice").value = finalPrice;
}
</script>
</head>
<body>
<div>
<form action="" id="calcform" onsubmit="return false;">
<div>
<div>
<fieldset>
<label>select</label>
<select id="selectionone" name='selectionone' onChange="getselectionPrice()">
<option value="11.2">1</option>
<option value="7.6">2</option>
<option value="7">3</option>
</select>
<br/>
<p>y
<input type="text" id="y" onchange="getselectionPrice()" />
</p>
<p>z
<input type="text" id="z" onchange="getselectionPrice()" />
</p>
<label>cover</label>
<input type="radio" name="cover" value="hard" />hard
<br />
<br>
<input type="radio" name="cover" value="soft" />soft
<br>
<br>
<br/>The new calculated price:
<INPUT type="text" id="totalPrice" Size=8>
</fieldset>
</div>
<input type='submit' id='submit' value='Submit' onclick="getselectionPrice()" />
</div>
</form>
</div>
</body>
</html>
If I remove the coverkind from js, the rest works fine. I googled about getting value from radio button and nothing found very relevant to this situation.
firebug error panel :
TypeError: document.getElementById(...) is null
var coverkind = document.getElementById("cover").value;
If you can use jQuery, you can get the value of the checked radio button in one line.
var Val = $("input[name=cover]:checked").val();
Here is the solution of your problem.
First give a same id to your radio buttons.
The checked property will tell you whether the element is selected:
<input type="radio" id="cover" name="cover" value="hard" checked="checked" />hard
<br />
<br>
<input type="radio" id="cover" name="cover" value="soft" />soft
and in JavaScript function, you can get it.
var coverkind = null;
if (document.getElementById('cover').checked)
{
coverkind = document.getElementById('cover').value;
}
if (coverkind == 'soft') {
var SizePrice = (z * 800);
} else {
var SizePrice = ((y / 16) + 1) * 8 * z;
}
You can use the output tag if you want or something else for your output. (a <p> element for example). Just make sure you give anything you want to access in your Javascipt an 'id' value.
You'll need to create a new file and call it something like 'script.js'. Google how to include this script in your html document.
Some of the things you'll need to use in your script:
document.getElementById(str) Returns an object representing an html
element with an id of 'str'
parseFloat(str) Takes a string 'str' and return the float value
.value This is a read/write property of an input text box object
that contains the text value
.checked ..and a property of an input radio button object.
When you hit a wall refer to the great google ;) Put all that together and you should be on the right track.
I'm adding new inputs dynamically. And I would also like to read values dynamically from them. My championName variable doesn't work in JS.
<form name="second_form" id="second_form" action="#" method="POST" style="margin: 0;" >
<div id="p_scents">
<p>
<label for="p_scnts">
<input type="text" id="p_scnt" size="20" list="champions" name="champion[]" value="" placeholder="Enter Champion's name">
<datalist id="champions"></datalist>
Add General Change<a></a>
Add Spell<a></a>
</label>
</p>
</div>
<br/><input type="submit" value="submit">
</form>
function val(doublechamp) {
var championsWithExtraSpells = ["Aatrox", "Elise", "Fizz", "Heimerdinger", "Jayce", "Lee Sin", "Nidalee", "Rek'Sai","Twisted Fate"];
var champion = this["champion[]"];
var championName = document.getElementsByName("Champion[]").value;
if($.inArray(championName, championsWithExtraSpells)==-1){
var existsInArray = false;}
else{
var existsInArray = true;}
d = document.getElementById("change[]").value;
var spellname = document.getElementById("ttt");
spellname.value=champions[""+championName+""][change(d, existsInArray)];
}
Collection returned by getElementsByName() in the line, so just replace it.
UPDATED
JS :
Replace :
var championName = document.getElementsByName("Champion[]").value;
By :
for(var i=0;i<document.getElementsByName("champion[]").length;i++)
var championName = document.getElementsByName("champion[]")[0].value;
Now you can get all the inputs values.
There are couple of changes you need to make:
- You're not invoking the function anywhere in the code you're showing
you'll need to add an onChange clause to the input or an onsubmit to the form to check the values..
the name of an element can't contain [] - so you should remove those from the name;
<input type="text" id="p_scnt" size="20" list="champions" name="champion" value="" placeholder="Enter Champion's name">
getElementsByName returns nodelist, not a single node (even if there's only one match). If you make the following changes you'll get farther:
And in the script change these two lines:
var championName = document.getElementsByName("champion");
if($.inArray(championName[0].value, championsWithExtraSpells)==-1){
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/
<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;