How to display the total number of quantity in the input box - javascript

I have a quantity field. The user can add multiple quantity fields on click on Add button.
My issue is, I have to display the total number of quantity in the input box. for example I added 10 quantity in the quantity box and the total is 10 in the total box.
The user can increase and decrease the quantity on click on plus and minus button as well as direct enter then quantity in the quantity box and total will display in the total box.
The user can add multiple quantities field same as on remove. I click on to remove the quantity should be removed from the total quantity field.
You can also check my code here as well https://jsfiddle.net/pu6qy4zr/70/
function increaseValue(n) {
var value = parseInt(document.getElementById('number' + n).value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('number' + n).value = value;
}
function decreaseValue(n) {
var value = parseInt(document.getElementById('number' + n).value, 10);
value = isNaN(value) ? 0 : value;
value < 1 ? value = 1 : '';
value--;
document.getElementById('number' + n).value = value;
}
$(document).ready(function() {
var max_fields = 20; //maximum input boxes allowed
var wrapper = $(".add_row"); //Fields wrapper
var add_button = $(".add_row_click"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$("input[id^=medication_name]").focus();
$(wrapper).append('<div class="custom_fields"><div class="col-md-6"><div class="row"><div class="col-md-6"><div class="form_group"><div class="plus_minus"><span class="value_button decrease" onclick="decreaseValue(' + x + ')" value="Decrease Value"> - </span><input type="number" id="number' + x + '" class="qty_number form_control" name="qty_number[]" class="form_control" value="0" /><span class="value_button increase" onclick="increaseValue(' + x + ')" value="Increase Value"> + </span></div></div></div><div class="col-md-6"><div class="form_group"> <div class="btn_row remove_field"> <span> - </span> Remove </div></div></div></div></div></div></div>');
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).closest('.custom_fields').remove();
x--;
})
});
<div class="add_row">
<div class="plus_minus">
<span class="value_button decrease" onclick="decreaseValue(1)" value="Decrease Value">-</span>
<input type="number" id="number1" class="qty_number form_control" name="qty_number[]" value="0" class="form_control" />
<span class="value_button increase" onclick="increaseValue(1)" value="Increase Value">+</span>
</div>
<div class="btn_row add_row_click"> <span> + </span> Add </div>
</div>
<input type="text" class="form_control" name="total_qty" id="total_qty" value="" placeholder="Total number of quantity" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

You can simplify all this.
run sum() on each change including the remove and direct input/paste.
only have one event handler for the plus/minus
remove the inline handlers
PS: I found a bug: value < 1 ? value = 1 : ''; would force a value of 1
PPS: I suggest you use .clone for the div instead of inserting it. Makes it much easier to update the HTML. Since I delegate and use relative addressing, you do not need to change the IDs of the fields
function sum() {
var total = 0;
$(".qty_number").each(function() { // or use .map.get()
total += this.value?parseInt(this.value):0;
})
$("#total_qty").val(total);
}
$(document).ready(function() {
var max_fields = 20; //maximum input boxes allowed
var $wrapper = $(".add_row"); //Fields wrapper
var add_button = $(".add_row_click"); //Add button ID
var x = 1; //initlal text box count
$(add_button).on("click",function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$("input[id^=medication_name]").focus();
$wrapper.append('<div class="custom_fields"><div class="col-md-6"><div class="row"><div class="col-md-6"><div class="form_group"><div class="plus_minus"><span class="value_button decrease" value="Decrease Value"> - </span><input type="number" id="number' + x + '" class="qty_number form_control" name="qty_number[]" class="form_control" value="0" /><span class="value_button increase" value="Increase Value"> + </span></div></div></div><div class="col-md-6"><div class="form_group"> <div class="btn_row remove_field"> <span> - </span> Remove </div></div></div></div></div></div></div>');
}
});
$wrapper.on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).closest('.custom_fields').remove();
x--;
sum(); // remove also updates the total
})
$wrapper.on("click",".value_button",function() {
var $input = $(this).closest(".plus_minus").find(".qty_number");
var value = parseInt($input.val(), 10);
value = isNaN(value) ? 0 : value;
value+=$(this).is(".decrease")?-1:1; // decrease on increase dependent on class
if (value < 0) value=0;
$input.val(value);
sum(); // sum each time
});
$wrapper.on("input",".qty_number",sum); // any input or paste
});
<div class="add_row">
<div class="plus_minus">
<span class="value_button decrease" value="Decrease Value">-</span>
<input type="number" id="number1" class="qty_number form_control" name="qty_number[]" value="0" class="form_control" />
<span class="value_button increase" value="Increase Value">+</span>
</div>
<div class="btn_row add_row_click"> <span> + </span> Add </div>
</div>
<input type="text" class="form_control" name="total_qty" id="total_qty" value="" placeholder="Total number of quantity" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related

