dynamic id selector not being called or instantiate - javascript

I am creating a jquery function, when I add new <tr id="select_row"> this tag with id will increase by one for example select_row1, select_row2, select_row3.
After the row has been increased I try to click on the checkbox but it does not trigger below as well as changing the value where id is #single_price0 and #total_price0
if ( ((meat_length == 1)&&(vege_length == 2)) || ((meat_length == 1)&&(vege_length == 1)) ) {};
var list = $('#add_order_table');
var initial = 0;
list.click(function(){
html = '<tr id="select-row'+initial+'">';
html += '<td class="col-md-7">';
//meat
html += '<div class="col-md-6">';
html += '<div class="checkbox"><label><input type="checkbox" name="meat'+initial+'[]" class="meat"> Black Pepper Fried Chicken</label></div>';
html += '<div class="checkbox"><label><input type="checkbox" name="meat'+initial+'[]" class="meat"> Pineapple Pork</label></div>';
html += '<div class="checkbox"><label><input type="checkbox" name="meat'+initial+'[]" class="meat"> Bitter Gourd with Dash Fish</label></div>';
html += '</div>';
//vege
html += '<div class="col-md-6">';
html += '<div class="checkbox"><label><input type="checkbox" name="vege'+initial+'[]" class="vege"> Garlic Bayam</label></div>';
html += '<div class="checkbox"><label><input type="checkbox" name="vege'+initial+'[]" class="vege"> Oyster Young Pakchoy</label></div>';
html += '</div>';
html += '</td>';
html += '<td class="col-md-1 text-center"><b><p>RM <span id="single_price'+initial+'">0.00</span></p><b></td>';
html += '<td class="col-md-2"><p><input id="qty'+initial+'"type="text" value="" name="demo" class="text-center qty_spinner"></p></td>';
html += '<td class="col-md-1 text-center"><b><p>RM <span id="total_price'+initial+'">0.00</span></p><b></td>';
html += '<td class="col-md-1 text-center"><p><button type="button" class="btn btn-danger" onclick="$(\'#select-row' + initial + '\').remove();">';
html += '<span class="glyphicon glyphicon-minus-sign" aria-hidden="true"></span>';
html += '</button></p></td>';
html += '</tr>';
$('#order_table tbody').append(html);
$('.qty_spinner').TouchSpin({
initval: 1,
min:1,
max:50,
buttondown_class: 'btn btn-danger',
buttonup_class: 'btn btn-primary',
});
var row = $("#select-row"+initial);
row.on('change',function(e){
var meat_length = $('input[class="meat"]:checked').length;
var vege_length = $('input[class="vege"]:checked').length;
if (meat_length == 0 || vege_length == 0) {
$("#single_price"+initial).text("0.00");
$("#total_price"+initial).text("0.00");
};
// 5.50 meal function
if ( ((meat_length == 1)&&(vege_length == 2)) || ((meat_length == 1)&&(vege_length == 1)) ) {
// set single price without parsing
$("#single_price"+initial).text("5.50");
//get single price with parsing
var single1 = parseFloat($("#single_price"+initial).text()).toFixed(2);
// get quantity value
var qty1 = parseInt($("#single_qty"+initial).val());
//single price multiply
var total = parseFloat(single1*qty1).toFixed(2);
$("#total_price"+initial).text(total);
};
// 6.00 meal function
if ( ((meat_length == 2)&&(vege_length == 1)) || (meat_length == 2) ) {
// set single price without parsing
$("#single_price"+initial).text("6.00");
//get single price with parsing
var single1 = parseFloat($("#single_price"+initial).text()).toFixed(2);
// get quantity value
var qty1 = parseInt($("#single_qty"+initial).val());
//single price multiply
var total = parseFloat(single1*qty1).toFixed(2);
$("#total_price"+initial).text(total);
};
});
initial++;
});

