I have two javascript text boxes.
<input type="text" name="test" value="300" />
<input type="text" name="test" value="500" />
How can I use javascript to alert the total price of the items in the text box?
Would something like this work?
var price = document.getElementById("test");
alert(price)
This will take all input elements into account (useful if you have many). Filter them by type and get their values in loop:
var inputs = document.getElementsByTagName("input");
var total = 0;
for (var i = 0; i < inputs.length; i++){
if (inputs[i].type = "text"){
total += parseInt(inputs[i].value, 10);
}
}
alert(total);
<input id="test1" type="text" name="test" value="300" />
<input id="test2" type="text" name="test" value="500" />
JS:
var price = parseInt(document.getElementById("test1").value, 10) + parseInt(document.getElementById("test2").value, 10);
<input id="price1" type="text" name="test" value="300" />
<input id="price2" type="text" name="test" value="500" />
This will work:
var price = document.getElementById("price1").value+document.getElementById("price2").value;
alert(price)
Note Do not have other tags with id="price1" or id="price2"
What you have written will not work, for several reasons. Firstly, as the name suggests, getElementById gets an element based on the value of the id attribute. You haven't given your input elements an id attribute, so that's not going to work.
Secondly, document.getElementById('someId') returns an element, but you want the value. You can use the value property to get it:
var price1 = parseInt(document.getElementById("test1").value, 10);
var price2 = parseInt(document.getElementById("test2").value, 10);
alert(price1 + price2);
This will work with the following HTML:
<input type="text" name="test" id="test1" value="300" />
<input type="text" name="test" id="test2" value="500" />
Note the use of parseInt. The value property returns a String, so we use parseInt to attempt to parse that into a Number. If you don't use it, price1 + price2 will simply concatenate the strings.
Related
I am trying to make a multiplication function in jquery where which helps change the default value-based output.
For example - if I type the input#mainInput value then it will change all the inputs value base own his default value * input#mainInput and if the value == 'NaN' it will do dirent funcion.
Please help me how to I make this function in jQuery.
$(document).on('keyup', 'input#mainInput', function() {
thisParentQtyValueBox = $(this).val();
daughtersBoxValueAttr = $("input.input__bom").attr("inputid");
daughtersBoxValue = $("input#daughterInput_" + daughtersBoxValueAttr).val();
$("input#daughterInput_" + daughtersBoxValueAttr).val(thisParentQtyValueBox * daughtersBoxValue);
if ($("input#daughterInput_" + daughtersBoxValueAttr) == 'Nan') {
$("input#daughterInput_" + daughtersBoxValueAttr).val('3' * daughtersBoxValue)
}
});
//If
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="mainInput" type="text" placeholder="Number" />
<br><br>
<input class="input__bom" id="daughterInput_1" type="text" placeholder="value" inputid="1" value="5" /><br/>
<input class="input__bom" id="daughterInput_2" type="text" placeholder="value" inputid="2" value="10" /><br/>
<input class="input__bom" id="daughterInput_3" type="text" placeholder="value" inputid="3" value="15" /><br/>
<input class="input__bom" id="daughterInput_4" type="text" placeholder="value" inputid="4" value="20" /><br/>
<input class="input__bom" id="daughterInput_5" type="text" placeholder="value" inputid="5" value="25" /><br/>
If I understand correctly, when the input is not a number, you want to do as if the input was 3.
Some issues in your code:
$("input.input__bom").attr("inputid") is always going to evaluate to 1, as only the first matching element is used. And it is strange to use this attribute value to then retrieve that element again via its id property.
You would need a loop somewhere so to visit each of the "input__bom" elements.
== 'Nan is never going to be true. You should in fact test the main input itself to see if it represents a valid number. For that you can use isNaN.
It is a bad idea to give these elements a unique id attribute. You can use jQuery to visit them each and deal with them. There is no need for such id attribute.
Don't use the keyup event for this, as input can be given in other ways than pressing keys (e.g. dragging text with mouse, or using the context menu to paste). Use the input event instead.
There is no good reason to use event delegation here on $(document). Just bind your listener directly the main input element.
Declare your variables with var (or let, const). It is bad practice to no do that (it makes your variables global).
It seems like the 5 "bom" input elements are not really intended for input, but for output. In that case the placeholder attribute makes no sense, and they should better be marked with the readonly attribute.
$("#mainInput").on('input', function() {
var mainInput = $(this).val();
var multiplier = +mainInput; // convert to number with unary +
// default value in case input is not a valid number, or is empty
if (Number.isNaN(multiplier) || !mainInput) {
multiplier = 3;
}
$('.input__bom').each(function() {
$(this).val( multiplier * $(this).data('value') );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="mainInput" type="text" placeholder="Number" />
<br><br>
<input class="input__bom" type="text" readonly data-value="5" value="5"><br/>
<input class="input__bom" type="text" readonly data-value="10" value="10"><br/>
<input class="input__bom" type="text" readonly data-value="15" value="15"><br/>
<input class="input__bom" type="text" readonly data-value="20" value="20"><br/>
<input class="input__bom" type="text" readonly data-value="25" value="25" /><br/>
You have to store the default value in the data attr so then it will not multiple by result value and it will multiple by your default value. for dynamic multiplication, you can use jquery each. check below code.
$(document).on('input', 'input#mainInput', function() {
thisParentQtyValueBox = parseInt( $(this).val() );
if( Number.isNaN( thisParentQtyValueBox ) ){
thisParentQtyValueBox = 3;
}
$('.input__bom').each(function(){
$(this).val( thisParentQtyValueBox * $(this).data('value') );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="mainInput" type="text" placeholder="Number" />
<br><br>
<input class="input__bom" id="daughterInput_1" type="text" placeholder="value" inputid="1" data-value ="5" value="5" /><br/>
<input class="input__bom" id="daughterInput_2" type="text" placeholder="value" inputid="2" data-value ="10" value="10" /><br/>
<input class="input__bom" id="daughterInput_3" type="text" placeholder="value" inputid="3" data-value ="15" value="15" /><br/>
<input class="input__bom" id="daughterInput_4" type="text" placeholder="value" inputid="4" data-value ="20" value="20" /><br/>
<input class="input__bom" id="daughterInput_5" type="text" placeholder="value" inputid="5" data-value ="25" value="25" /><br/>
I have a computation fare using the getElementById.innerHTML the total fare showing using <h5 id="totalFare"></h5> but instead if getElementByID i want to parse in getElementsByName by using a <input type="number" name="totalFare" readonly /> i'm searching a lot page to find out the answer, below is my codes. i hope you can help me.
<input type="number" id="adults" min="0" onkeyup="calculate()" name="booking[adults]" class="validate" value="0" required>
<input type="number" id="children" min="0" onkeyup="calculate()" name="booking[children]" class="validate" value="0" required>
<input type="number" id="senior" min="0" onkeyup="calculate()" name="booking[senior]" class="validate" value="0" required>
<script type="text/javascript">
function calculate(){
var adults = document.getElementById("adults").value;
var children = document.getElementById("children").value;
var senior = document.getElementById("senior").value;
var Fare = document.getElementById("hideFare").value;
var values = fare(adults, children, senior, Fare);
console.log(values)
document.getElementById("totalFare").innerHTML = values.totalFare;
}
function fare(x, y, z, a) {
var res = {};
res.totalFare = (( x * a) + (y * (a *.80)) + (z * (a *.80)))
return res
}
</script>
Use getElementsByName like below.
console.log(document.getElementsByName("test")[0].value);
<input type="text" name="test" id="testing" value="This is a value" />
The document.getElementsByName("test") gives you something like an array (called a collection of elements since there could be multiple elements with the same name), so the [0] is there to get the first index which is the value you wanted. Look at the link below for more information.
https://www.w3schools.com/jsref/met_doc_getelementsbyname.asp
I just want to get all different values using javascript with the same id.
Here is my input code:
<input type="text" id="full" name="full" value="2018-12-06">
<input type="text" id="full" name="full" value="2018-12-14">
<input type="text" id="full" name="full" value="2018-12-18">
When I alert the id of the inputs it show's the 2018-12-06 only. I want to disable the jquery datepicker but the 2018-12-06 is the only one read.
Here is my calendar.
and my javascript code:
var x = (document.getElementById('full').value);
var array = ["2018-12-25", "2019-01-01", x]
I want to disable all value with same id like the mention above,
IDs must be unique. You should add a class to each element and then use getElementsByClassName.
Because the method returns a nodelist to get each input value you need to iterate over it. For both these examples I've used map, but you might find a for/loop or forEach easier to use.
const full = document.getElementsByClassName('full');
const arr = [...full].map(input => input.value);
console.log(arr);
<input type="text" class="full" value="2018-12-06">
<input type="text" class="full" value="2018-12-14">
<input type="text" class="full" value="2018-12-18">
An alternative might be to use querySelectorAll. This uses CSS selectors so you can pinpoint elements by their attributes instead:
const full = document.querySelectorAll('[name="full"]');
const arr = [...full].map(input => input.value);
console.log(arr);
<input type="text" name="full" value="2018-12-06">
<input type="text" name="full" value="2018-12-14">
<input type="text" name="full" value="2018-12-18">
ID is used as an individual identifier. So it is illegal to use same Id for multiple elements. To get values of multiple elements use class instead of id.
You can use getElementsByClassName() function to read values of all elements with same class name
Alternative to getElementsByClassName() using jQuery
var l = $('.full').length;
//Initialize default array
var result = [];
for (i = 0; i < l; i++) {
//Push each element to the array
result.push($('.full').eq(i).val());
}
//print the array or use it for your further logic
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="full" value="2018-12-06">
<input type="text" class="full" value="2018-12-14">
<input type="text" class="full" value="2018-12-18">
You can't create an element with the same Id, If you want to get all different values from another element using javascript you can use ClassName
<input type="text" class="full" name="full" value="2018-12-06">
<input type="text" class="full" name="full" value="2018-12-14">
<input type="text" class="full" name="full" value="2018-12-18">
var x = document.getElementsByClassName('full');
Using Jquery I need to add all values of input.
Using jquery each is there any way to use regix in element name
like
items[regix_goes_here][debit]
I need values of all input and I want them incremented using each.
My code
<input name="items[1][debit]" type="number">
<input name="items[341][debit]" type="number">
<input name="items[31][debit]" type="number">
<input name="items[431][debit]" type="number">
First, assign a class to your inputs, for example:
<input class="js-inc" name="items[1][debit]" type="number">
<input class="js-inc" name="items[341][debit]" type="number">
<input class="js-inc" name="items[31][debit]" type="number">
<input class="js-inc" name="items[431][debit]" type="number">
Now you can increment all of them, without even jquery. Use .value to access the value as a string. Use Number("..") to convert it to a number. Add one to it, and assign it back.
var inputs = document.querySelectorAll("input.js-inc")
inputs.forEach(function(input) {
input.value = Number(input.value) + 1
})
Here's a live example
If you want to sum all the values of inputs with name="items[X][Y]", you can filter them by testing if their name attribute matches this /items\[\d+\]\[debit\]/ Regex.
This is how should be your code:
var sum = 0;
$('input[type="button"]').click(function() {
$('input').each(function() {
if ($(this).attr('name') && $(this).attr('name').match(/items\[\d+\]\[debit\]/)) {
sum += $(this).val() ? parseInt($(this).val()) : 0;
}
});
console.log(sum);
});
Demo:
var sum = 0;
$('input[type="button"]').click(function() {
$('input').each(function() {
if ($(this).attr('name') && $(this).attr('name').match(/items\[\d+\]\[debit\]/)) {
sum += $(this).val() ? parseInt($(this).val()) : 0;
}
});
console.log(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="items[1][debit]" type="number" value="2">
<input name="items[341][debit]" type="number" value="2">
<input name="items[31][debit]" type="number" value="2">
<input name="items[431][debit]" type="number" value="2">
<input type="button" value="SUM" />
Hi i want to calculate two input field values and result will show in third input field so i want to write code in ajax page
<input id="a1" type="text" />
<input id="a2" type="text" onblur="Calculate();" />
<input id="a3" type="text" name="total_amt" value="" />
here javascript function
<script>
function Calculate()
{
var resources = document.getElementById('a1').value;
var minutes = document.getElementById('a2').value;
document.getElementById('a3').value=parseInt(resources) * parseInt(minutes);
document.form1.submit();
}
</script>
starting its working but nw its not working please help me
Thanks in Advance
Look this! Work it.
http://jsfiddle.net/op1u4ht7/2/
<input id="a1" type="text" />
<input id="a2" type="text" onblur="calculate()" />
<input id="a3" type="text" name="total_amt" />
calculate = function()
{
var resources = document.getElementById('a1').value;
var minutes = document.getElementById('a2').value;
document.getElementById('a3').value = parseInt(resources)*parseInt(minutes);
}
Try AutoCalculator https://github.com/JavscriptLab/autocalculate Calculate Inputs value and Output By using selector expressions
Just add an attribute for your output input like data-ac="(#firstinput+#secondinput)"
No Need of any initialization just add data-ac attribute only. It will find out dynamically added elements automatically
FOr add 'Rs' with Output just add inside curly bracket data-ac="{Rs}(#firstinput+#secondinput)"
My code is from an answer above. Special thank for you!
calculate = function (a, p, t) {
var amount = document.getElementById(a).value;
var price = document.getElementById(p).value;
document.getElementById(t).value = parseInt(amount)*parseInt(price);}
<input type="number" id="a0" onblur="calculate('a0', 'p0', 't0')">
<input type="number" id="p0" onblur="calculate('a0', 'p0', 't0')">
<input type="number" id="t0" >
<hr>
<input type="number" id="a1" onblur="calculate('a1', 'p1', 't1')">
<input type="number" id="p1" onblur="calculate('a1', 'p1', 't1')">
<input type="number" id="t1" >
put in you form id="form1"
the JavaScript is look like this.
calculate = function()
{
var resources = document.getElementById('a1').value;
var minutes = document.getElementById('a2').value;
document.getElementById('a3').value = parseInt(resources)*parseInt(minutes);
document.form1.submit();
}