Using JS variable as the property of HTML input Form - javascript

I have a form which have two field "optin" and "Qty".The quantity field of the form accept the number.The minimum number which can be entered in this field(QTY) depends upon the the value of the Option field i.e. If the option fiels value is red then the minimum value propert of the Qty field should be 5 and if it is 'Red' then the minimum property of the Qty field should be 10. I am doing it by the given code but its not working.
<td><input type="text" name="option" onkeydown="random()" class="form-control" >
<script>
function random()
{
var a=document.getElementById('option').value;
if(a==="red")
{
var minimum = '5';
}
else if(a==="green")
{
var minimum= '10';
}
}
</script>
<input type="NUMBER" name="qty" class="form-control" min=<?php var minimum ?> ></td>

<!-- This is the code you provided -->
<td><input type="text" name="option" onkeydown="random()" class="form-control" >
<script>
function random()
{
var a=document.getElementById('option').value;
if(a==="red")
{
var minimum = '5';
}
else if(a==="green")
{
var minimum= '10';
}
}
</script>
<input type="NUMBER" name="qty" class="form-control" min=<?php var minimum ?> ></td>
Let's see...
First of all lets change your if else case with a switch:
switch(a){
case "red":
var minimum = 5;
break;
case "green":
var minimum = 10;
break;
}
Now I will remove the php tag and add a line to change the min value of the input.
<td><input type="text" id="option" onkeydown="random()" class="form-control" />
<script>
function random()
{
var a=document.getElementById('option').value;
switch(a){
case "red":
var minimum = 5;
break;
case "green":
var minimum = 10;
break;
}
document.getElementById("input").setAttribute("min", minimum)//this line adds an attribute or sets it to a given value
}
</script>
<input type="NUMBER" id="input" class="form-control" /></td>
Now let's see this code in action!
Run the following snippet.
<td><input type="text" id="option" onchange="random()" class="form-control" />
<script>
function random()
{
var a=document.getElementById('option').value;
switch(a){
case "red":
var minimum = 5;
break;
case "green":
var minimum = 10;
break;
}
document.getElementById("input").setAttribute("min", minimum)//this line adds an attribute or sets it to a given value
}
</script>
<input type="NUMBER" id="input" class="form-control" /></td>
And done! Also, I changed the onkeydown to onchange.

Added more rows in case there are many rows with the same fields.
Secondly, I have added an event listener instead of direct function
call but you can do either.
Extracting into calculatingMinimunQuantity for easier readibility
and calling setAttribute (min) there.
var options = document.querySelectorAll(".option");
options.forEach(function(option) {
option.addEventListener("change", function() {
calculatingMinimunQuantity(option);
});
});
function calculatingMinimunQuantity(option) {
var minimum = 0;
var value = option.value;
if (value === "red") {
minimum = "5";
} else if (value === "green") {
minimum = "10";
}
// getting the quantity input field
option.nextElementSibling.setAttribute("min", minimum);
}
<td>
<div>
<input type="text" class="option form-control" placeholder="option" name="option" />
<input type="NUMBER" class="form-control" name="qty" placeholder="quantity" />
</div>
</td>
<td>
<div>
<input type="text" class="option form-control" placeholder="option" name="option" />
<input type="NUMBER" class="form-control" name="qty" placeholder="quantity" />
</div>
</td>

Related

How to multiple (a*b) two input text value and show it Dynamicly with text change in javascript?