Wrap initial in a function, so it preserves the increment within the change function:
(function(initial) {
var row = $("#select-row"+initial);
row.on('change',function(e){
var meat_length = $('input[class="meat"]:checked').length;
var vege_length = $('input[class="vege"]:checked').length;
if (meat_length == 0 || vege_length == 0) {
$("#single_price"+initial).text("0.00");
$("#total_price"+initial).text("0.00");
};
// 5.50 meal function
if ( ((meat_length == 1)&&(vege_length == 2)) || ((meat_length == 1)&&(vege_length == 1)) ) {
// set single price without parsing
$("#single_price"+initial).text("5.50");
//get single price with parsing
var single1 = parseFloat($("#single_price"+initial).text()).toFixed(2);
// get quantity value
var qty1 = parseInt($("#single_qty"+initial).val());
//single price multiply
var total = parseFloat(single1*qty1).toFixed(2);
$("#total_price"+initial).text(total);
};
// 6.00 meal function
if ( ((meat_length == 2)&&(vege_length == 1)) || (meat_length == 2) ) {
// set single price without parsing
$("#single_price"+initial).text("6.00");
//get single price with parsing
var single1 = parseFloat($("#single_price"+initial).text()).toFixed(2);
// get quantity value
var qty1 = parseInt($("#single_qty"+initial).val());
//single price multiply
var total = parseFloat(single1*qty1).toFixed(2);
$("#total_price"+initial).text(total);
};
});
})(initial);

Related

Generate html in for each with closing tag every 4 loop

I'm trying to generate the following html :
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-3"></div>
<div class="col-md-3"></div>
<div class="col-md-3"></div>
</div>
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-3"></div>
<div class="col-md-3"></div>
<div class="col-md-3"></div>
</div>
<div class="row">
<div class="col-md-3"></div>
</div>
So I tried the following :
var response = '[{"id":7},{"id":10},{"id":15},{"id":11},{"id":14},{"id":9},{"id":8},{"id":12},{"id":1}]'
var json = $.parseJSON(response);
var add_html = "";
$(json).each(function (i, val) {
if (i % 4 == 0){
add_html += "<div class='row'>";
}
add_html = add_html + "<div class='col-md-3'></div>";
if (i % 4 == 0){
add_html = add_html + "</div>";
}
});
/*
if (i % 4 != 1){
add_html = add_html + "</div>";
}
*/
console.log(add_html)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
But doesn't output the desired result
Try like below. And check changes with comment.
There are two changes in your code.
You need to open your row div with i%4 == 0 and close it with i%4 == 3.
Once each loop complete you should check if (json.length - 1) % 4 != 3 then need to add </div>
var response = '[{"id":7},{"id":10},{"id":15},{"id":11},{"id":14},{"id":9},{"id":8},{"id":12},{"id":1}]'
var json = $.parseJSON(response);
var add_html = "";
$(json).each(function(i, val) {
if (i % 4 == 0) {
add_html += "<div class='row'>";
}
add_html = add_html + "<div class='col-md-3'></div>";
// Change 1 - Update condition here to compare with 3
if (i % 4 == 3) {
add_html += "</div>";
}
});
// Change 2 - Add additional condition
if ((json.length - 1) % 4 != 3) {
add_html += "</div>";
}
console.log(add_html)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Old version
Initialize add_html with opening row div.
When i % 4 == 3 which means it is forth index add closing div and open a new one.
Once each loop completes then add closing div.
Note - This has one bug. It will add extra <div class='row'></div> when json array is of json.length % 4 == 0 .
var response = '[{"id":7},{"id":10},{"id":15},{"id":11},{"id":14},{"id":9},{"id":8},{"id":12},{"id":1}]'
var json = $.parseJSON(response);
// Initialize your html with opening row div
var add_html = "<div class='row'>";
$(json).each(function(i, val) {
add_html = add_html + "<div class='col-md-3'></div>";
if (i % 4 == 3) { // <- Update condition here to compare with 3
// Close current row div and open new one
add_html += "</div>";
add_html += "<div class='row'>";
}
});
// End your html with closing row div
add_html = add_html + "</div>";
console.log(add_html)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
To achieve your goal you could batch the original array in to groups of 4 and then use map() to iterate through that and create the HTML you require:
var json = $.parseJSON('[{"id":7},{"id":10},{"id":15},{"id":11},{"id":14},{"id":9},{"id":8},{"id":12},{"id":1}]');
let perChunk = 4;
json = json.reduce((all, one, i) => {
const ch = Math.floor(i / perChunk);
all[ch] = [].concat((all[ch] || []), one);
return all
}, [])
let html = json.map(chunk => `<div class="row">${chunk.map(item => `<div class="col-md-3"></div>`).join('')}</div>`).join('');
console.log(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
var response = '[{"id":7},{"id":10},{"id":15},{"id":11},{"id":14},{"id":9},{"id":8},{"id":12},{"id":1}]'
var json = JSON.parse(response);
const add_html = json.map(() => '<div class="col-md-3"></div>').reduce((pre, cur) => {
const arr = pre[pre.length - 1];
if (arr.length >= 4) {
pre.push([cur])
} else {
arr.push(cur);
}
return pre;
}, [[]]).map(item => `<div class="row">${item.join('')}</div>`).join('')

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.

How to set minimum length of 6 in input? [Live seach]

How can I display the results with at least two characters? So I'll get faster results list.
I can not use any Submit button, this is auto complete form
HTML :
<input class="form-control btn-group-lg" data-minlength="2" type="text" id="autoCompleteSearch" value="" required="required">
JavaScript:
$(document).ready(function () {
var data = [
"id": "",
"soruCore": "",
"soruIceri": "",
"sik1": ""
},
];
$('#txt-search').keyup(function () {
var searchField = $(this).val();
if (searchField === '') {
$('#filter-records').html('');
return;
}
var regex = new RegExp(searchField, "i");
var output = '<div class="row" style="margin: 10px;">';
var count = 1;
$.each(data, function (key, val) {
if ((val.soruIceri.search(regex) != -1) || (val.soruCore.search(regex) != -1)) {
output += '<div class="container">';
output += '<div class="row">';
output += '<h2 style="color: #FFFFFF">' + val.sik1 + '</h2>';
output += '</div></div>';
output += '</section>';
if (count % 2 == 0) {
output += '</div><div class="row">';
}
count++;
}
});
output += '</div>';
$('#filter-records').html(output);
});
});
Try this:
function checkLength(){
var textbox = document.getElementById("textbox");
if(textbox.value.length >= 6)
}
You should use the pattern attribute. You might need the "required" attribute too because otherwise an empty value will be excluded from constraint validation.
<input required pattern=".{6,}" title="6 characters minimum">
<input required pattern=".{6,20}" title="6 to 20 characters">

