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
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 quick question for you guys here. I was handed a set of lead generation pages and asked to get them up and running. The forms are great, expect for one small issue... they use the jQuery below to allow users to submit multiple instances of a data set by clicking an "Add another item" button. The problem is that the duplicated items are duplicated EXACTLY. Same name, id, etc. Obviously, this doesn't work when attempting to process the data via PHP, as only the first set is used.
I'm still learning jQuery, so I was hoping that someone could point me in the right direction for how to modify the plugin below to assign each duplicated field an incremental integer on the end of the ID and name assigned. So, the fields in each dataset are Role, Description, Age. Each additional dataset will use the ID & name syntax of fieldname#, where # represents numbers increasing by 1.
Thanks in advance for any advice!
/** https://github.com/ReallyGood/jQuery.duplicate */
$.duplicate = function(){
var body = $('body');
body.off('duplicate');
var templates = {};
var settings = {};
var init = function(){
$('[data-duplicate]').each(function(){
var name = $(this).data('duplicate');
var template = $('<div>').html( $(this).clone(true) ).html();
var options = {};
var min = +$(this).data('duplicate-min');
options.minimum = isNaN(min) ? 1 : min;
options.maximum = +$(this).data('duplicate-max') || Infinity;
options.parent = $(this).parent();
settings[name] = options;
templates[name] = template;
});
body.on('click.duplicate', '[data-duplicate-add]', add);
body.on('click.duplicate', '[data-duplicate-remove]', remove);
};
function add(){
var targetName = $(this).data('duplicate-add');
var selector = $('[data-duplicate=' + targetName + ']');
var target = $(selector).last();
if(!target.length) target = $(settings[targetName].parent);
var newElement = $(templates[targetName]).clone(true);
if($(selector).length >= settings[targetName].maximum) {
$(this).trigger('duplicate.error');
return;
}
target.after(newElement);
$(this).trigger('duplicate.add');
}
function remove(){
var targetName = $(this).data('duplicate-remove');
var selector = '[data-duplicate=' + targetName + ']';
var target = $(this).closest(selector);
if(!target.length) target = $(this).siblings(selector).eq(0);
if(!target.length) target = $(selector).last();
if($(selector).length <= settings[targetName].minimum) {
$(this).trigger('duplicate.error');
return;
}
target.remove();
$(this).trigger('duplicate.remove');
}
$(init);
};
$.duplicate();
Add [] to the end of the NAME attribute of the input field so for example:
<input type ="text" name="name[]"
This way your $POST['name'] will hold an array of strings. For that element. It will be an array with keys that are numbers from 0 to however many items it holds.
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();
How can I find the values of two different select dropdowns and add the two values together upon selection(not submition) if they have the same "name" and then place the sum value into an array using jquery?
EDIT
For a little clarification, I am dynamically creating the list which needs to look like this
BOX A, BOX A, TITLE
BOX B, BOX B, TITLE
BOX C, BOX C, TITLE
etc...
Every list will be different and rarely the same. Next time the boxes could be D E or F. When selected(currently .onchange) All corresponding boxes need to be added together then pushed into a seperate array if the value is not empty...
var s=[sumOfAs, sumOfBs, sumOfCs];
I hope this helps...
Also the back end is PHP
THANKS!
EDIT
Here is the jquery code that pushes the first set of values into an array...
$("#selectionBox select").change(function(){
s = [];
$("#selectionBox select option:selected").each(function(){
$("#selected_songs").text('');
var v = $(this).val();
if(v != ''){
s.push(v);
}
if(s != ""){
$('#selectionButton').show();
var mw = $("#list_month_New").val();
var dw = $("#list_day_New").val();
var yw = $("#list_year_New").val();
var t = $("#listTitle").val();
if(mw == "" || dw == "" || yw == ""){
$("#songListWarning").show();
}else{
$("#songListWarning").hide();
}
}else{
$("#list_month_New").val();
$("#list_day_New").val();
$("#list_year_New").val();
$("#listTitle").val();
$('#selectionButton').hide();
}
});
s.sort();
jQuery.each(s, function(){
O = "";
O = this+"<br />";
str = /&(.+)/.exec(O)[1];
num = O.replace(/\-.*/, '');
fullString = '<span style="color:black">'+num+'</span> - '+str;
$("#selected_songs").append(fullString);
});
I just need to figure out how to add another value to the initial value?
var runningTotals = {};
$('select').each(function() {
var $this = $(this);
var name = $this.attr("name");
var val = runningTotals[name];
if (!val) {
val = 0;
}
val += +($this.val());
runningTotals[name] = val;
});
Please refer to this fiddle
EDIT
Edited to update for the change edit you made
I have a HTML table with text in the cells like so:
<tr><td>HELLO</td></tr>
I then have a text area like so:
<input type="text" id="txt_message" name="txt_message"
I want to make it so that when you click inside the table cell, the data (in this case the word 'HELLO') is inserted into the text area (so the user does not have to type it).
I dont know if this is possible, but I am guessing it is and it is 'probably' something in JavaScript.
If anybody has any advice that would be great, Thank you :)
[Working demo]
var textbox = document.getElementById('textbox');
var table = document.getElementById('table');
// add one event handler to the table
table.onclick = function (e) {
// normalize event
e = e || window.event;
// find out which element was clicked
var el = e.target || e.srcElement;
// check if it's a table cell
if (el.nodeName.toUpperCase() == "TD") {
// append it's content to the textbox
textbox.value += (el.textContent || el.innerText);
}
}
Note: all the conditional assignments with || are for cross-browser compatibility.
Here is Working demo using jquery.
To get the value, use innerhtml and a span, more here: http://www.vbforums.com/showthread.php?t=339864
To update the textarea you should be able to do something like: document.getElementById ("text_message").value = x;
a simple jQuery snippet, assuming you have 1 textarea and multiple td's to click over
(function() {
var ta = $('#txt_message');
$('td').bind('click.addtextarea', function() {
var text = $(this).html();
ta.val([ta.val(), text].join(' ')); /* this add words */
/* ta.val(text); this print one word */
});
})()