i want to show the money that customer must pay and my inputs are like this :
<input type="text" class="form-control" placeholder="cost " id="txt" name="credit">
<input type="text" class="form-control" placeholder="quantity" id="txt" name="limit">
when the input text is changing i want to show the total cost (quantity*cost) in a <p> tag Dynamicly how can it be with javascript?
You can try this:
<input type="text" class="form-control" placeholder="cost " id="credit" name="credit" onchange="calculate()">
<input type="text" class="form-control" placeholder="quantity" id="limit" name="limit" onchange="calculate()">
<p id="result"></p>
And javascript part:
function calculate() {
var cost = Number(document.getElementById("credit"));
var limit = Number(document.getElementById("limit"));
document.getElementById("result").innerHTML= cost*limit;
}
You must ensure you entered numbers in inputs.
All of the above will generate errors if both the boxes are blank . Try this code , its tested and running .
<script>
function calc()
{
var credit = document.getElementById("credit").value;
var limit = document.getElementById("limit").value;
if(credit == '' && limit != '')
{
document.getElementById("cost").innerHTML = parseInt(limit);
}
else if(limit == '' && credit != '')
{
document.getElementById("cost").innerHTML = parseInt(credit);
}
else if(limit!= '' && credit!= '')
{
document.getElementById("cost").innerHTML = parseInt(limit) * parseInt(credit);
}
else
{
document.getElementById("cost").innerHTML = '';
}
}
</script>
</head>
<input type="number" value="0" min="0" class="form-control" placeholder="cost" id="credit" name="credit" onkeyup="calc();">
<input type="number" value="0" min="0" class="form-control" placeholder="quantity" id="limit" name="limit" onkeyup="calc();">
<p id="cost"></p>
Hope this will be useful
// get cost field
var _cost = document.getElementById("cost");
_cost.addEventListener('keyup',function(event){
updateCost()
})
// get quantity field
var _quantity = document.getElementById("quantity");
_quantity.addEventListener('keyup',function(event){
updateCost()
})
function updateCost(){
var _getCost = document.getElementById("cost").value;
var _getQuantity = document.getElementById("quantity").value;
var _total = _getCost*_getQuantity;
console.log(_total);
document.getElementById("updateValue").textContent = ""; // Erase previous value
document.getElementById("updateValue").textContent = _total // update with new value
}
jsfiddle
In case you consider using JQuery I've made this fiddle.
See if it works for you.
https://fiddle.jshell.net/9cpbdegt/
$(document).ready(function() {
$('#credit').keyup(function() {
recalc();
});
$('#limit').keyup(function() {
recalc();
});
function recalc() {
var credit = $("#credit").val();
var limit = $("#limit").val();
var result = credit * limit;
$("#result").text(result);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" placeholder="cost " id="credit" name="credit" value="0">x
<input type="text" class="form-control" placeholder="quantity" id="limit" name="limit" value="0">
<p id="result">0</p>
Try this:
<script >
function myFunction() {
document.getElementById('totalcost').innerHTML = document.getElementById('txt').value * document.getElementById('txt2').value;}
</script>
Also, change your HTML to this:
<input type="text" onkeypress="myFunction()" onkeyup="myFunction()" onclick="myFunction()" onmousemove="myFunction()" class="form-control" placeholder="cost " id="txt" name="credit">
<input type="text" onkeypress="myFunction()" onkeyup="myFunction()" onclick="myFunction()" onmousemove="myFunction()" class="form-control" placeholder="quantity" id="txt2" name="limit">
Enter cost and quantity.
Note the change with the second input: id='txt' was changed to id='txt2'. This is because no 2 elements can have the same id.
Note: Untested.

How to get the product of two field into another field in each button click

I have 3 textboxes.product of two textboxes are get into another textbox automatically.the fields are quantity and per/unit.then these two is multiplied into the field amount in each click.But the problm is i got the product in first click only..
js
var new_string='<div class="form-group" id="exp_'+unqid+'">'
+'<label for="exampleInputPassword1">'+name+'</label> </br>'
+'<input name="quantity_'+unqid+'" type="text" id="quantity" style="margin-right:20px;" class="form-con" placeholder="Quantity" required>'
+'<input name="perunit_'+unqid+'" type="text" id="perunit" style="margin-right:20px;" onchange="getTotalAmount('+unqid+')" class="form-con" placeholder="Per/unit" required>'
+'<input name="amount_'+unqid+'" type="text" id="amount" class="form-con" placeholder="Amount" required></div>';
$("#create").append(new_string);
called function
function getTotalAmount(unqid)
{
alert(unqid);
var q = document.getElementById("quantity").value;
//alert(q);
var p = document.getElementById("perunit").value;
// alert(p);
if(q!='' && p!='')
{
var total = p * q;
// alert(total);
document.getElementById("amount").value = total;
}
}
You can do something like this :
html code
Value 1<input type="text" id="t1"><br/>
Value 2<input type="text" id="t2"><br/>
Result<input type="text" id="t3">
js:
$('#t2').blur(function(){
var a = $('#t1').val();
var b = $('#t2').val();
var c = a*b;
$('#t3').val(c)
});
and check at https://jsfiddle.net/ejzn66n5/

How do I use javascript or jquery to find a sum and product of values from a forms field inputs?

How do I use javascript or jquery to find a sum and product of number values that users enter into my forms fields. Thanks for your time and help.
Input 1 Value + Input 2 Value = Input A
Input A Value * .08 = Input B Value
Input A Value + Input B Value = Total Input
<form>
<input type="text" id="1" name="1">
<input type="hidden" id="2" name="2" value="33">
<input type="text" id="A" name="A">
<input type="text" id="B" name="B">
<input type="text" id="total" name="total">
<button type="button" id="button" name="button">
</form>
WHAT IVE TRIED
<script>
var $form = $('#contactForm'),
$summands = $form.find('.sum1'),
$sumDisplay = $('#itmttl');
$form.delegate('.sum1', 'change', function ()
{
var sum = 0;
$summands.each(function ()
{
var value = Number($(this).val());
if (!isNaN(value)) sum += value;
});
$sumDisplay.val(sum);
});
</script>
<script>
function multiply(one, two) {
if(one && two){
this.form.elements.tax.value = one * two;
} else {
this.style.color='blue';
}
}
</script>
Please find Fiddle link
JSFiddle
$(document).ready(function(){
$('#calculate').on('click',function(){
var v1 = $('#1').val(); // take first text box value
var v2 = $('#2').val(); // take second hidden text box value
$('#A').val(parseInt(v1)+parseInt(v2)); // set value of A
var aval = (parseInt($('#A').val()) * parseFloat(.8)); // calculate value of b
$('#B').val(aval);// set value of B
var totalval = parseInt($('#A').val()) + parseFloat(aval);
//calculate value for total
$("#total").val(totalval); // set total
})
});
I assume you want to update the fields when you lick the button? Created a snippet instead of a fiddle:
$("#button").click(function() {
$("#A").val( parseInt($("#1").val()) + parseInt($("#2").val()) );
$("#B").val(parseInt($("#A").val()) * .8);
$("#total").val( parseInt($("#A").val()) + parseInt($("#B").val()) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="1" name="1">
<input type="hidden" id="2" name="2" value="33">
<input type="text" id="A" name="A">
<input type="text" id="B" name="B">
<input type="text" id="total" name="total">
<button type="button" id="button" name="button">
</form>

auto calculate without clicking any button

Hi I'm new for programming and I'm facing one problem.
I have 3 input for values and 1 input for total. What I need is when I change the value in any input total should change automatically.
<input type="text" name="Amt" id="amount" class="form-control" />
<input type="text" name="Amt" id="amount" class="form-control" />
<input type="text" name="Amt" id="amount" class="form-control" />
And for total I have:
<input type="text" class="form-control" name="total" id="total" value="" />
And below is the script:
<script type="text/javascript">
$('#amount').change(function() {
$('#total').attr('value', function() {
var result = 0;
$('#amount').each(function() {
result += $(this).attr('value');
});
return result;
});
});
</script>
You have multiple ids for amount. These should be changed to classes. In addition, the value for each amount will be picked out by jQuery as a string, so that needs to be changed to an integer:
$('.amount').change(function () {
var result = 0;
$('.amount').each(function () {
result += +$(this).val();
});
$('#total').val(result);
});
Fiddle.

2 name attributes for a field in a form

I have a script that calculates the values in each and shows the calulated values. At the end it also calculates the already calculated values from all div's
Here is the html code:
<td>
<div>
<input name="r" class="rate" type="text" maxlength="255" size="5" value />
<input name="p" class="pack" type="text" maxlength="255" size="5" value />
<span class="amount"></span>
</div>
</td>
<td>
<div>
<input name="r" class="rate" type="text" maxlength="255" size="5" value />
<input name="p" class="pack" type="text" maxlength="255" size="5" value />
<span class="amount"></span>
</div>
</td>
The problem is that I want to put all fields in a form and then submit them to a database.
However, all divs contain two input fields with name "r" and "p".
So, I am kind of stuck here because I cannot figure out how to make the names unique or how to have them passed to the DB using POST.
This is what the calculating script looks like:
<script type="text/javascript">//<![CDATA[
//any time the amount changes
$(document).ready(function() {
$('input[name=r],input[name=p]').change(function(e) {
var total = 0;
var $row = $(this).parent();
var rate = $row.find('input[name=r]').val();
var pack = $row.find('input[name=p]').val();
total = parseFloat(rate * pack);
//update the row total
$row.find('.amount').text(total);
var total_amount = 0;
$('.amount').each(function() {
//Get the value
var am= $(this).text();
console.log(am);
//if it's a number add it to the total
if (IsNumeric(am)) {
total_amount += parseFloat(am, 10);
}
});
$('.total_amount').text(total_amount);
});
});
//isNumeric function Stolen from:
//http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric
function IsNumeric(input) {
return (input - 0) == input && input.length > 0;
}
//]]>
</script>
HTML:
<input type="text" name="r[]">
<input type="text" name="p[]">
<hr>
<input type="text" name="r[]">
<input type="text" name="p[]">
<hr>
<input type="text" name="r[]">
<input type="text" name="p[]">
PHP:
for ($i = 0; $i < count($_POST['p']); $i++) {
$rate = $_POST['r'][$i];
$pack = $_POST['p'][$i];
// do something with $rate and $pack
}
Since the browser submits all inputs (even if no value has been entered) and by specification it submits them in the order they are defined in the HTML code, you can rely that the elements in the two $_POST arrays will line up and the corresponding rate and pack will be received at the same index in the respective array.

Categories

Resources