Loop through array and add to string based on count

I'm trying to loop through an array of items and build up a HTML structure based on what count we are at through the array.
It should wrap every item in a cell and every 4 items in a row and every 8 items in a column div.
Here is the JavaScript:
var html = ''; // for those that were asking where html was...
for(var i=0;i<response.length;i++)
{
// for first and every 8 items
if(i == 0 || i % 8 === 0)
{
console.log('columnstart');
html = html + '<div class="column">';
}
// for first and every 4 items
if(i == 0 || i % 5 === 0)
{
console.log('rowstart');
html = html + '<div class="row">';
}
// after every 4 items BUT NOT the first
if(i % 4 === 0 && i !== 0)
{
console.log('rowend');
html = html + '</div>';
}
// after every 8 items BUT NOT the first
if(i == response.length && i !== 0 || i % 7 === 0 && i !== 0)
{
console.log('columnend');
html = html + '</div>';
}
console.log('cell');
html = html + '<div class="cell"></div>';
}
and here is an example of how the HTML should be being rendered:
<div class="column">
<div class="row">
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
</div>
<div class="row">
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
</div>
</div>
<div class="column">
<div class="row">
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
</div>
<div class="row">
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
</div>
</div>
However it seems my counts are off...
Because I get the following in the console:
columnstart
rowstart
cell
cell
cell
cell
cell
rowend
rowstart
cell
cell
cell
columnend
columnstart
cell
rowend
cell
rowstart
cell
cell
Well, it seems there was a lot wrong with your logic, so I just rewrote the whole thing. Basically, treat the first and last element as special cases, that way the counting logic doesn't need to be as complicated.
See comments for more information:
var html = '';
for (var i = 0; i < response.length; i++) {
// If first element, open column and row and add first cell.
if (i == 0) {
html = html + '<div class="column">';
html = html + '<div class="row">';
html = html + '<div class="cell"></div>';
// If the first element, is also the last, then close row and column now.
if (i == response.length - 1) {
html = html + '</div>';
html = html + '</div>';
}
}
// If last element, add last cell and close row and column.
else if (i == response.length - 1) {
html = html + '<div class="cell"></div>';
html = html + '</div>';
html = html + '</div>';
}
// Otherwise, process based on count.
else {
// If end of row, then close row.
if (i % 4 == 0) {
html = html + '</div>';
}
// If end of column close column, open new column.
if (i % 8 == 0) {
html = html + '</div>';
html = html + '<div class="column">';
}
// If end of row, open new row.
if (i % 4 == 0) {
html = html + '<div class="row">';
}
// Insert the cell.
html = html + '<div class="cell"></div>';
}
}
Here is a working example
A couple of tyypos:
// for first and every 4 items
if(i == 0 || i % 5 === 0)
{
console.log('rowstart');
html = html + '<div class="row">';
}
should be:
// for first and every 4 items
if(i == 0 || i % 4 === 0)
{
console.log('rowstart');
html = html + '<div class="row">';
}
a typpo or two and an issue with logic and precedence:
// after every 8 items BUT NOT the first
if(i == response.length && i !== 0 || i % 8 === 0 && i !== 0)
{
console.log('columnend');
html = html + '</div>';
}
should be:
// after every 8 items BUT NOT the first
if(i === response.length - 1 || (i !== 0 && i % 8 === 0))
{
console.log('columnend');
html = html + '</div>';
}
for(var i=0;i<response.length;++i)
{
// for first and every 8 items
if(i % 8 == 0) {
console.log('columnstart');
html = html + '<div class="column">';
}
// for first and every 4 items
if(i % 4 == 0) {
console.log('rowstart');
html = html + '<div class="row">';
}
console.log('cell');
html = html + '<div class="cell"></div>';
// after every 4 items BUT NOT the first
if(i % 4 == 3) {
console.log('rowend');
html = html + '</div>';
}
// after every 8 items
if(i % 8 == 7) {
console.log('columnend');
html = html + '</div>';
}
}
Should be
for(var i=0;i<response.length;i++)
{
// Before 1st and every 8 cells
if(i % 8 == 0)
{
console.log('columnstart');
html = html + '<div class="column">';
}
// Before 1st and every 4 items
if(i % 4 == 0)
{
console.log('rowstart');
html = html + '<div class="row">';
}
console.log('cell');
html = html + '<div class="cell"></div>';
// after every 4th cell added
if(i % 4 == 3)
{
console.log('rowend');
html = html + '</div>';
}
// after every 8th cell added
if(i % 8 ==7)
{
console.log('columnend');
html = html + '</div>';
}
}
I'm afraid you misinterpreted the modulo (%) operator
i % 7==0 means that i is divisible by 7 what you want is i % 8==7
I always find it more clear with a switch statement:
while (response.length%8!=7)
response.push('');
var html='';
for(var i=0;i<response.length;i++)
{
switch (i%8) {
case 0: html = html + '<div class="column"><div class="row">'+response[i];break;
case 4: html = html + '</div><div class="row">'+response[i];break;
case 7: html = html + response[i]+'</div></div>';break;
default: html = html + response[i];
}
}

