I am trying to multiply the contents of a text box called qty1 by the price in a select box that is retrieved using ajax.
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#stock1').on('change', function (){
var newValue1 = $.getJSON('select2.php', {stockID: $(this).val()}, function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options += data[x]['priceeach'];
}
$('#priceeach1').text(options);
var qty1 = $("#qty1").text();
var priceeach1 = $("#priceeach1").text();
$('#linetotal1').text(priceeach1 * qty1);
});
});
});
</script>
<script>
The script changes the values in this html :
Price Each : £<span id="priceeach1"></span> - Line Total : £<span id="linetotal1"></span>
The priceeach1 values are changed, but the linetotal1 value stay at 0, even when the select box is changed or the values in qty1 are changed. What should happen is priceeach1 from the drop down is multiplied by the text box qty1. For example if the priceeach1 = 20.00 and the qty1 was 2 linetotal1 would be 40.00 , but all I get at present is 0 .
The qty1 as you say in the description is a textbox. And you are getting its value using the text() property. That's why you get blank as an answer.
Use the .val() property to get the value of a textbox.
You have to parse the values as Float or Int using parseFloat or parseInt
var qty1 = $("#qty1").html();
var priceeach1 = $("#priceeach1").html();
var total=parseFloat(priceeach1) * parseInt(qty1);
$('#linetotal1').html(total);
Related
I'll try my best to explain my current problem.
I've created a view, something like excel. It's dynamically created. (see below)
A B C
| 1| | 3| | 7| // The input format is `<input type='text' class='inputitem' id='colA_row1' />`
| 2| | 6| | 8| // The `id` of this `inputitem`is defined by the number of columns and rows automatically
| 9| | 7| | 4|
|12| |16| |19| // The format of total textbox is `<input type='text' class='totalitem' id='total_colA' />
//// The `id` of this `totalitem` is defined by the number of column automatically
User may input any number to any inputitem and the value of totalitem is adjusted to the SUM of value in each column. (in example, if user change the value of column A row 2 to 9, the totalcolumn of column A is changed into 19)
This is my current jquery code:
$('.inputitem').on('keyup', function(){
var _inputitem = $(this);
var _inputitem_arr = $(this).attr('id').split('_');
var _inputitem_col = _inputitem_arr[0];
var _inputitem_row = _inputitem_arr[1];
/*SUM SCRIPT*/
var sum_item = 0;
$('.inputitem').each(function(i){
var inputitem_val = parseFloat($(this).val().replace(',', ''));
$('.totalitem').each(function(i){
var _totalitem = $(this);
var _totalitem_arr = $(this).attr('id').split('_');
var _totalitem_col = _totalitem_arr[1];
if(_inputitem_col == _totalitem_col){
sum_item = sum_item + inputitem_val;
_totalitem.val(sum_item);
}
});
});
/*END SUM SCRIPT*/
});
My current script give wrong value of total item. It seems to adding the SUM of different column into the formula. Any help and suggestion is much appreciated
Think about the flow of this code.
Your outermost function executes when the user finishes a key press (keyup event) on any input element on your page that has class "input item". So far, so good.
You initialize the sum to 0 and then you call
$('.inputitem').each(function(i){
This call means that for every element on the page that has class "input item", you will run the entire script inside the inner function. So for the first inputitem (perhaps the one in the top left, perhaps not) we get the value 1.0 in inputitem_val.
Here's where the trouble really starts. Next you call the each function for all of your total cells. But this is a nested call. So you are doing that inner-most function anew for each of the 9 (or however many) cells of your outer each loop. Here's a fix un-nests the functions:
$('.inputitem').on('keyup', function(){
var _inputitem = $(this);
var _inputitem_arr = $(this).attr('id').split('_');
var _inputitem_col = _inputitem_arr[0];
//whichever column this cell is in is the column we need to re-sum
var active_col = _inputitem_col
/*SUM SCRIPT*/
var sum_item = 0;
//iterate through each input cell
$('.inputitem').each(function(i){
var _inputitem = $(this);
var _inputitem_arr = $(this).attr('id').split('_');
var _inputitem_col = _inputitem_arr[0];
//check whether the current input cell is in the active column
if(_inputitem_col == active_col){
//if so, add it to our partial sum
var inputitem_val = parseFloat($(this).val().replace(',', ''));
sum_item += inputitem_val;
}
});
//find and update only the relavent sum cell
$('.totalitem').each(function(i){
var _totalitem = $(this);
var _totalitem_arr = $(this).attr('id').split('_');
var _totalitem_col = _totalitem_arr[1];
if(_inputitem_col == _totalitem_col){
_totalitem.val(sum_item);
}
});
/*END SUM SCRIPT*/
});
$('.inputitem').on('keyup', function(){
var _inputitem_arr = $(this).attr('id').split('_');
var _inputitem_col = _inputitem_arr[0];
var $totlaSelector = '#total_' + _inputitem_col;
var $ColTotal = 0;
$('[id^="'+_inputitem_col+'"]').each(function(i){
var $thisVal = 0;
if($(this).val() != ''){
$thisVal = parseInt($(this).val());
}
$ColTotal = $ColTotal + $thisVal;
});
$($totlaSelector).val($ColTotal);
});
I have updated your jQuery on keyup event.
I have a display of some data through jquery. now I want to put some textbox in front of data but it doesn't show the 'n' numbers of textbox only single box display. see my code
$("#jobcard").html(data[i]['jobcard_id']);
var qty = data[i]['jobcard_material_qty'].split(",");
for(var j =0; j<qty.length; j++){ //qty.length =5
$("#issue").html('<input type="text" name="qty_issue_"'+j+ '><br>');
}
i alert(qty.length) //got ans 5
so i just need input 5 input boxes but i got sinlge box only.
You can use the JQuery method append() for this!
var qty = {
length: 5
};
var data = [{
jobcard_id: 1
}];
var i=0;
$("#jobcard").html(data[i]['jobcard_id']);
for (var j = 0; j < qty.length; j++) { //qty.length =5
$("#issue").append('<input type="text" name="qty_issue_"' + j + '><br>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="jobcard"></div>
<div id="issue"></div>
Can anyone help?
I am wanting to allocate the result that is displayed in a div with id = result to a variable in which I can use to put into a mysql database field upon selection of a dropdown box list which is allocated a price.
This is what I have at moment.
<script>
$("#country").on("change", function(){
var selected = $(this).val();
$("#results").html("Estimated Postage: " + selected);
})
</script>
<div id='result'>Abracadabra</div>
<script>
var a = $('#result').attr('id'); // to extract the id of this div
var b = $('#result').html(); // to extract the html content of this div
var c = $('#result').text(); // to extract only the text from this div
console.log('a = ', a);
console.log('b = ', b);
console.log('c = ', c);
</script>
If the div is dynamically generated after the page loads completely, use a static parent in selector, like this:
$('body #result').html();
consider if $_SESSION['PRICE'] Consist a value="100 50 10" as string so i want to check 3 checkbox consist of value 100 , 50 and 10
$( document ).ready(function() {
var price=<?php echo $_SESSION['PRICE']; ?>;// retrieve sessionvariable value and assign to javascript
var priceArray=price.split(" ");
var i;
for(i=0;i<count(priceArray);i++){
$(":checkbox[value=priceArray[i]").attr("checked","true");
}
});
If you want it then surrount it with quotes
var price= "<?php echo $_SESSION['PRICE']; ?>";// retrieve sessionvariable value and assign to javascript
So JS code will be like
price = "100 50 10";
var priceArray=price.split(" ");
alert(priceArray[1]);
Your JsFiddle
I have a javascript function that create Checkbox by drop_down's selection. When I clicked the add button , system will create checkbox(es) with values.
function addElement()
{
var e= document.getElementById('top-addon');
var tops = e.options[e.selectedIndex].text;
var tops_value=e.options[e.selectedIndex].value;
// alert(tops_value);
var ni = document.getElementById('myDiv');
num += 1;
//var newdiv = document.createElement('div');
var countedName = num;
// newdiv.setAttribute('id',Name);
var x = document.createElement("input");
x.type = "checkbox";
x.name = "toppings[]";
x.setAttribute('id',countedName);
x.checked = true;
x.value = tops_value;
//var inner_text = tops + '<a href=\'#\' onclick=\'removeElement('+countedName+')\'> [x] </a>';
//var text= document.createTextNode(inner_text);
x.innerHTML=tops;
ni.appendChild(x);
//ni.appendChild(inner_text);
}
I had make some screenshots to explain you my current problems. Please check my screenshot for more clear picture.
This is like this, for an item like ice-cream, customers can add many toppings example , nuts, jelly etc.
Then I have another problem.Created checkbox's are not shown . I can only see square box(es)
Please see my second attached picture below.Seems okay to me.But I can't see any description text(s).
What I am trying to achieve is
to show selection
Calculate the items,they will be generated with checked value. I have already achieve the code to remove the generated toppings. So I want to calculate the total value of generated items and they should be changeable.
Example. if remove a generated item. Total toppings should decrease.Thanks for your help in advance.
For your first problem: In order to display text for a checkbox, you should put checkbox inside label. Here is modified code for you
function addElement()
{
var e= document.getElementById('top-addon');
var tops = e.options[e.selectedIndex].text;
var tops_value=e.options[e.selectedIndex].value;
// alert(tops_value);
var ni = document.getElementById('myDiv');
num += 1;
//var newdiv = document.createElement('div');
var countedName = num;
// newdiv.setAttribute('id',Name);
var x = document.createElement("input");
x.type = "checkbox";
x.name = "toppings[]";
x.setAttribute('id',countedName);
x.checked = true;
x.value = tops_value;
//x.innerHTML=tops; We don't need to set text to checkbox.
/* These lines are added */
var label = document.createElement("label");
label.appendChild(x);
var span = document.createElement("span");
span.innerText = tops;
label.appendChild(span);
/* End of added lines */
// Beware that we are adding label to div, instead of checkbox.
ni.appendChild(label);
}
For your second problem: To calculate grand total of cart, you need to define a function (let's say calculateTotal) that implements sort of this pseudocode:
function calculateTotal
begin
get all checkboxes under myDiv
for each selected check box
begin
get check box id
get substring of id, after comma (",")
add substring (price) to total
end
end
This method should be triggered whenever user clicks add item button, remove item button, and checkboxs' onChange events fire.
I guess this answer should address your issue with checkboxes text: https://stackoverflow.com/a/10143276/1492792