Keyup function isn't changing input box? - javascript

I am trying to create a simple form that calculates a few fields and calculates the total price as unit cost * quantity. I am trying to use a keyup function to automatically change the unit price as the entered unit price changes, but when I change the price nothing happens.
HTML
<!-- Div for quantity -->
<div class="form-group">
<input type="number" class="form-control" id="quantity" name="quantity" placeholder="Quantity" required>
</div>
<!-- Div for unit price -->
<div class="form-group">
<input type="number" class="form-control" id="unitPrice" name="unitPrice" placeholder="Unit Price" required>
</div>
<!-- div for cost -->
<div class="form-group">
<input type="number" class="form-control" id="cost" name="cost" placeholder="Cost" required>
</div>
JS
$(document).ready(function () {
$("#unitPrice").keyup(function () {
var quantity = +$("#quantity").val();
var price = +$("#unitPrice").val();
$("#cost").val(quantity * unitPrice);
});
});
});

It's a typo.
Change
$("#cost").val(quantity * unitPrice);
to
$("#cost").val(quantity * price);

Here's a working solution. Your variable name is
price
NOT unitPrice
.Hope it helps!
$(document).ready(function () {
$("#unitPrice").keyup(function () {
var quantity = +$("#quantity").val();
var price = +$("#unitPrice").val();
$("#cost").val(quantity * price);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<div class="form-group">
<input type="number" class="form-control" id="quantity" name="quantity" placeholder="Quantity" required>
</div>
<!-- Div for unit price -->
<div class="form-group">
<input type="number" class="form-control" id="unitPrice" name="unitPrice" placeholder="Unit Price" required>
</div>
<!-- div for cost -->
<div class="form-group">
<input type="number" class="form-control" id="cost" name="cost" placeholder="Cost" required>
</div>

You have used the wrong variable name. Replace this line
$("#cost").val(quantity * unitPrice);
with
$("#cost").val(quantity * price);

Related

Make the result of input 1 and input 2 appear in input 3 automatically [duplicate]

This question already has answers here:
Summation of field values using keyup event
(3 answers)
Closed 11 months ago.
I just want to make the result of input 1 and input 2 appear in input 3 without clicking any button or text. It means if user write number 5 in input 1 and number 5 in input 2 will automatically show the result 10 in input 3. I have this code :
<div class="inputs">
<div class="input-box">
<label for="exampleInputEmail1" class="details">number 1</label>
<input type="number" name="num1" class="form-control" id="num1" value="<?php echo
$num1?>" placeholder="0" aria-describedby="emailHelp">
</div>
<div class="input-box">
<label for="exampleInputEmail1" class="details">number 2</label>
<input type="number" name="num2" class="form-control" id="num2" value="<?php echo
$num2?>" placeholder="0" aria-describedby="emailHelp">
</div>
<div class="input-box">
<label for="exampleInputEmail1" class="details">result</label>
<input type="number" name="res" class="form-control" id="res" value="<?php echo
$res?>" placeholder="0" aria-describedby="emailHelp">
</div>
</div>
java script :
<script>
function myFunction() {
var x = parseInt(document.getElementById("num1").value);
var y = parseInt(document.getElementById("num2").value);
var z = x + y;
document.getElementById("res").innerHTML = z;
}
</script>
There are a few adjustments you need to do.
You need to call you function myFunction() at the event oninput, and you need to call it on the input <input> fields not on the result <input> field as you did it.
In myFunction() you need to check whether a value could be parsed using isNaN(). In case of a sum it's probably a good idea to set a default value of 0 in case some invalid value was entered or one field is empty.
function myFunction() {
var x = parseInt(document.getElementById("num1").value);
// set default value to 0 if parsing was not successful
if (isNaN(x)) x = 0;
var y = parseInt(document.getElementById("num2").value);
// set default value to 0 if parsing was not successful
if (isNaN(y)) y = 0;
var z = x + y;
document.getElementById("res").value = z;
}
<div class="inputs">
<div class="input-box">
<label for="exampleInputEmail1" class="details">number 1</label>
<input type="number" name="num1" class="form-control" id="num1" oninput="myFunction()" value="<?php echo
$num1?>" placeholder="0" aria-describedby="emailHelp" />
</div>
<div class="input-box">
<label for="exampleInputEmail1" class="details">number 2</label>
<input type="number" name="num2" class="form-control" id="num2" oninput="myFunction()" value="<?php echo
$num2?>" placeholder="0" aria-describedby="emailHelp" />
</div>
<div class="input-box">
<label for="exampleInputEmail1" class="details">result</label>
<input type="number" name="res" class="form-control" id="res" value="<?php echo
$res?>" placeholder="0" aria-describedby="emailHelp" />
</div>
</div>

How to get multiple values from input field in jquery?

I want to get input field values which are in foreach loop using jquery . Here is the html structure
#foreach ($products as $product)
<div class = "form-row">
<input type="text" name="quantity" class="form-control quantity"value="{{$product->quantity }}">
<input type="text" name="price" class="form-control price"value="{{$product->price}}">
</div>
#endforeach
I'm trying to get value in this way
var quantity = $('.quantity').val();
var price= $('.price').val();
But In this way, I get only first-row value. How can get all rows value using jquery?
You have to loop through all the elements to get the values from them.
You can try jQuery's .map() and .get() to get all the values in an array.
Demo:
var quantityArr = $('.quantity').map(function(){
return +this.value;
}).get();
console.log(quantityArr);
// if you want the value comma separated then join the array
var quantityCommaSeperatedString = quantityArr.join(',');
console.log(quantityCommaSeperatedString);
var priceArr = $('.price').map(function(){
return +this.value;
}).get();
console.log(priceArr);
// if you want the value comma separated then join the array
var priceCommaSeperatedString = priceArr.join(',');
console.log(priceCommaSeperatedString);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="quantity" class="form-control quantity"value="1">
<input type="text" name="price" class="form-control price"value="10">
<input type="text" name="quantity" class="form-control quantity"value="2">
<input type="text" name="price" class="form-control price"value="20">
<input type="text" name="quantity" class="form-control quantity"value="3">
<input type="text" name="price" class="form-control price"value="30">
Update: As mentioned in the comment: get values by row
$('.form-row').click(function(){
var quantity = $(this).find('.quantity').val();
console.log(quantity);
var price = $(this).find('.price').val();
console.log(price);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class = "form-row">
<input type="text" name="quantity" class="form-control quantity"value="1">
<input type="text" name="price" class="form-control price"value="10">
</div>
<div class = "form-row">
<input type="text" name="quantity" class="form-control quantity"value="2">
<input type="text" name="price" class="form-control price"value="20">
</div>
<div class = "form-row">
<input type="text" name="quantity" class="form-control quantity"value="3">
<input type="text" name="price" class="form-control price"value="30">
</div>

Click function does not append HTML block using append() function

I'm trying to append the same code again on click. My 'education_wrap" class empty for now. Other than that I have just added in-line CSS for now.
var max_fields = 5; //maximum input boxes allowed
var wrapper = $(".education_wrap"); //Fields wrapper
var add_button = $("#add_education"); //Add button ID
$(add_button).click(function(e){
e.preventDefault();
var total_fields = wrapper[0].childNodes.length;
if(total_fields < max_fields){
$(wrapper).append('<p style="font-weight:bold;">Institute Name<span class="required">*</span></p><div class="item"><input type="text" id="institute" name="institute" placeholder="Institute Name" required/></div><p style="font-weight:bold;">Degree Name<span class="required">*</span></p><div class="item"><input type="text" id="degree" name="degreen" placeholder="Bachelor of Engineering in Software Engineering, etc." required/></div><p style="font-weight:bold;">From<span class="required">*</span></p><div class="item"><input type="date" id="from_date" name="from_date" value="2020-07-22" required/></div><p style="font-weight:bold;">To<span class="required">*</span></p><div class="item"> <input type="date" id="to_date" name="to_date" value="2020-07-22" required/></div></div>'); //add input box
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form><h3 style="font-weight: bold;">Education</h3>
<div class="education_wrap">
<p style="font-weight:bold;">Institute Name<span class="required">*</span></p>
<div>
<input type="text" id="institute" name="institute" placeholder="Institute Name" required/>
</div>
<p style="font-weight:bold;">Degree Name<span class="required">*</span></p>
<div>
<input type="text" id="degree" name="degreen" placeholder="Bachelor of Engineering in Software Engineering, etc." required/>
</div>
<p style="font-weight:bold;">From<span class="required">*</span></p>
<div>
<input type="date" id="from_date" name="from_date" value="2020-07-22" required/>
</div>
<p style="font-weight:bold;">To<span class="required">*</span></p>
<div>
<input type="date" id="to_date" name="to_date" value="2020-07-22" required/>
</div>
</div>
<div style="margin-top:20px;">
<button id="add_education">Add Another Education</button>
</div></form>
Also, I cannot get my mind around how to submit multiple sets of information using POST method for once. Please guide.
var max_fields = 5; //maximum input boxes allowed
var wrapper = $(".education_wrap"); //Fields wrapper
var add_button = $("#add_education"); //Add button ID
$(add_button).click(function(e) {
var total_fields = wrapper[0].childNodes.length;
alert(total_fields < max_fields);
//if (total_fields < max_fields) { // this condition returns false that's why it creates issue
$(wrapper).append('<p style="font-weight:bold;">Institute Name<span class="required">*</span></p><div class="item"><input type="text" id="institute" name="institute" placeholder="Institute Name" required/></div><p style="font-weight:bold;">Degree Name<span class="required">*</span></p><div class="item"><input type="text" id="degree" name="degreen" placeholder="Bachelor of Engineering in Software Engineering, etc." required/></div><p style="font-weight:bold;">From<span class="required">*</span></p><div class="item"><input type="date" id="from_date" name="from_date" value="2020-07-22" required/></div><p style="font-weight:bold;">To<span class="required">*</span></p><div class="item"> <input type="date" id="to_date" name="to_date" value="2020-07-22" required/></div></div>'); //add input box
//}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<h3 style="font-weight: bold;">Education</h3>
<div class="education_wrap">
<p style="font-weight:bold;">Institute Name<span class="required">*</span></p>
<div>
<input type="text" id="institute" name="institute" placeholder="Institute Name" required/>
</div>
<p style="font-weight:bold;">Degree Name<span class="required">*</span></p>
<div>
<input type="text" id="degree" name="degreen" placeholder="Bachelor of Engineering in Software Engineering, etc." required/>
</div>
<p style="font-weight:bold;">From<span class="required">*</span></p>
<div>
<input type="date" id="from_date" name="from_date" value="2020-07-22" required/>
</div>
<p style="font-weight:bold;">To<span class="required">*</span></p>
<div>
<input type="date" id="to_date" name="to_date" value="2020-07-22" required/>
</div>
</div>
<div style="margin-top:20px;">
<button type="submit" id="add_education">Add Another Education</button>
</div>
</form>
Note:- There is a slight mistake in your code. There is one if condition which returns a false value that's why a block of code is not executed.
There is many issue in your Code, follow below things:
1 . if(total_fields < max_fields){ Here your condition getting false, so no append process will begin
2 . use type="button" instead of submit
3 . use separate button for append html and for submit form
for how to submit multiple sets of information using POST
use input name as array like <input type="date" id="from_date" name="from_date[]" value="2020-07-22" required/>
use classes instead of id here because of repetition here id="from_date"

JQuery - Get values from html array inputs

A user has the capacity to add as many items as possible through html inputs. The inputs look like;
<input class="form-control" name="part_number[]" number" type="text">
<input class="form-control" name="part_number[]" number" type="text">
<input class="form-control" name="part_number[]" number" type="text">
<input class="form-control item" name="description[]" type="text">
<input class="form-control item" name="description[]" type="text">
<input class="form-control item" name="description[]" type="text">
I would like to add the items to my database for storage.. How do i iternate through each input? part number and description belong to a single row.
function getdata() {
var partNumbers = [];
var descriptions = [];
$('[name="part_number[]"]').each(function() {
partNumbers.push(this.value);
})
$('[name="description[]"]').each(function() {
descriptions.push(this.value);
})
var data = {
partNumbers: partNumbers,
descriptions: descriptions
}
$('#output').val(JSON.stringify(data))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="form-control" name="part_number[]" type="text" value="part number 1">
<input class="form-control" name="part_number[]" type="text" value="part number 2">
<input class="form-control" name="part_number[]" type="text" value="part number 3">
<br>
<input class="form-control item" name="description[]" type="text" value="description 1">
<input class="form-control item" name="description[]" type="text" value="description 2">
<input class="form-control item" name="description[]" type="text" value="description 3">
<hr>
<button type="button" onclick="getdata()">get data</button>
<textarea id="output" rows="10" cols="100" placeholder="output"></textarea>
If your inputs are within a form, you can use .serializeArray() and then .reduce() it to create an object which stores keys and array values for multiple input types like below. You can then submit this data to your server to then store in your database:
const data = $("#myform").serializeArray().reduce((acc, o) => {
if (o.name.slice(-2) === "[]") {
acc[o.name] = acc[o.name] || [];
acc[o.name].push(o.value);
} else {
acc[o.name] = o.value;
}
return acc;
}, {});
console.log(data); // data to POST
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myform">
<input class="form-control" name="part_number[]" value="pn1" type="text">
<input class="form-control" name="part_number[]" value="pn2" type="text">
<input class="form-control" name="part_number[]" value="pn3" type="text">
<input class="form-control item" name="description[]" value="desc1" type="text">
<input class="form-control item" name="description[]" value="desc2" type="text">
<input class="form-control item" name="description[]" value="desc3" type="text">
<input class="form-control item" name="single_data" value="non-array data" type="text">
</form>
From your question, I understand that you want the description and part number in a row.
Please find my answer using .each function of jQuery.
The .each() function iterates through all the specified elements and it returns the index position of each element. Here I'm iterating through the part number, so I want to take the corresponding description, that is the description at the index position of part_number. To achieve this am using another jQuery selector :eq(). It will select the element at index n within the matched set.
$(".submit").on("click", function(){
let user_input = [];
$("input[name='part_number[]']").each(function(index){
user_input.push({
part_number: $(this).val(),
description: $(`.item:eq(${index})`).val()
});
});
console.log("final result = ", user_input);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="form-control" name="part_number[]" placeholder="number" type="text">
<input class="form-control" name="part_number[]" placeholder="number" type="text">
<input class="form-control" name="part_number[]" placeholder="number" type="text">
<input class="form-control item" name="description[]" placeholder="description" type="text">
<input class="form-control item" name="description[]" placeholder="description" type="text">
<input class="form-control item" name="description[]" placeholder="description" type="text">
<button type="submit" class="submit"> Save</button>
I would rather fix the HTML than trying to fix the data afterwards.
You have items with the values descriptionand part_number, in order to group the data i would firstly group them visually in your HTML by adding a wrapper around each part_number + description pair:
<div class="item">
<input type="text" name="part_number[]" />
<input type="text" name="decription[]" />
</div>
After that we fix the input names' and add them to a group item:
<div class="item">
<input type="text" name="item[part_number]" />
<input type="text" name="item[decription]" />
</div>
To add multiple item elements in your form you need to add an ID to each item when adding it to your form:
<div class="item">
<input type="text" name="item[0][part_number]" />
<input type="text" name="item[0][decription]" />
</div>
<div class="item">
<input type="text" name="item[1][part_number]" />
<input type="text" name="item[1][decription]" />
</div>
When adding these values to your database you can then iterate over them like so: ( I'm just guessing you will use PHP)
foreach( $_POST['item'] as $item) {
$item['part_number'];
$item['description];
}

My onchange is not working

I need to double the price but the function is not working. The total not display. Below is the code.
This is my form:
<label>Price</label>
<input type="text" id="price" name="price" value="<%=rs.getDouble(2)%>" onchange="autoprice()"/>
<label>Total</label>
<input type="text" id="total" name="total" readonly="readonly"/>
my script:
<script>
function autoprice(){
var x = document.getElementById("price").value;
document.getElementById("total").value = (x * 2).toFixed(2);
}
</script>
Here I made a snippet of your code and its working fine.
function autoprice() {
var x = document.getElementById("price").value;
document.getElementById("total").value = (x * 2).toFixed(2);
}
<label>Price</label>
<input type="text" id="price" name="price" value="" onchange="autoprice()" />
<label>Total</label>
<input type="text" id="total" name="total" readonly="readonly" />
Onchange needs the cursor move out of focus. After entering value press Tab or Enter. Use oninput, if you want to change it dynamically when the value is changed like the below code.
<label>Price</label>
<input type="text" id="price" name="price" value="" oninput="autoprice()"/>
<label>Total</label>
<input type="text" id="total" name="total" readonly="readonly"/>
<script>
function autoprice(){
var x = document.getElementById("price").value;
document.getElementById("total").value = (x * 2).toFixed(2);
}
</script>

Categories