Check if item exists in specific <td> by jquery - javascript

I have items names in drop down and a quantity text box. i am adding item and its quantity to table if quantity is greater then zero,
Now i want to check if item is already present in the table then just sum the quantity
<script>
$(document).ready(function(){
$("#addBtn").click(function(){
var rmnameList = document.getElementById("rname");
var name = rmnameList.options[rmnameList.selectedIndex].text;
var qty = $('#qty').val();
if (qty > 0)
{
var tbody = $('#rTable').children('tbody');
var table = tbody.length ? tbody : $('#rTable');
//Add row
table.append('<tr><td>'+ name + '</td><td>'+ qty +'</td></tr>');
}
});
});
</script>
I am unable to find the respective <td> element to update.
My jquery selector is :
$('#rTable tbody tr td:first-child')
and it returns:
[<td>​BUN​</td>​, <td>​Ketchup​</td>​, <td>​Banana​</td>​]

Use an attribute on the tr to store the rname, and then use it to check whether the element exists
$(document).ready(function() {
$("#addBtn").click(function() {
var name = $('#rname option:selected').text();
var qty = $('#qty').val();
if (qty > 0) {
var tbody = $('#rTable').children('tbody');
var table = tbody.length ? tbody : $('#rTable');
//Add row
var $tr = table.find('tr[data-rname="' + name + '"]');
if ($tr.length) {
$tr.find('td:last-child').text(function(i, t) {
return +t + +qty;
})
} else {
table.append($('<tr><td>' + name + '</td><td>' + qty + '</td></tr>').attr('data-rname', name));
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="rname">
<option></option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<input id="qty" />
<button id="addBtn">Add</button>
<br />
<table id="rTable"></table>

You can use .filter
var target = table.find("tr").filter(function(idx, tr) {
var td = tr.find('td:first-child');
return (td.text() === name);
});
if (target.length > 0) {
// Sum up
} else {
// Create new
}
I'd suggest you use <tr data-name="' + name + '"><td>'+ name + '</td><td>'+ qty +'</td></tr> to create a tr with data-name
Then the filter can be simplified to:
var target = table.find("tr").filter('[data-name="' + name + '"]');

You can use .filter() to check it the item is already present on the table.
var count = $('#rTable td').filter(function() {
return $(this).text().trim() == name;
});
count will be greater that one if the table contains that element.
Also you can use $("#rname option:selected").text(); inorder to get the selected option text.
$("#addBtn").click(function() {
var name = $("#rname option:selected").text();
var qty = parseInt($('#qty').val());
var count = $('#rTable td').filter(function() {
return $(this).text().trim() == name;
});
if (qty > 0 && count == 0) {
var tbody = $('#rTable').children('tbody');
var table = tbody.length ? tbody : $('#rTable');
//Add row
table.append('<tr><td>' + name + '</td><td>' + qty + '</td></tr>');
}
});

Related

how to serialize a form under specific conditions

Taka a look at this fiddle here this is a form where a business user enters the offered services.I sent the data with ajax and by serializing the form.
Click edit and add(plus sign) a service...in the example an input is added where it's name attribute value is of this **form= form[5]...**contrast with this with the form of the name attribute value in the other inputs...only the newly added services have the name attribute like this and the reason for that is to serialize only these...and not the others already present in the DOM/stored in the DB.
And now my problem:
Imagine that the user goes to edit the already registered services(or that he goes to edit them and add a new one)...at this case the already registered services wont'be serialized cause of the form the name attribute value has...(and the reason for this is explained above).
What can I do in this case?Sometimes I must serialize only part of a form and sometimes whole of the form.If all the inputs have name attribute value of form[1....] then along with the newly added input...already registered services will be serialized again.
Thanks for listening.
Code follows(you can see it in the fiddle too)
$('.editservices').click(function() {
//console.log(('.wrapper_servp').length);
originals_ser_input_lgth = $('.services').length;
var originals = [];
$('.show_price')
// fetch only those sections that have a sub-element with the .value
class
.filter((i, e) => $('.value', e).length === 1)
// replace content in remaining elements
.replaceWith(function(i) {
var value = $('.value', this).data('value');
var fieldsetCount = $('#serv').length;
var index = fieldsetCount + i;
return '<div class="show_price"><p id="show_p_msg">Price
visibility</p></div>' + '\
<div class="show_p_inpts">' +
'<input class="price_show"' + (value == 1 ? "checked" : "") + '
type="radio" name="form[' + index + '][price_show]" value="1">yes' +
'<input class="price_show"' + (value == 0 ? "checked" : "") + '
type="radio" name="form[' + index + '][price_show]" value="0">no' +
'</div>'; // HTML to replace the original content with
});
$('#buttons').removeClass('prfbuttons');
$('#saveserv').addClass('hideb');
$('.actionsserv').removeClass('actionsserv');
priceavail = $(".price_show:input").serializeArray();
});
$('#addser').on('click', function() {
$('#saveserv').css('border','2px solid none');
var serviceCount = $('input.services').length + 1;
var serv_inputs = '<div class="wrapper_servp"><div class="serv_contain">\n\
<input placeholder="service" class="services text" name="form[' + serviceCount + '][service]" type="text" size="40"> \n\
<input placeholder="price" class="price text" name="form[' + serviceCount + '][price]" type="text" size="3"></div>';
var p_show = '<div class="show_p">' +
'<p id="show_p_msg">Price visibility;</p>' +
'<span id="err_show_p"></span><br>' +
'</div>';
var inputs = '<div class="show_p_inpts">' +
'<input class="price_show" type="radio" name="form[' + serviceCount + '][price_show]" value="1">yes' +
'<input class="price_show" type="radio" name="form[' + serviceCount + '][price_show]" value="0">no' +
'</div></div>';
$('.wrapper_servp').last().after(serv_inputs + p_show + inputs);
$('#saveserv').removeClass('hideb');
$('#remser').css('display', 'inline');
});
$('#cancelserv').click(function(e) {
e.preventDefault();
//var newinputs = $('.wrapper_servp').length;
//var inp_remv = newinputs - originals_ser_input_lgth;
//$('.wrapper_servp').slice(-inp_remv).remove()
$('.show_p_inpts')
.filter((i, e) => $('.price_show:checked', e).length === 1)
.replaceWith(function(i) {
var value = $('.price_show:checked').attr('value');
return '<span data-value="' + value + '" class="value">' + (value == 1 ? "yes" : "no") + '</span>'
});
});
var groupHasCheckedBox = function() {
return $(this).find('input').filter(function() {
return $(this).prop('checked');
}).length === 0;
},
inputHasValue = function(index) {
return $(this).val() === '';
};
$('#saveserv').click(function(e) {
e.preventDefault();
//from here
var $radioGroups = $('.show_p_inpts');
$('.show_p_inpts').filter(groupHasCheckedBox).closest('div').addClass("error");
$('.services, .price').filter(inputHasValue).addClass("error");
//to here
var $errorInputs = $('input.services').filter((i, e) => !e.value.trim());
if ($errorInputs.length >= 1) {
console.log($errorInputs);
$('#err_message').html('you have to fill in the service'); return;
}
if ($('input.price').filter((i, e) => !e.value.trim()).length >= 1) {
$('#err_message').html('you have to fill in the price'); return;
}
});
var IDs=new Array();
$('body').on('click', '#remser', function(e){
var inputval=$('.services:visible:last').val();
if(inputval!=='')
{r= confirm('Are you sure you want to delete this service?');}
else
{
$('.wrapper_servp:visible:last').remove();
}
switch(r)
{
case true:
IDs.push($('.services:visible:last').data('service'));
$('.wrapper_servp:visible:last').addClass('btypehide');
if($('.serv_contain').length==1)$('#remser').css('display','none');
$('#saveserv').removeClass('hideb').css('border','5px solid red');
//originals.servrem=true;
break;
case false:var i;
for(i=0;i<originals.ser_input_lgth;i++)
{
$('input[name="service'+i+'"]').val(services[i].value);
$('input[name="price'+i+'"]').val(prices[i].value);//εδω set value
}
$('.services').slice(originals.ser_input_lgth).remove();
$('.price').slice(originals.ser_input_lgth).remove();
$('.openservices').addClass('hide').find('.services,.price').prop('readonly', true);
var text='<p class="show_price">Θες να φαίνεται η τιμή;<span data-value="'+ show_pr_val.value +'" class="value">' +(show_pr_val.value==1 ? 'yes':'no') + '</span></p>';
$('.show_p_inpts').remove();
$('.show_price').replaceWith(text);;
break;
}
});
I have an Idea for you. What you can do is when you show the currently existed value in you html instead of giving name attribute just give data-name attribute. I.e
Change this
<input class="services text" data-service="21" size="40" value="hair" type="text" name="service0" readonly="">
To This
<input class="services text" data-service="21" size="40" value="hair" type="text" data-value="hair" data-name="service0" readonly="">
Now when user update this values you can bind an event in jQuery like below.
$(document).ready(function(){
$(".services input").on("change paste keyup", function() {
if($(this).val() === $(this).attr("data-value"))
{
$(this).removeAttr("name");
}else{
$(this).attr("name",$(this).attr("data-name"));
}
});
});
By this way you can give name attribute to only those elements whose values are changed. Now each time you can serialize the whole form and it will only get the value of changed elements.
Don't forget to give unique class to already existed elements so you can bind on change event. Hope its clear to you.

VB.net non MVC RAZOR | Need help, javascript stack procress

I make a shopping website and have 2 menu, when i call page from ajax to show on my content zone (On DIV).
<script>
$(function () {
$("#chicken_tab2").click(function () {
$.ajax({
type: "POST",
url: "/view/Content/Index_cp.vbhtml",
datatype: "html",
success: function (data) {
$("#getcontent").html(data);
}
});
});
});
</script>
My content come to show but it can't use javascipt from _Layout.vbtml.
Then i put Main.js(it's Cart jquery)
<script src="~/view/Cart/main.js"></script>
inside main.js
jQuery(document).ready(function ($) {
//var getnum = $('#getnum').val();
//alert(getnum);
var cartWrapper = $('.cd-cart-container');
//product id - you don't need a counter in your real project but you can use your real product id
var productId = 0;
if( cartWrapper.length > 0 ) {
//store jQuery objects
var cartBody = cartWrapper.find('.body')
var cartList = cartBody.find('ul').eq(0);
var cartTotal = cartWrapper.find('.checkout').find('span');
var cartTrigger = cartWrapper.children('.cd-cart-trigger');
var cartCount = cartTrigger.children('.count')
var addToCartBtn = $('.cd-add-to-cart');
var undo = cartWrapper.find('.undo');
var undoTimeoutId;
var getnum = $('.getnum');
//-----------------------------------------------------------------------------------------------------
//O function Strat
//O function End
//add product to cart
addToCartBtn.on('click', function(event){
event.preventDefault();
addToCart($(this));
});
//open/close cart
cartTrigger.on('click', function(event){
event.preventDefault();
toggleCart();
});
//close cart when clicking on the .cd-cart-container::before (bg layer)
cartWrapper.on('click', function(event){
if( $(event.target).is($(this)) ) toggleCart(true);
});
//delete an item from the cart
cartList.on('click', '.delete-item', function(event){
event.preventDefault();
removeProduct($(event.target).parents('.product'));
});
//update item quantity
cartList.on('change', 'select', function(event){
quickUpdateCart();
});
//reinsert item deleted from the cart
//undo.on('click', 'a', function(event){
// clearInterval(undoTimeoutId);
// event.preventDefault();
// cartList.find('.deleted').addClass('undo-deleted').one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(){
// $(this).off('webkitAnimationEnd oanimationend msAnimationEnd animationend').removeClass('deleted undo-deleted').removeAttr('style');
// quickUpdateCart();
// });
// undo.removeClass('visible');
//});
}
function toggleCart(bool) {
var cartIsOpen = ( typeof bool === 'undefined' ) ? cartWrapper.hasClass('cart-open') : bool;
if( cartIsOpen ) {
cartWrapper.removeClass('cart-open');
//reset undo
clearInterval(undoTimeoutId);
undo.removeClass('visible');
cartList.find('.deleted').remove();
setTimeout(function(){
cartBody.scrollTop(0);
//check if cart empty to hide it
if( Number(cartCount.find('li').eq(0).text()) === 0) cartWrapper.addClass('empty');
}, 500);
} else {
cartWrapper.addClass('cart-open');
}
}
function addToCart(trigger) {
var ids = trigger.data('ids');
var item = trigger.data('item');
var cartIsEmpty = cartWrapper.hasClass('empty');
//update cart product list ****add trigger in ()
addProduct(trigger.data('item'),trigger.data('detail'), trigger.data('productname'), trigger.data('pic'), $('#' + ids + '').val());
//update number of items
updateCartCount(cartIsEmpty);
//update total price
updateCartTotal(1, true);
//show cart
cartWrapper.removeClass('empty');
}
function commaSeparateNumber(val) {
while (/(\d+)(\d{3})/.test(val.toString())) {
val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
}
return val;
}
function addProduct(item, detail, product, pic, QTY) {
//this is just a product placeholder
//you should insert an item with the selected product info
//replace productId, productName, price and url with your real product info
productId = productId + 1;
//var productAdded = $('<li class="product"><div class="product-image"><img src="Cart/product-preview.png" alt="placeholder"></div><div class="product-details"><h3>'+ product +'</h3><span class="price">$'+ 1 +'</span><div class="actions">Delete<div class="quantity"><label for="cd-product-'+ productId +'">Qty</label><span class="select"><select id="cd-product-'+ productId +'" name="quantity"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option></select></span></div></div></div></li>');
var productAdded = $('<li class="product"><div class="product-image"><input type="text" name="item" value="' + item + '" hidden /><input type="text" name="detail" value="' + detail + '" hidden /><img src="/view/images/' + pic + '" alt="placeholder"></div><div class="product-details"><h3>' + product + '</h3><input type="text" name="productname" value="' + product + '" hidden /><input type="text" name="pic" value="/view/images/' + pic + '" hidden /><span class="price">จำนวน</span><span class="price">' + QTY + ' kg.</span><input class="price" type="text" hidden name="QTY" value="' + QTY + '"><div class="actions">ลบ</div></div></li>');
cartList.prepend(productAdded);
}
function removeProduct(product) {
clearInterval(undoTimeoutId);
cartList.find('.deleted').remove();
var topPosition = product.offset().top - cartBody.children('ul').offset().top ,
productQuantity = Number(product.find('.quantity').find('select').val()),
productTotPrice = Number(product.find('.price').text().replace('$', '')) * productQuantity;
product.css('top', topPosition+'px').addClass('deleted');
//update items count + total price
updateCartTotal(1, false);
updateCartCount(true, -productQuantity);
undo.addClass('visible');
//wait 8sec before completely remove the item
undoTimeoutId = setTimeout(function(){
undo.removeClass('visible');
cartList.find('.deleted').remove();
}, 0);
}
function quickUpdateCart() {
var quantity = 0;
var price = 0;
cartList.children('li:not(.deleted)').each(function(){
var singleQuantity = Number($(this).find('select').val());
quantity = quantity + singleQuantity;
price = price + singleQuantity*Number($(this).find('.price').text().replace('$', ''));
});
cartTotal.text(price.toFixed(2));
cartCount.find('li').eq(0).text(quantity);
cartCount.find('li').eq(1).text(quantity+1);
}
function updateCartCount(emptyCart, quantity) {
if( typeof quantity === 'undefined' ) {
var actual = Number(cartCount.find('li').eq(0).text()) + 1 ;
var next = actual + 1;
if( emptyCart ) {
cartCount.find('li').eq(0).text(actual);
cartCount.find('li').eq(1).text(next);
} else {
cartCount.addClass('update-count');
setTimeout(function() {
cartCount.find('li').eq(0).text(actual);
}, 150);
setTimeout(function() {
cartCount.removeClass('update-count');
}, 200);
setTimeout(function() {
cartCount.find('li').eq(1).text(next);
}, 230);
}
} else {
var actual = Number(cartCount.find('li').eq(0).text()) -1 ;
var next = actual + 1;
cartCount.find('li').eq(0).text(actual);
cartCount.find('li').eq(1).text(next);
}
}
function updateCartTotal(price, bool) {
bool ? cartTotal.text( (Number(cartTotal.text()) + Number(price)).toFixed(0) ) : cartTotal.text( (Number(cartTotal.text()) - Number(price)).toFixed(0) );
}
});
and when i change back to this page it stack a function (one time come back to this page it will do 2 time function and more if you come back again) I must to say sorry my English is not good and so thank you for help.

Update totals in a table

I have:
$('#createStockOrder').click(function () {
modal('create-stock-order', {}, function () {
var $modal = $(this);
var submitted = false;
var model = [];
$('.glyphicon-plus').click(function () {
var product_id = $('#productSelect option:selected').text(),
size_id = $('#sizeSelect option:selected').text(),
colour_id = $('#colourSelect option:selected').text(),
quantity = $('#quantity').val();
// Get index of the element where all the fields matches
var index = getObjectIndex(model, product_id, size_id, colour_id);
// If object found in the array
if (index !== false) {
// Update the quantity in the same element
model[index].quantity = quantity;
} else {
// Add the element in the array
model.push({
product_id: product_id,
size_id: size_id,
colour_id: colour_id,
quantity: quantity
});
}
printStock(model);
});
var form = document.getElementById('create_sale');
var $form = $(form);
$form.on('submit', function (e) {
e.preventDefault();
if (!submitted) {
submitted = true;
$('#create_sale .btn-primary').addClass('disabled');
var formData = new FormData(form);
qwest.post(form.action, formData)
.then(function (resp) {
$modal.modal('hide');
})
.catch(function (xhr, response, e) {
var html = '';
$.each(response, function (i, v) {
html += '<p>' + v + '</p>';
});
$('#create_sale .alert').html(html).removeClass('hide');
$('#create_sale .btn-primary').removeClass('disabled');
submitted = false;
});
}
})
}, {width: 1000});
});
// Currently the function is Static, but it can be changed to dynamic
// by using nested loop and a flag to store the match status
function getObjectIndex(arr, product_id, size_id, colour_id) {
// Loop over array to find the matching element/object
for (var i = 0; i < arr.length; i++) {
var obj = arr[i];
if (obj.product_id === product_id && obj.size_id === size_id && obj.colour_id === colour_id) {
// When all key-value matches return the array index
return i;
}
}
// When no match found, return false
return false;
}
function printStock(model) {
var html = '';
var total_row_quantity = 0;
var total_row_value = 0;
$.each(model, function (i1, v1) {
html += '<tr>';
$.each(v1, function (i2, v2) {
html += '<td>' + v2 + '</td>';
$('#product_totals tr').each(function(i3, v3){
var product_code = $('td', v3).eq(0).html();
if(product_code == v2) {
total_row_quantity += parseInt(model[i1].quantity);
total_row_value += parseFloat($('td', v3).eq(2).html()*model[i1].quantity);
$('td', v3).eq(1).html(total_row_quantity);
$('td', v3).eq(3).html(accounting.formatMoney(total_row_value, ''));
} else {
total_row_quantity = 0;
total_row_value = 0;
}
})
});
html += '</tr>';
});
$('#stock_order tbody').html(html);
}
The HTML is:
<tbody id="product_totals">
<tr data-id="1">
<td>JW1501</td>
<td class="code-quantity-total">0</td>
<td>79.00</td>
<td class="code-cost-total">0</td>
</tr>
<tr data-id="2">
<td>JW1502</td>
<td class="code-quantity-total">0</td>
<td>99.00</td>
<td class="code-cost-total">0</td>
</tr>
<tr data-id="3">
<td>JW1501-1</td>
<td class="code-quantity-total">0</td>
<td>20.00</td>
<td class="code-cost-total">0</td>
</tr>
<tr data-id="4">
<td>JW1502-2</td>
<td class="code-quantity-total">0</td>
<td>25.00</td>
<td class="code-cost-total">0</td>
</tr>
</tbody>
The list of rows (JW1501, JW1502) is dynamic.
The problem I am having is that if a variant of e.g. JW1502 is added, only the total quantity and value is calculated for that one. Any previous different variants of JW1502 are ignored.
How can I fix this?
Example content of var model:
[
{"product_id":"JW1501","size_id":"70A","colour_id":"小豹纹","quantity":"1"},
{"product_id":"JW1501","size_id":"75B","colour_id":"小豹纹","quantity":"2"},
{"product_id":"JW1502","size_id":"85A","colour_id":"黑色","quantity":"1"}
]
The above for JW1501 would show the incorrect quantity of 2, not 3.
...
$('#product_totals tr').each(function (i3, v3) {
console.log(v1, v2, v3)
...
Outputs:
Object {product_id: "JW1501", size_id: "70A", colour_id: "小豹纹", quantity: "2"}
"JW1501"
<tr data-id=​"1">​<td>​JW1501​</td>​<td class=​"code-quantity-total">​2​</td>​<td>​79.00​</td>​<td class=​"code-cost-total">​158.00​</td>​</tr>​
I have completely changed your printStock function to achieve your goal:
function printStock(model) {
$("#product_totals tr").each(function(){
var id = $("td:eq(0)", this).text().trim();
var price = parseFloat($("td:eq(2)", this).text());
var count = 0;
$.each(model, function(i, item){
if (item.product_id == id) count += (+item.quantity);
});
$("td:eq(1)", this).text(count);
$("td:eq(3)", this).text((count * price).toFixed(2));
});
var rows = $.map(model, function(item){
return [
"<td>" + item.product_id + "</td>",
"<td>" + item.size_id + "</td>",
"<td>" + item.colour_id + "</td>",
"<td>" + item.quantity + "</td>"
].join("");
});
var html = "<tr>" + rows.join("</tr><tr>") + "</tr>";
$('#stock_order tbody').html(html);
}
The main difference is that my code groups items in model by product_id for further counting.
Also refer my fiddle.

javascript value does not add up

I try to make a count up function whenever there is pressed on a button (button is not in this code).
the result of the count up should be in the read only text field.
var html='';
var huidig = 0;
$('body').off('click', '[data-type=product]').on('click', '[data-type=product]', function(e)
{
e.preventDefault();
var price = $(this).attr('data-price');
var name = $(this).attr('data-name');
var id = $(this).attr('data-id');
if($('input[value='+id+']').length > 0)
{
var parent = $('input[value='+id+']').parent();
console.log("parent: " + parent);
var currentValue = parseFloat(parent.find('input[name^=product_amount]').val());
console.log("currentValue: " + currentValue);
currentValue++;
console.log("currentValue: " + currentValue);
parent.find('input[name^=product_amount]').val(parseFloat(currentValue));
console.log(parent.find('input[name^=product_amount]').val(parseFloat(currentValue)));
}
else
{
html+='<div class="row-fluid"><div class="span1"><input type="hidden" name="product[]" value="'+id+'"/><input type="text" readonly="readonly" name="product_amount[]" value="0" /></div> <div class="span7">'+name+'</div> <div class="span3 offset1">€'+price+'</div> </div>';
}
$('.bill').html(html);
amount = amount + parseFloat(price);
$('.total_bill').html(amount.toFixed(2));
});

Build a array of div's id using each DIV inside section

I'm trying to get the ID of each DIV inside this HTML code
<section id="choices">
<div id="talla_choice_24" style="">
...
</div>
<div id="color_choice_25" style="">
...
</div>
<div id="sport_choice_26" style="">
...
</div>
<button type="button" class="create-variation" id="create-variation" style="">Crear variaciones</button>
<section id="variations_holder" style="display: none"></section>
</section>
So I made this:
function getDivId(div) {
var inputValues = [];
$("#" + div + ' > div').each(function() {
inputValues.push($(this).val());
})
return inputValues;
}
And I call here:
$('#choices').on("click", "#create-variation", function(e) {
var parent_id = $(this).closest("section").attr("id");
var element = getDivId(parent_id);
iterateChoices("", element[0], element.slice(1), 0);
});
I need to build something like this:
var element = new Array($('#talla_choice_24 input:text'), $('#color_choice_25 input:text'), $('#sport_choice_26 input:text'));
But I get this error:
Uncaught TypeError: Object has no method 'each'
What is wrong?
UPDATE
This is the code for iterateChoices() function:
function iterateChoices(row, element, choices, counter) {
if ($.isArray(choices) && choices.length > 0) {
element.each(function(index, item) {
if (counter == 0)
row = '<input type="text" required="required" value="" name="pupc[]" /><input type="text" required="required" value="" name="pprice[]" /><input type="text" required="required" value="" name="pqty[]" />';
iterateChoices(row + '<input value="' + item.value + '">', choices[0], choices.slice(1), counter + 1);
});
} else {
html_temp = "";
$.each(element, function(index, item) {
html_temp += row + '<input value="' + item.value + '"><br>';
});
html += html_temp;
}
}
I also made some changes at this code:
function getDivId(div) {
var inputValues = [];
$("#" + div + ' > div').each(function() {
inputValues.push("#" + $(this).attr('id') + ' input:text');
});
return inputValues;
}
And now the error change to this:
Uncaught TypeError: Object #talla_choice_24 input:text has no method 'each'
UPDATE 2
I still continue change getDivId() function to build a array like this:
var element = new Array($('#talla_choice_24 input:text'), $('#color_choice_25 input:text'), $('#number_choice_23 input:text'), $('#sport_choice_23 input:text'));
But can't get it since array values are constructed as strings, see below:
function getDivId(div) {
var inputValues = [];
$("#" + div + ' > div').each(function() {
inputValues.push('$("#' + $(this).attr('id') + ' input:text")');
});
return inputValues;
}
I'm getting:
("$('#talla_choice_24 input:text')", "$('#color_choice_25 input:text')")
I think there is the problem
You are using the val method on a div element, which just returns an empty string. There is no each method on a string.
You don't need the id of each div to get the input elements inside them. This will get you the inputs in a single jQuery object:
var element = $(this).closest("section").find("> div input:text");
If you really need an array of separate jQuery objects, you can then do this:
element = element.map(function(){ return $(this); }).get();
var arr = [];
$("#create-variation").on('click', function(){
$("#choices > div").each(function(a,b){
arr.push($(this).text());
});
});
After some headaches I realized how to fix the (my) error, here is the solution to all the problems:
function getDivId(div) {
var inputValues = [];
$("#" + div + ' > div').each(function() {
inputValues.push($("#" + $(this).attr('id') + " input:text"));
});
return inputValues;
}

Categories

Resources