Splitting an array

I have two javascript functions, the first one is working, teh second is working but not echoing the correct value in the hidden inputs.
Ive manage to get the last hidden input value correct but I'm not sure how
var customTicketsArr = Array();
function EditEventAddTicket(){
alertWrongTime = false;
var TicketName = jQuery("#ticketname").val();
var TicketPrice = jQuery("#ticketprice").val();
var ticketquantity = jQuery("#ticketquantity").val();
var storeString = "TicketName" + TicketName + "TicketPrice" + TicketPrice + "Quantity" + ticketquantity + '';
customTicketsArr.push(storeString);
EditEventUpdateTickets(true);
}
function EditEventUpdateTickets(fade){
jQuery("#custom_tickets_string").val(customTicketsArr);
var output = "";
var style = "";
for (i = customTicketsArr.length-1; i >= 0; i--){
ticketname = customTicketsArr[i].split("TicketName");
ticketprice = customTicketsArr[i].split("TicketPrice");
ticketquantity = customTicketsArr[i].split("Quantity");
if(fade){
if (customTicketsArr.length - 1 == i){
style = "display: none; ";
var fadeInDiv = i;
} else {
style = "";
}
}
if (i % 2 == 1) { style += "background-color: #660000; "}
html = "<div id='customticket" + i + "' class='customeventbase' style='" + style + "'>";
html += '<input type="hidden" name="customTicketid[' + i + '][Name]" id="customticketName' + i + '" value="'+ ticketname + '" />';
html += '<input type="hidden" name="customTicketid[' + i + '][Price]" id="customticketPrice' + i + '" value="' +ticketprice[1] +'" />';
html += '<input type="hidden" name="customTicketid[' + i + '][Quantity]" id="customticketQuantity' + i + '" value="'+ ticketquantity[1] +'" />';
html += '<button class="customeventdel" type="button" onClick="EditEventRemoveDate(' + i + ')"></button>';
html += '<div class="clear"></div>';
html += '</div>\n';
output += html;
}
output += "<input type='hidden' id='custom_ticket_info' name='custom_ticket_info' value='" + customTicketsArr + "' />";
jQuery("#custom_ticket_container").html(output);
if(fade){
setTimeout("EditEventfadeInDiv(" + fadeInDiv +")", 10);
}
}
this outputs:
<div style="background-color: #660000; " class="customeventbase" id="customticket1">
<input type="hidden" value=",testTicketPrice50Quantity44" id="customticketName1" name="customTicketid[1][Name]">
<input type="hidden" value="undefined" id="customticketPrice1" name="customTicketid[1][Price]">
<input type="hidden" value="44" id="customticketQuantity1" name="customTicketid[1][Quantity]">
<button onclick="EditEventRemoveDate(1)" type="button" class="customeventdel"></button>
<div class="clear"></div></div>
the values for the first two hidden fields are incorrect
They're not incorrect values - split() is doing exactly what it is supposed to - returning an array of substrings after removing the separator.
With your string structure, splitting on TicketName will give you two strings - the substring before the separator and the substring after - TicketName itself is not included.
Thus, for the string "TicketNametestTicketPrice50Quantity44", you will get "" and "testTicketPrice50Quantity44" when you split on "TicketName" . Splitting the same string on TicketPrice will give you "TicketNametest" and "50Quantity44".
I'd suggest putting objects into your array instead -
var storeObject = {
"TicketName" : TicketName,
"TicketPrice" : TicketPrice,
"Quantity" : ticketquantity
};
customTicketsArr.push(storeObject);
You can then get back the data as:
for (i = customTicketsArr.length-1; i >= 0; i--){
var currentObject = customTicketsArr[i];
var ticketname = currentObject.TicketName;
var ticketprice = currentObject.TicketPrice;
var ticketquantity = currentObject.Quantity;
//do other stuff here
}
why do you save it as a string? I would recommend storing it in an object:
function EditEventAddTicket(){
alertWrongTime = false;
var TicketName = jQuery("#ticketname").val();
var TicketPrice = jQuery("#ticketprice").val();
var ticketquantity = jQuery("#ticketquantity").val();
var ticket = {"TicketName": TicketName, "TicketPrice": TicketPrice, "Quantity": ticketquantity};
customTicketsArr.push(ticket);
EditEventUpdateTickets(true);
}
and then you can simply load the data:
for (i = customTicketsArr.length-1; i >= 0; i--){
ticketname = customTicketsArr[i].TicketName;
ticketprice = customTicketsArr[i].TicketPrice;
ticketquantity = customTicketsArr[i].Quantity;
// ...
}
Why not just make a two dimensional array?
var customTicketsArr = Array();
function EditEventAddTicket() {
customTicketsArr.push({
'name' : jQuery("#ticketname").val(),
'price' : jQuery("#ticketprice").val(),
'qty' : jQuery("#ticketquantity").val()
});
}

Categories

Resources