how to split php session variable - php

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

Related

How to SUM each column in this dynamically created table like excel

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.

pass variable into string in symfony and jquery

I want to pass the id into a string but always I get an error
var c = document.getElementById("predefinedMessage");
var id= c.selectedIndex;
var text= "{{ form.predefinedMessage.vars.choices[id].data.message }}";
$('message').val(text);
});
how I can pass the id in the text variable
If the element that you're selecting is a drop down list, I suggest the following code using jQuery as you're already using it:
// Select by the ID predefinedMessage
var dropDown = $("select#predefinedMessage");
// Get the selected index from the dropdown
var selectedIndex = dropDown.find("option:selected").index();
var text = "{{ form.predefinedMessage.vars.choices[" + selectedIndex + "].data.message }}";
$('message').val(text);

Jquery Math, Select Dropdown Value + Text Field

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);

Dynamically Created Checkbox calculation, Not showing properly

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

Total value with JavaScript and PHP

I'm using this form script to automatically calculate totals. Now I need to get that total and add it to a database via PHP and MySQL.
I don't know how to 'name' the totalPrice div, so that I can pass its value to the database.
Edit:
I'm still not getting results in the database. I'm now using $_POST[totalValue] for the field set and totalPrice for the field name.
HTML:
<div id="totalPrice"></div></div>
<input type="hidden" name="totalValue" id="totalValue" />
JavaScript:
$("#vendorform").submit(function(){
var totalValue = document.getElementById('totalValue');
totalValue.value = vendorPrice; //the actual total value
});
function calculateTotal()
{
//Here we get the total price by calling our function
//Each function returns a number so by calling them we add the values they return together
var vendorPrice = getTentPrice() + getElecPrice() + getPropanePrice();
//display the result
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Total Price Vendor $"+vendorPrice;
}
The vendorPrice variable is not available outside the scope of the function calculateTotal. You could make vendorPrice a global variable, but that's a bit of an ugly hack.
Alternatively, you could do something like this:
function calculateTotal()
{
var vendorPrice = getTentPrice() + getElecPrice() + getPropanePrice();
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Total Price Vendor $"+vendorPrice;
return vendorPrice; // <-- ADDED
}
And this:
$("#vendorform").submit(function(){
var totalValue = document.getElementById('totalValue');
totalValue.value = calculateTotal(); // <-- CHANGED
});
This way, you assign the value that is now returned by calculateTotal() to totalValue.value.
By the way: since it looks like you're already using jQuery, you can rewrite your code like this:
// [...]
var divobj = $('#totalPrice');
divobj.css('display', 'block');
divobj.text("Total Price Vendor $"+vendorPrice);
// [...]
var totalValue = $('#totalValue');
totalValue.val(calculateTotal());
This makes it a bit more readable (although that's debatable) and a bit more cross-browser reliant. jQuery has great docs (e.g. the documentation on .val()). If you're going to use jQuery more often I can highly recommend bookmarking the docs and skimming through them.
Using jQuery:
$("#cakeform").submit(function(){
var price = $("#totalPrice").text().replace(/[\s\S]+\$/,"")
$("#cakeForm").append('<input type="hidden" name="estimated_price" value="' + price + '" />')
})
But as #nick-rulez pointed out, is usually not a good idea to save calculated values in a database.
You can set the value to:
<input type="hidden" name="totalValue" id="totalValue" />
Which you have to put inside your <form>...</form>.
When you submit the form you're going to receive input's value.
You can set the value to the hidden field with this sniped:
JS
var totalValue = document.getElementById('totalValue');
totalValue.value = myValue; //myValue is the total
JavaScript:
function calculateTotal()
{
var Price = getTshirtPrice() + getTshirtType() + getTshirtColour() +
getTextColour();
var divobj = document.getElementById('textbox');
divobj.value = "Total Price For the T-shirt: £"+Price;
return Price;
}
HTML:
<div id="totalPrice"><input type="text" id="textbox"></div>
Do that. It works perfectly fine.

Categories