Checkbox doesn't store the value

I am trying to create a dynamic Question List along with its dynamic options. With each option I maintain a flag using checkbox. If the checkbox is clicked the AnalysisFlag value should be true and if not then it should be false. However using the below mentioned method, I am always getting the false value whether I clicked the checkbox or not.
Can someone please take a look and suggest me how I can maintain the AnalysisFlag value along with its equivalent option?
function GetDynamicTextBox(value) {
var textBox = $("<input />").attr("type", "textbox").attr("name", "DynamicTextBox").attr("class", "form-control").attr("placeholder","Your Answer");
textBox.val(value);
debugger;
**var allVals = [];
$('[name="DynamicAnalysisFlag"]:checked').each(function () {
allVals.push($(this).val());
});**
return textBox, allVals;
}
var j = 66;
var x = 2;
var option = 'option' + x;
function AddTextBox() {
for (var i = j; i <= j; i++) {
$('#TextBoxContainer' + x).after("<br id='Removebr" + (x + 1) + "'><div class='input-group' id='TextBoxContainer" + (x + 1) + "'><div class= 'input-group-prepend'><div class='input-group-text'> " + String.fromCharCode(i) + " **<input type='checkbox' id='DynamicAnalysisFlag' value= 'true' name='DynamicAnalysisFlag' class='checklistitem''></div>**</div><input autocomplete='off' class='form-control test-option test-option" + x + " text-box single-line' data-val='true' data-val-required='Answer is required' id=" + option + " name='DynamicTextBox' placeholder='Your Answer' type='text' value=''><span class='field-validation-valid text-danger' data-valmsg-for='AnalysisFlag' data-valmsg-replace='true'></span></div>");
}
j++;
x++;
}
function RemoveTextBox() {
if (x != 2) {
$('#TextBoxContainer' + x).remove();
$('#Removebr' + x).remove();
--x;
--j;
}
}
$('#btnNext').on('click', function() {
var radioValue1 = $("input[name='AnalysisFlag']:checked").val();
var txtVal = $('.test-option' + radioValue1).val();
$('#hiddenRadioValue').val(txtVal);
});
$(function() {
var values = eval('#Html.Raw(ViewBag.Values)');
if (values != null) {
$("#TextBoxContainer").html("");
$(values).each(function() {
$("#TextBoxContainer").append(GetDynamicTextBox(this));
});
}
});
<div id="radio" class="col-xs-12">
<br id="Removebr2">
<div class="input-group" id="TextBoxContainer2">
<div class="input-group-prepend">
<div class="input-group-text">
A
<input type="checkbox" id="radio1" value="1" name="AnalysisFlag" onselect="alert('clicke')">
</div>
</div>
<input autocomplete="off" class="form-control test-option test-option1 text-box single-line" data-val="true" data-val-required="Option is required" id="opt1" name="opt1" placeholder="Your Answer" type="text" value="">
<span class="field-validation-valid text-danger" data-valmsg-for="opt1" data-valmsg-replace="true"></span>
<input data-val="true" data-val-required="The AnalysisFlag field is required." id="hiddenRadioValue" name="AnalysisFlag" type="hidden" value="">
<br>
</div>
</div>
<div class="card-footer">
<input type="submit" id="btnNext" value="Next »" class="btn btn-primary vigor-btn">
</div>
<button type="button" id="btnRemove" class="btn btn-primary vigor-btn" onclick="RemoveTextBox()">Remove Options</button>
<button type="button" id="btnAdd" class="btn btn-primary vigor-btn" onclick="AddTextBox()">Add Options</button>
I have edited the GetDynamicTextBox() function in which I am getting the DynamicAnalysisFlag value which I add at the time of adding another textbox in AddTextBox() function. But now the issue is, if I tick the checkbox I am getting the true value but if I don't tick the checkbox I am getting nothing. So, what changes should I do in this code so if I check the code, I get true and if not then I get false.

