Add simpleCart Items to Form as Input Values - javascript

I need to add the items from simpleCart to a form. I can't find any built-in functions that will do this so I'm trying to create my own script.
On the checkout page simpleCart adds the items like this:
<div class="simpleCart_items">
<table>
<thead>
<tr class="headerRow">
<th class="item-name">Name</th>
<th class="item-price">Price</th>
<th class="item-size">Size</th>
<th class="item-color">Color</th>
<th class="item-decrement"></th>
<th class="item-quantity">Qty</th>
<th class="item-increment"></th>
<th class="item-total">SubTotal</th>
<th class="item-remove"></th>
</tr>
</thead>
<tbody>
<tr class="itemRow row-0 odd" id="cartItem_SCI-1">
<td class="item-name">Deer Shirt</td>
<td class="item-price">฿400.00</td>
<td class="item-size">Small</td>
<td class="item-color">Blue</td>
<td class="item-decrement">-</td>
<td class="item-quantity">2</td>
<td class="item-increment">+</td>
<td class="item-total">฿800.00</td>
<td class="item-remove">Remove</td>
</tr>
<tr class="itemRow row-1 even" id="cartItem_SCI-2">
<td class="item-name">Deer Shirt</td>
<td class="item-price">฿400.00</td>
<td class="item-size">Medium</td>
<td class="item-color">Clay</td>
<td class="item-decrement">-</td>
<td class="item-quantity">1</td>
<td class="item-increment">+</td>
<td class="item-total">฿400.00</td>
<td class="item-remove">Remove</td>
</tr>
</tbody>
</table>
</div>
On that same checkout page I have a form where the customer adds their name, mailing address, etc. I'd like to add each item above as an input to the form like this:
<input type="hidden" name="Item 1" value="Deer Shirt">
...
It seemed using jQuery's .each would work, but it's not producing the desired result.
This is what I've got now:
simpleCart.ready(function() {
$('.itemRow').each(function(){
$('form').append('<input type="hidden" name="' + $('.itemRow').attr('id') + '" value="' + $('.item-name').text() + '">');
$('form').append('<input type="hidden" name="' + $('.itemRow').attr('id') + '" value="' + $('.item-color').text() + '">');
});
});
Expected output:
<input type="hidden" name="cartItem_SCI-1" value="Deer Shirt">
<input type="hidden" name="cartItem_SCI-1" value="Blue">
<input type="hidden" name="cartItem_SCI-2" value="Deer Shirt">
<input type="hidden" name="cartItem_SCI-2" value="Clay">
Actual output:
<input type="hidden" name="cartItem_SCI-1" value="NameDeer ShirtDeer Shirt">
<input type="hidden" name="cartItem_SCI-1" value="ColorBlueClay">
<input type="hidden" name="cartItem_SCI-1" value="NameDeer ShirtDeer Shirt">
<input type="hidden" name="cartItem_SCI-1" value="ColorBlueClay">
Maybe .each isn't the best way. Any ideas on how to get the expected output?

First error is here
$('.itemRow').each(function(){
$('form').append('<input type="hidden" name="' + $(this).attr('id') + '" value="' + $(this).find('.item-name').text() + '">');
$('form').append('<input type="hidden" name="' + $(this).attr('id') + '" value="' + $(this).find('.item-color').text() + '">');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="simpleCart_items">
<table>
<thead>
<tr class="headerRow">
<th class="item-name">Name</th>
<th class="item-price">Price</th>
<th class="item-size">Size</th>
<th class="item-color">Color</th>
<th class="item-decrement"></th>
<th class="item-quantity">Qty</th>
<th class="item-increment"></th>
<th class="item-total">SubTotal</th>
<th class="item-remove"></th>
</tr>
</thead>
<tbody>
<tr class="itemRow row-0 odd" id="cartItem_SCI-1">
<td class="item-name">Deer Shirt</td>
<td class="item-price">฿400.00</td>
<td class="item-size">Small</td>
<td class="item-color">Blue</td>
<td class="item-decrement">-</td>
<td class="item-quantity">2</td>
<td class="item-increment">+</td>
<td class="item-total">฿800.00</td>
<td class="item-remove">Remove</td>
</tr>
<tr class="itemRow row-1 even" id="cartItem_SCI-2">
<td class="item-name">Deer Shirt</td>
<td class="item-price">฿400.00</td>
<td class="item-size">Medium</td>
<td class="item-color">Clay</td>
<td class="item-decrement">-</td>
<td class="item-quantity">1</td>
<td class="item-increment">+</td>
<td class="item-total">฿400.00</td>
<td class="item-remove">Remove</td>
</tr>
</tbody>
</table>
</div>
<form></form>
And as for me same hidden input name for color and name is error

Pavlo's answer above is correct per the way I asked the original question but due to xDreamCoding's comment I did some digging and found that simpleCart has it's own .each operator. In the end I'm able to get what I need with this:
simpleCart.each(function( item , x ){
$('form').append('<input type="hidden" name="' + item.get('id') + ' Name" value="' + item.get('name') + '">');
$('form').append('<input type="hidden" name="' + item.get('id') + ' Color" value="' + item.get('color') + '">');
});

Related

using onkeyup inside of the append (input) in javascript

var tvalue = [];
function add_purchase(value){
if (value in tvalue) {
return 0;
}else{
tvalue.push(value);
}
var obj = document.getElementById('item');
var item = obj.options[obj.selectedIndex].text;
$('#show_item').append(' <tr class="warning" >'+
' <td class="title-text">'+
item+
' </td> '+
' <td class="title-text">'+
' <input type="hidden" value="'+value+'" name="item_id[]">'+
' </td>'+
' <td class="title-text">'+
' <input type="text" id="txt2" name="quantity[]">'+
' </td>'+
' <td class="hidden-xs"> '+
' <input type="text" name="price[]">'+
'</td>'+
' <td class="hidden-xs" > '+
'<p> the total of every caculate must be here </p>'+
' </td>'+
' </tr>');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label class="control-label col-md-3">Items
<span class="required"> * </span>
</label>
<div class="col-md-5">
<select class="form-control select2me" id="item"
onchange="add_purchase(this.value)">
<option value=""></option>
#foreach($items as $item)
<option value="{{ $item->id }}"> {{ $item->name }} </option>
#endforeach
</select>
</select>
</div>
</div>
<hr>
<table class="table table-striped table-hover">
<thead>
<tr class="active">
<th colspan="2" class="hidden-xs"> Material </th>
<th class="hidden-xs" style="width:10%">Quantity </th>
<th class="hidden-xs" style="width:10%">Price</th>
<th class="hidden-xs" style="width:10%">Total</th>
</tr>
</thead>
<tbody id="show_item">
</tbody>
<tfoot>
<tr class="success">
<th colspan="2">Total</th>
<th class="ltr" style="text-align:center"></th>
<th class="ltr" style="text-align:left">($)</th>
<th class="ltr" style="text-align:center"></th>
</tr>
</tfoot>
</table>
there is a dropdown for items that we can select as many items as want, and every item has price, quantity and total. What I want here is to make a function that makes (price * quantity) real time and put the result in total, but don't know how to write onkeyup or any method like onkeyup in the append.
Thanks in advance for your help.
Try changing this.value to $(this).val()

Get Current Selected Checkbox value using jQuery

I need to get current selected value from selected check box from table.Below the code i am using for get selected value from checkbox.But It is getting all the selected value from table.I need only selected table row value.
$.each($('input[type="checkbox"]:checked').closest("td").next("td"), function() {
values.push($(this).text().trim())
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="DeviceTable" class="table table-bordered">
<thead>
<tr class="info">
<th style="width: 10px;">
<input type="checkbox" id="check_selectall-custom" onclick="selectAllCustom(this)" />SA</th>
<th>Device</th>
<th> Type</th>
<th> Model</th>
<th> Status</th>
</tr>
</thead>
<tbody class="parameter_table">
<tr id="tr_device_id1">
<td>
<input type="checkbox" name="checkBox[]" onclick="DeviceClickedBox()">
</td>
<td id="macadd" style="word-break:break-all;">
Mac1
</td>
<td style="word-break:break-all;">
Dev 1
</td>
<td style="word-break:break-all;">
Model 1
</td>
<td class="Selected_Device" id="Selected_Device">
<b id="Selected_Device" style="float: right;"></b>
</td>
</tr>
<tr id="tr_device_id2">
<td>
<input type="checkbox" name="checkBox[]" onclick="DeviceClickedBox()">
</td>
<td id="macadd" style="word-break:break-all;">
Mac 2
</td>
<td style="word-break:break-all;">
Parm 2
</td>
<td style="word-break:break-all;">
Model 2
</td>
<td class="Selected_Device" id="Selected_Device">
<b id="Selected_Device" style="float: right;"></b>
</td>
</tr>
</tbody>
</table>
Give your TDs a class instead of ID
I do not know what you want to click, but here I do it on click of the checkbox
$(function() { // assuming jquery is loaded, execute on page load
$("#check_selectall-custom").on("click", function() {
var checked = this.checked;
$("input[type=checkbox]").not(this).prop("checked",checked);
});
$("#getval").on("click", function() {
var values = $("input[type=checkbox]:checked").not(this).map(function() {
return $(this).closest("tr").find(".macadd").text().trim();
}).get();
$("#res").html(values.join("<br/>"))
});
});
#tr_device_id1 td {
word-break: break-all
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="DeviceTable" class="table table-bordered">
<thead>
<tr class="info">
<th style="width: 10px;">
<label><input type="checkbox" id="check_selectall-custom" />SA</label>
</th>
<th>Device</th>
<th> Type</th>
<th> Model</th>
<th> Status</th>
</tr>
</thead>
<tbody class="parameter_table">
<tr id="tr_device_id1">
<td>
<input type="checkbox" name="checkBox[]">
</td>
<td class="macadd">
Mac 1
</td>
<td class="device">
Dev 1
</td>
<td class="model">
Model 1
</td>
<td class="Selected_Device">
</td>
</tr>
<tr id="tr_device_id2">
<td>
<input type="checkbox" name="checkBox[]">
</td>
<td class="macadd">
Mac 2
</td>
<td class="device">
Dev 2
</td>
<td class="model">
Model 2
</td>
<td class="Selected_Device">
</td>
</tr>
</tbody>
</table>
<button type="button" id="getval">Show checked</button>
<span id="res"></span>
var TotalChkBx;
$("input:checkbox").on("click", function() {
var n = $("input:checkbox").index(this);
$('#detail').append("Column 1" + $("table#DeviceTable tbody tr:eq(" + n + ") td:eq(1) ").text() + '<br/>');
$('#detail').append("Column 2" + $("table#DeviceTable tbody tr:eq(" + n + ") td:eq(2) ").text() + '<br/>');
$('#detail').append("Column 3" + $("table#DeviceTable tbody tr:eq(" + n + ") td:eq(3) ").text() + '<br/>');
$('#detail').append("Column 4" + $("table#DeviceTable tbody tr:eq(" + n + ") td:eq(4) ").text() + '<br/>');
});
function CheckAll(CheckBox) {
$('#detail').html("");
var TargetBaseControl = document.getElementById("DeviceTable"); // objRef.parentNode.parentNode.parentNode;
var TargetChildControl = "check";
//var Check_TEXT = "CHECK_CheckBox"
var Inputs = TargetBaseControl.getElementsByTagName("input");
// var Spans = TargetBaseControl.getElementsByTagName("span");
for (var n = 0; n < Inputs.length; ++n) {
if ((Inputs[n].type === 'checkbox')) //
{
Inputs[n].Checked = CheckBox.checked;
$("#" + Inputs[n].id).attr("Checked", CheckBox.checked);
$('#detail').append("Column 1" + $("table#DeviceTable tbody tr:eq(" + n + ") td:eq(1) ").text() + '<br/>');
$('#detail').append("Column 2" + $("table#DeviceTable tbody tr:eq(" + n + ") td:eq(2) ").text() + '<br/>');
$('#detail').append("Column 3" + $("table#DeviceTable tbody tr:eq(" + n + ") td:eq(3) ").text() + '<br/>');
$('#detail').append("Column 4" + $("table#DeviceTable tbody tr:eq(" + n + ") td:eq(4) ").text() + '<br/>');
}
// else { $('#detail').html("");}
}
Counter = CheckBox.checked ? TotalChkBx : 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="DeviceTable" class="table table-bordered">
<thead>
<tr class="info">
<th style="width: 10px;">
<input type="checkbox" id="check1" name="checkBox" id="check_selectall-custom" onclick="CheckAll(this)" />SA</th>
<th>Device</th>
<th> Type</th>
<th> Model</th>
<th> Status</th>
</tr>
</thead>
<tbody class="parameter_table">
<tr id="tr_device_id1">
<td>
<input type="checkbox" id="check2" name="checkBox">
</td>
<td id="macadd" style="word-break:break-all;">
Mac1
</td>
<td style="word-break:break-all;">
Dev 1
</td>
<td style="word-break:break-all;">
Model 1
</td>
<td class="Selected_Device" id="Selected_Device">
<b id="Selected_Device" style="float: right;"></b>
</td>
</tr>
<tr id="tr_device_id2">
<td>
<input type="checkbox" id="check3" name="checkBox">
</td>
<td id="macadd" style="word-break:break-all;">
Mac 2
</td>
<td style="word-break:break-all;">
Parm 2
</td>
<td style="word-break:break-all;">
Model 2
</td>
<td class="Selected_Device" id="Selected_Device">
<b id="Selected_Device" style="float: right;"></b>
</td>
</tr>
</tbody>
</table>
<div id="detail"></div>

Getting the value from input field within html TD tag using javascript

I have this current script in calculating the columns average but I
can't get the value from input. The code only accesses what's in the
td.
Can anyone tell me why the result is NaN?
I had tried putting the value in td and it's ok but I need the value
inside the input type. How do I access the value in the input?
This table is an update form that is why it is an input field.
Also how do I add a keyup event in all the input fields?
Sample output
Subject | Term1 | Term2 | Term3 | Term4
Math 81 87 81 80
Science 89 83 81 80
Average | 85 | 85 | 81 | 80
HTML
<div class="table table-responsive table-bordered">
<table class="table">
<thead>
<th colspan="3">Subjects</th>
<th colspan="2">First Grading</th>
<th colspan="2">Second Grading</th>
<th colspan="2">Third Grading</th>
<th colspan="2">Fourth Grading</th>
</thead>
<tbody>
#foreach($update_card['AllGrade'] as $subject) {!! Form::hidden('grade_id[]',$subject['grade_id']) !!}
<tr>
<td colspan="3">{!! $subject->subject !!}</td>
<td colspan="2"><input type="text" name="term_1[]" value="{!! $subject->term_1 !!}" class="form-control number-only"></td>
<td colspan="2"><input type="text" name="term_2[]" value="{!! $subject->term_2 !!}" class="form-control number-only"></td>
<td colspan="2"><input type="text" name="term_3[]" value="{!! $subject->term_3 !!}" class="form-control number-only"></td>
<td colspan="2"><input type="text" name="term_4[]" value="{!! $subject->term_4 !!}" class="form-control number-only"></td>
</tr>
#endforeach
<tr id="average">
<td colspan="2">Average</td>
<td colspan="2">0</td>
<td colspan="2">0</td>
<td colspan="2">0</td>
<td colspan="2">0</td>
</tr>
</tbody>
</table>
Script
$(document).ready(function(){
$("#average td").each(function(k,v){
debugger;
if(k>0){
$sum=0;
$row = $(this).closest("table").find("tr");
$($row).each(function(key,val){
if(key>0 && key<$row.length-1){
$sum+=parseInt($($(this).find("td")[k]).text());
}
})
$(this).text($sum/($row.length-2));
}
})
});
A simplified version of your average computation:
$('.table :input').on('input', function(e) {
var cellIdx = $(this).closest('td').index() + 1;
var currAvgCell = $("#average td:nth-child(" + cellIdx + ")").get(0);
var cellsInput = $(this).closest("table tbody").find("tr:not(:last) td:nth-child(" + cellIdx + ") :input");
// reset value
currAvgCell.textContent = '0';
cellsInput.each(function (key, r) {
currAvgCell.textContent = +r.value + +currAvgCell.textContent;
});
currAvgCell.textContent = +currAvgCell.textContent / +cellsInput.length;
});
// comput at dom ready each average
$('.table tbody tr:first :input').trigger('input');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="table table-responsive table-bordered">
<table class="table">
<thead>
<th colspan="3">Subjects</th>
<th colspan="2">First Grading</th>
<th colspan="2">Second Grading</th>
<th colspan="2">Third Grading</th>
<th colspan="2">Fourth Grading</th>
</thead>
<tbody>
<tr>
<td colspan="3">Math</td>
<td colspan="2"><input type="text" name="term_1[]" value="81"
class="form-control number-only"></td>
<td colspan="2"><input type="text" name="term_2[]" value="87"
class="form-control number-only"></td>
<td colspan="2"><input type="text" name="term_3[]" value="81"
class="form-control number-only"></td>
<td colspan="2"><input type="text" name="term_4[]" value="80"
class="form-control number-only"></td>
</tr>
<tr>
<td colspan="3">Science</td>
<td colspan="2"><input type="text" name="term_1[]" value="89"
class="form-control number-only"></td>
<td colspan="2"><input type="text" name="term_2[]" value="83"
class="form-control number-only"></td>
<td colspan="2"><input type="text" name="term_3[]" value="81"
class="form-control number-only"></td>
<td colspan="2"><input type="text" name="term_4[]" value="80"
class="form-control number-only"></td>
</tr>
<tr id="average">
<td colspan="3">Average</td>
<td colspan="2">0</td>
<td colspan="2">0</td>
<td colspan="2">0</td>
<td colspan="2">0</td>
</tr>
</tbody>
</table>
</div>
In your code, $($(this).find("td")[k]).text() gets text value of the table cell. In order to get value of the input inside, you'd need to write $(this).find("td").eq(k).find('input').val().
Also, you can add global events to elements, like so:
$('table').on('keyup', 'td input', callback)
It's gonna call the event on every input inside table td, even if it was created dynamically.

Add a row to my table using Javascript and MVC

I have a table like this on my MVC view
<table class="PBHEP table table-bordered">
<thead>
<tr>
<th style="text-align: center">Compute PBHEP Offsets</th>
</tr>
</thead>
<tbody>
<tr>
<th style="text-align: center">Present Conditions</th>
</tr>
</tbody>
</table>
<table class="PDHEPparams table table-bordered">
<tbody>
<tr>
<th></th>
<th>Township</th>
<th>Range</th>
<th>Section</th>
<th>Crop</th>
<th>Acres</th>
</tr>
<tr id="rowtoadd">
<td style =" text-align:center">
<input type="button" class="btn btn-small btn-primary" value="+" onclick="addrow"></td>
<td style =" text-align:center">
<input class="input-small" type="text" placeholder="Township"></td>
<td style =" text-align:center">
<input class="input-small" type="text" placeholder="Range"></td>
<td style =" text-align:center">
<input class="input-small" type="text" placeholder="Section"></td>
<td style =" text-align:center">
<select></select></td>
<td style =" text-align:center">
<input class="input-small" type="text" placeholder="Acres"></td>
</tr>
</tbody>
</table>
How do I add a new row to this table on the button click ? what should be my javascript function for the button onclick.
Here is the general idea of it.
$('.btn').on('click', function() {
var township = $('.input-small').eq(0).val();
var range = $('.input-small').eq(1).val();
var section = $('.input-small').eq(2).val();
var acres = $('.input-small').eq(3).val();
$('.PDHEPparams tbody').append("<tr><td>" + township + "</td><td>" + range + "</td><td>" + section + "</td><td>" + acres + "</td></tr>");
});
Here is a rough fiddle.

JavaScript: How can i populate table rows with the values in an array

<table border="0" cellspacing="2" cellpadding="2" width="99%" id="subAccTable">
<tr>
<td colspan="10">
<h2 align="left" class="pagetitle">Sub Accounts</h2>
</td>
</tr>
<tr>
<th width="10%" class="heading" align="center"><bean:message key="prompt.editVtierAttribute.action" /></th>
<th align="center" class="heading"><bean:message key="report8.header.account" /></th>
<th align="center" class="heading"><bean:message key="report8.header.homeDir" /></th>
<th align="center" class="heading"><bean:message key="report8.header.primaryGroup" /></th>
<th align="center" class="heading"><bean:message key="report8.header.addToGroup" /></th>
</tr>
<tr style="" class="<%=className%>">
<input type="hidden" name="vtierId" value="<%=vtierId%>" />
<td align="center" valign="bottom" class="<%=className%>">
<img name="subAccId" id="<%=subAccountUtil.getId().get(i)%>" onclick="deleteTableRow(this);"
src="images/trashcan.gif" title="Delete SubAccount" border="0" class="clientActions" />
</td>
<td align="center" valign="bottom" class="<%=className%>">
<input type="text" name="subAcc" value="<%= (String)subAccountUtil.getSubAccountName().get(i) %>"
onchange="updateSubAccount(this);" />
</td>
<td align="center" valign="bottom" class="<%=className%>">
<input type="text" name="subHomeDir" value="<%= (String)subAccountUtil.getSubAccountHomeDir().get(i) %>"
onchange="updateSubAccount(this);" />
</td>
<td align="center" valign="bottom" class="<%=className%>">
<input type="text" name="subPriGroup" value="<%= (String)subAccountUtil.getSubAccountPrimaryGroup().get(i) %>"
onchange="updateSubAccount(this);" />
</td>
<td align="center" valign="bottom" class="<%=className%>"> </td>
<td align="center" valign="bottom" class="<%=className%>"> </td>
</tr>
</table>
Now i want to populate the table rows here with the values in an array objArr which contains values like
0)1234, ~, tedtds, tedtds etc.
How can i populate my table columns (text boxes) with the values in this array ?
You can build a string of html with a while or for all statement and then set the contents of a div with that html.
var table1 = "<table>"
var table3 = "</table>"
for (x in array1)
{
table2 = table2 + "<tr><td>" +array1[x] + "</td></tr>"
}
var table4 = table1 + table2 + table3
var mydiv = document.getElementById('mydiv1')
mydiv1.innerHTML = table4
I'd suggest you use one of the existing templating frameworks rather than trying to reinvent the wheel...
jsrender would work, though I've found knockout to be quicker and easier...
http://github.com/BorisMoore/jsrender
http://knockoutjs.com

Categories