JQuery function does not respect clicked component

I have a product page where you can make customizations to the product such as adding or removing "ingredients" and for each customization that can be added or removed I create an input with a + and - button to increase or decrease my choice.
I inform via parameter to the javascript function the component (input) that will receive the increment or decrement, the maximum value that can be increased, the minimum value (decrement) and the increment interval.
However, for each possible customization in the product I must present a component like this:
<div class="qty mt-5">
<span class="minus" name="diminuir[]" onclick="AumentaDiminui('qty_4', 0, 5, 1)">-</span>
<input type="number" class="count" name="qty_4" value="0" step="1" max="5" min="0">
<span class="plus" name="aumentar[]" onclick="AumentaDiminui('qty_4', 0, 5, 1)">+</span>
</div>
And this is my java script function that should add or subtract the value and present it in the correct input
<script>
function AumentaDiminui(controle, valorMinimo, valorMaximo, valorIncremento) {
$(document).ready(function () {
$('[name="aumentar[]"]').click(function () {
if ($("[name=" + controle + "]").val() == valorMaximo)
return;
$("[name=" + controle + "]").val(parseInt($("[name=" + controle + "]").val()) + valorIncremento);
});
$('[name="diminuir[]"]').click(function () {
if ($("[name=" + controle + "]").val() <= valorMinimo) {
$("[name=" + controle + "]").val(valorMinimo);
return;
}
$("[name=" + controle + "]").val(parseInt($("[name=" + controle + "]").val()) - valorIncremento);
});
});
}
</script>
It turns out that the value is not incremented by 1 in 1 as I inform via parameter and if I have more than one component on the screen, when clicking on + or - the value of all inputs are changed regardless of the button I click on
A few comments about your code:
If jquery will handle the click events on the <span>, one should not define a onclick event in the span tag.
There is no need to define a function. You can just wait for the ready event and then monitor for clicks on both <span> (using the jquery .click() function).
You can access the values of min and max value defined in the <input> using the jquery .attr() function.
This is a working code:
$(document).ready(function () {
$('.qty .minus, .qty .plus').click(function () {
var input = $(this).parent().find('input[type=number]');
var newVal = +input.val();
var step = +input.attr('step');
if ($(this).hasClass('plus')){
newVal += step;
} else {
newVal -= step;
}
var min = input.attr('min');
var max = input.attr('max');
if (newVal > max) {
newVal = max;
} else if (newVal < min){
newVal = min;
}
input.val(newVal);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Step: 1</p>
<div class="qty mt-5">
<span class="minus">-</span>
<input type="number" class="count" value="0" step="1" max="5" min="0">
<span class="plus">+</span>
</div>
<p>Step: 2</p>
<div class="qty mt-5">
<span class="minus">-</span>
<input type="number" class="count" value="0" step="2" max="5" min="0">
<span class="plus">+</span>
</div>
There is a much easier way to do this, with just a few data-* attributes. This will work on any number of div elements with these attributes and a plus and minus button.
$('.qty').on('click','.minus', function(){
var $parent = $(this).parent();
var min = $parent.data('min');
var inc = $parent.data('inc');
var $input = $(this).siblings('.count');
var val = parseInt($input.val(),10);
if(val > min)
$input.val(val - inc);
})
$('.qty').on('click','.plus', function(){
var $parent = $(this).parent();
var max = $parent.data('max');
var inc = $parent.data('inc');
var $input = $(this).siblings('.count');
var val = parseInt($input.val(),10);
if(val < max)
$input.val(val + inc);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="qty mt-5" data-min="0" data-max="5" data-inc="1">
<span class="minus">-</span>
<input type="number" class="count" name="qty_4" value="0" step="1" max="5" min="0">
<span class="plus" name="aumentar[]">+</span>
</div>
<div class="qty mt-5" data-min="0" data-max="100" data-inc="5">
<span class="minus">-</span>
<input type="number" class="count" name="qty_4" value="0" step="1" max="5" min="0">
<span class="plus" name="aumentar[]">+</span>
</div>
You could also choose to read min, max and step from the input if you prefered with much the same logic.
create an jquery extension
(function($){
$.fn.AumentaDiminui = function(options) {
var settings = $.extend({ control: null, minvalue:1, maxvalue: 5 , action:'+' }, options );
var curval = $(settings .control).val ();
if ('+'==settings.action){
if (curval==settings.maxvalue) return;
curval++;
}
else {
if (curval==settings.minvalue) return;
curval++;
}
$(settings .control).val (curval);
};
}(jQuery));
call so as
$('div.qty.mt-5 span.minus').click(function (){ $.fn.AumentaDiminui({ action:'-', control:'div.qty.mt-5 input.count' }); });
$('div.qty.mt-5 span.plus').click(function (){ $.fn.AumentaDiminui({ action:'+', control:'div.qty.mt-5 input.count' }); });

Dynamically remove field button not working properly

Here is my code. I am able to add new field and appending the new field and remove button. There is two problem.
Remove button is not appending properly. It should append just after the
strength every time.
It Should remove respected input fields salt field and Strength field of every column.
$(document).ready(function() {
var max_fields = 100; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
var y = x - 1;
$(wrapper).append('<div class="input-field col s6"><input class="salt" id="salt' + y + '" name="drugs[' + y + '][salt]" type="text" required><label for="salt' + y + '">Salt/Drugs</label></div><div class="input-field col s6"><input class="strength" id="strength' + y + '" name="drugs[' + y + '][strength]" type="text" required><label for="strength' + y + '">Strength</label></div>'+'</div>'+' <div class="s4"><i class="material-icons">remove_circle</i></div>');
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent().remove();
x--;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="row input_fields_wrap">
<div class="input-field col s4">
<input class="salt" id="salt" name="drugs[0][salt]" type="text" required>
<label for="salt">Salt/Drugs</label>
</div>
<div class="input-field col s4">
<input class="strength" id="strength" name="drugs[0][strength]" type="text" required>
<label for="strength">Strength</label>
</div>
<div class="s4">
<button class="btn btn-large light-blue add_field_button">Add more salt/drugs</button>
</div>
</div>
I want it to be like this
Based on the link in the comment, it is better to restructure the htmlString.
You can try the following way:
$(document).ready(function() {
var max_fields = 100; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
var y = x - 1;
$(wrapper).prepend('<div class="input-field col s6"><input placeholder="Salt/Drugs" class="salt" id="salt' + y + '" name="drugs[' + y + '][salt]" type="text" required><input placeholder="Strength" class="strength" id="strength' + y + '" name="drugs[' + y + '][strength]" type="text" required><i class="material-icons">remove_circle</i></div></div>');
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent().remove();
x--;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="row input_fields_wrap">
<div class="input-field col s4">
<input placeholder="Salt/Drugs" class="salt" id="salt" name="drugs[0][salt]" type="text" required>
<input placeholder="Strength" class="strength" id="strength" name="drugs[0][strength]" type="text" required>
</div>
<div class="s4">
<button class="btn btn-large light-blue add_field_button">Add more salt/drugs</button>
</div>
</div>
Dynamically generated elements do not respond when listening the event directly, you have to listen to the DOM on them like
$(document).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent().remove();
x--;
})

How to add/delete 2 or more fields in a form dynamically

I would want to have two or more fields in a form to be dynamically added and deleted as per requirement. Say for, a person can have more than 1 phone numbers and more than 1 email address. The idea is to let the user add more than one phone number and email address if they have
This down below is what I did (only a rough example)
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 0;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('<div><input type="text" name="mytext[' + x + ']"/>Delete</div>'); //add input box
}
else
{
alert('You Reached the limits')
}
});
$(wrapper).on("click",".delete", function(e){
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container2");
var add_button = $(".add_form_field_1");
var x = 0;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('<div><input type="text" name="text[' + x + ']"/>Delete</div>'); //add input box
}
else
{
alert('You Reached the limits')
}
});
$(wrapper).on("click",".delete", function(e){
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
//I repeated the javascript for the first field which was this
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 0;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('<div><input type="text" name="mytext[' + x + ']"/>Delete</div>'); //add input box
}
else
{
alert('You Reached the limits')
}
});
$(wrapper).on("click",".delete", function(e){
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container1">
<button class="add_form_field">Add New Field <span style="font-size:16px; font-weight:bold;">+ </span></button>
<div>
<input type="text" name="mytext[]">
</div>
</div>
<div class="container2">
<button class="add_form_field_1">Add New Field <span style="font-size:16px; font-weight:bold;">+ </span></button>
<div>
<input type="text" name="text[]">
</div>
</div>
And the JsFiddle.
I am not a javascript coder hence do not know if this is how you do it or is there a better way.
P.S. I asked the same question an hour ago and had to rephrase it as it was causing confusion.
You can simplyfy so much your code, check this:
$(document).ready(function() {
$("button.add_form_field").click(function(e) {
e.preventDefault();
var name = $(this).closest(".container").find("input:first").attr("class")
var numInputs = $(this).closest(".container").find("input").size()
if (numInputs < 10) {
numInputs++;
if (name=="mytext"){
$(this).closest(".container").append('<div><input type="text" name="mytext[' + numInputs + ']"/>Delete</div>');
}
if (name=="text"){
$(this).closest(".container").append('<div><input type="text" name="text[' + numInputs + ']"/>Delete</div>');
}
} else alert('You Reached the limits')
});
$(document).on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<button class="add_form_field">Add New Field <span style="font-size:16px; font-weight:bold;">+ </span></button>
<div>
<input type="text" name="mytext[1]" class="mytext">
</div>
</div>
<div class="container">
<button class="add_form_field">Add New Field <span style="font-size:16px; font-weight:bold;">+ </span></button>
<div>
<input type="text" name="text[1]" class="text">
</div>
</div>
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="mytext[]"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>
Here is a working example, Hope this will helps you.
This may help you Mecom
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function removeUserDetail(index)
{
var rows=jQuery("#user_info tr").length;
jQuery("#user_info tr:nth-child("+(index+1)+")").remove();
if(index==(rows-1))
{
jQuery("#user_info tr:nth-child("+(index)+")").children().eq(4).append('<a class="mc_plus_button" id="plus_1" href="javascript:void();" onclick="addUserDetail();" title="add"><strong>+</strong></a>');
}
jQuery("#user_info tr").each(function(i,e){
if(i>1)
{
jQuery(this).children().eq(4).children().eq(0).attr("onclick","removeUserDetail("+i+");");
}
});
}
function addUserDetail() {
var row_count1 = jQuery("#user_info tr").length;
var row_count = 0;
jQuery(".tr_clone").each(function(index, value) {
var rowid = jQuery(this).data('rowid');
if (rowid > row_count) {
row_count = rowid;
}
});
row_count = row_count + 1;
jQuery("#user_info tr").eq(row_count1 - 1).find(".mc_plus_button").remove();
var html = '<tr class="tr_clone" data-rowid="' + row_count + '"><td>' + row_count + '</td>';
html += '<td style="text-align: center"><input type="text" name="user_info[name][]" id="name_'+row_count+'" aria-invalid="false" /></td>';
html += '<td style="text-align: center"><input type="text" name="user_info[email][]" id="email_'+row_count+'" aria-invalid="false" /></td>';
html += '<td style="text-align: center"><input type="text" name="user_info[contact][]" id="contact_'+row_count+'" aria-invalid="false" /></td>';
html += '<td><a class="mc_minus_button" id="minus_' + row_count + '" href="javascript:void();" onclick="removeUserDetail(' + row_count + ');" title="remove"><strong>–</strong></a><a class="mc_plus_button" href="javascript:void();" onclick="addUserDetail();" title="add"><strong>+</strong></a></td></tr>';
jQuery("#user_info").append(html);
}
</script>
<table id="user_info">
<tr>
<th>#</th>
<th>Name</th>
<th>Email</th>
<th>Contact</th>
</tr>
<tr class="tr_clone" data-rowid="1">
<td align="center">1</td>
<td style="text-align: center">
<input type="text" name="user_info[name][]" id="name_1" aria-invalid="false" />
</td>
<td style="text-align: center">
<input type="text" name="user_info[email][]" id="email_1" aria-invalid="false" />
</td>
<td style="text-align: center">
<input type="text" name="user_info[contact][]" id="contact_1" aria-invalid="false" />
</td>
<td><a class="mc_plus_button" href="javascript:void();" onclick="addUserDetail();" title="add"><strong>+</strong></a></td>
</tr>
</table>

Calculating price from <span> value and <input> value

Today I try to calculating the price from <span> value and <input> value. And then, put the result in <span>.
I already tried this code. This is my html:
<td class="cart-product-price">
<span id="price" class="amount">19.99</span>
</td>
<td class="cart-product-quantity">
<div class="quantity clearfix">
<input type="button" value="-" class="minus" field="quantity">
<input type="text" id="quantity" name="quantity" value="2" class="qty" />
<input type="button" value="+" class="plus" field="quantity">
</div>
</td>
<td class="cart-product-subtotal">
<span id="total" class="amount"></span>
</td>
So I want to get price value from <span id="price>, get quantity from <input type="text" id="quantity" name="quantity">, and put the result in <span id="total" class="amount"></span>
This is my script code:
<script type="text/javascript">
var price = parseFloat($('#price').val()) || 0;
var qty = parseInt($('input[name=quantity]').val());
var total = price*qty;
$('#total').text(total);
</script>
Note: I am using JQuery for increase / decrease quantity (plus & minus button)
Did I wrote something wrong?
Thanks
UPDATE
This is my increase / decrease javascript code:
<script type="text/javascript">
jQuery(document).ready(function(){
// This button will increment the value
$('.plus').click(function(e){
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If is not undefined
if (!isNaN(currentVal)) {
// Increment
$('input[name='+fieldName+']').val(currentVal + 1);
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
}
});
// This button will decrement the value till 0
$(".minus").click(function(e) {
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If it isn't undefined or its greater than 0
if (!isNaN(currentVal) && currentVal > 0) {
// Decrement one
$('input[name='+fieldName+']').val(currentVal - 1);
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
}
});
});
</script>
The 'price' field is a span, which do not have a value property. Instead, you need to read the text() from it. Also note that the 'quantity' field has an id, so you would be better to use that as a selector as it's much faster. Try this:
var price = parseFloat($('#price').text()) || 0;
var qty = parseInt($('#quantity').val());
var total = price * qty;
$('#total').text(total);
Working example
var price = parseFloat($('#price').text()) || 0; //parseFloat($('#price').val()) || 0;
var qty = parseInt($('input[name=quantity]').val());
var total = price * qty;
$('#total').text(total);
The .val() method is primarily used to get the values of form elements such as input , select and textarea
FIDDLE DEMO
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<style>
.active {
color:red;
}
</style>
<script>
$(document).ready(function () {
var price = parseFloat($('#price').text()) || 0;
var qty = parseInt($('input[name=quantity]').val());
var total = price * qty;
$('#total').text(total);
});
</script>
</head>
<body>
<table>
<tr>
<td class="cart-product-price">
<span id="price" class="amount">19.99</span>
</td>
<td class="cart-product-quantity">
<div class="quantity clearfix">
<input type="button" value="-" class="minus" field="quantity">
<input type="text" id="Text1" name="quantity" value="2" class="qty" />
<input type="button" value="+" class="plus" field="quantity">
</div>
</td>
<td class="cart-product-subtotal">
<span id="total" class="amount"></span>
</td>
</tr>
</table>
</body>
</html>

Categories

Resources