how to control for loop - javascript

this is my code......initially alltextboxes is showing...if i click the next or prev button it works properly....but i want only two textboxes per each click so initialy should show two text box ..........how i get it........how to solve......
see for full code:http://jsfiddle.net/sankarss/gAVZ8/22/
function starts(values)
{
maximum=values;
var form = document.forms[0];
var container = $("#sankar");
container.empty();
for (var i = 0; i < maximum; i++)
container.append('<fieldset style="width: 250px; height: 80px;"><legend>Files of ' +(i + 1) + ' / ' + maximum + '</legend><input type="text" name="name' + i + '" /><br /><br /><input type="text" name="topic' + i + '" /></fieldset>');
goto(form, 0);
}

Simply put this code under the for() line:
if(i>=2){
continue;
}
Ad#m

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.

Make entire table editable and saving the changes on click

I'm trying to make an editable table such that when the user clicks on the 'edit' button, every table data cell get placed inside an input form that the user can type in and change the information. Once the user is done, they may click the edit button again so that all of the input fields go away and the changes made are saved and displayed on the table.
I have made it so that every single data in every table data cell gets placed inside an input field when the user clicks the single 'edit' button. However, I'm having a really rough time trying to figure out how to remove the input boxes and display all the updated table cells. I was thinking of placing "contenteditable" withing every td and changing it to true/false would work, but I couldn't figure it out.
I'm using local storage for this, but I just need help on this one thing. Any help would be greatly appreciated.
var retrieveContacts = localStorage.getItem("contacts");
var newVariable = JSON.parse(retrieveContacts);
var isEdit = 0; // is the table in edit mode? 0- false 1- true
// set to 0 (false) by default
$.each(newVariable, function(){
$('#tableStyles').append('<tr>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].email + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].firstname + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].lastname + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].prefix + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].title + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].company + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].phone + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].fax + '</td>' +
'</tr>');
i++;
});
$('#createCont').click(function(){
var newRow = "<tr style='height: 35px;'><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>";
$('#tableStyles').append(newRow);
newVariable.push({"email": "",
"firstname": "",
"lastname": "",
"prefix": "",
"title": "",
"company": "",
"phone": "",
"fax": ""});
localStorage.setItem("contacts", JSON.stringify(newVariable));
});
$('#editCont').click(function(){
if(isEdit == 0){
var j = 0;
var trCount = 2; // up to newVariable.length+1
var tdCount = 1; // up to 8
for(trCount; trCount < newVariable.length+2; trCount++){
for(tdCount; tdCount < 9; tdCount++){
var testing1 = $("tr:nth-child(" + trCount + ")").children("td:nth-child(" + tdCount + ")");
var testing2 = testing1.html("<input type='text' value='" + testing1.html() + "'/>");
}
tdCount = 1;
}
trCount = 2;
tdCount = 1;
isEdit = 1;
//console.log("isEdit set to 1");
} else if(isEdit == 1) { // if the edit button is clicked and we are already editing the form,
// then we have take out the input boxes and save all changes.
for(trCount; trCount < newVariable.length+2; trCount++){
for(tdCount; tdCount < 9; tdCount++){
var testing1 = $("tr:nth-child(" + trCount + ")").children("td:nth-child(" + tdCount + ")");
}
tdCount = 1;
}
isEdit = 0;
//console.log("isEdit set to " + isEdit);
}
});
I would like to offer you a better solution. You can place the input field directly into the table cells and use the readonly attribute to set it editable.
Here is the code:
document.getElementById("edit").addEventListener("click", function() {
var fields = document.querySelectorAll("table input[type='text']");
for (var i = 0; i < fields.length; i++) {
fields[i].readOnly = false;
}
document.getElementById("save").style.display = "inline-block";
});
document.getElementById("save").addEventListener("click", function() {
var data = {};
data.name = document.getElementById("name").value;
data.email = document.getElementById("email").value;
// window.localStorage.formData = JSON.stringify(data);
// localStorage will not work in this snippet editor
// uncomment it in your code
var fields = document.querySelectorAll("table input[type='text']");
for (var i = 0; i < fields.length; i++) {
fields[i].readOnly = true;
}
document.getElementById("save").style.display = "none";
});
table input[type="text"] {
/* place any styling here */
}
table input[type="text"]:read-only {
border: none;
}
#save {
display: none;
}
<form>
<table>
<tr>
<td>Name:</td>
<td><input type="text" id="name" value="Some Name" readonly /></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" id="email" value="Email address" readonly /></td>
</tr>
</table>
<input type="button" id="edit" value="Edit" />
<input type="button" id="save" value="Save" />
</form>
Please, tell me if it works for you!

How to add or delete fields depending on value of another field

I have form:
<div class="fieldWrapper">
<label for="id_rooms">Rooms:</label>
<input id="id_rooms" type="number" name="rooms" min="1">
</div>
<div class="extrafieldWrapper">
</div>
Depending on number of rooms i want to add or delete new fields "adult" and "children". For example: if value of field "room" will be 2, it should generate two couples another fields for each room 'adult' and 'children', but if change value from 2 on 1, it should delete one couple of fields. And when change the value of 'room' field from 2 to 3, it should add one couple of fields. I saw many examples how to do this on java-script, so i try to write the script by my self, but it doesn't work correctly. Depending on value of field 'room' it only add new couple of fields.
$(function() {
var newFields = $('');
$('#id_rooms').bind('blur keyup change', function() {
var n = this.value || 0;
if (n + 1) {
if (n > newFields.length) {
addFields(n);
} else {
removeFields(n);
}
}
});
function addFields(n) {
for (form_num = newFields.length; form_num < n; form_num++) {
$("input[id='id_form-TOTAL_FORMS']").attr('value', form_num + 1);
$(".extrafieldWrapper").append("<br/><label for='id_form-" + form_num + "-adult'>Adult:</label> <input id='id_form-" + form_num + "-adult' type='number' name='form-" + form_num + "-adult'/> <label for='id_form-" + form_num + "-children'>Children:</label> <input id='id_form-" + form_num + "-children' type='number' name='form-" + form_num + "-children'/> ");
}
}
function removeFields(n) {
$('.extrafieldWrapper').html('');
}
});
I am newbie in java-script, can you tell me what i'm doing wrong. Thanks a lot.
It's a bit unclear what behavior exactly you wanted. Here I tried to represent it with code:
$(function () {
$('#id_rooms').bind('blur keyup change', function () {
var n = $('#id_rooms').val() || 0;
$("input#id_form-TOTAL_FORMS]").attr('value', n);
$(".extrafieldWrapper").empty();
for (var i = 0; i < n; i++) {
$(".extrafieldWrapper").append("<br/><label for='id_form-" + i + "-adult'>Adult:</label> <input id='id_form-" + i + "-adult' type='number' name='form-" + i + "-adult'/> <label for='id_form-" + i + "-children'>Children:</label> <input id='id_form-" + i + "-children' type='number' name='form-" + i + "-children'/>");
}
});
});
Anyway, you don't need two functions for adding and removing fields. You only need to rewrite the whole content of your div in one cycle. Or, if you prefer two functions approach, then you need to gather all the tags describing one pair of fields you add/remove under one div or span and give each of such groups an unique id by which you would address it.

How to do client side validations if some text boxes are generated dynamically

I'm working on a form which has this add button, if the button is clicked a text box is foing to generate and i have a minus button to cancel it.
my problem is i have to work on client side validations in this page
the code i used to generate new text boxes is
i = 0;
var counter = 2;
$("#addButton").click(function () {
optionCount++;
i++;
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv'+i);
newTextBoxDiv.after().html('<label>Option : </label>' +
'<input type="text" class="add_input" name="textbox' + counter + '" id="textbox' + counter + '" > <input type="button" class="rem_img minusclick" id="removeButton'+i+'" alt="Remove" title="Remove" onclick="RemoveButton(\''+i+'\',\''+counter+'\')">');
newTextBoxDiv.appendTo("#TextBoxesGroup");
optionIds.push(counter);
counter++;
The validation is to be done after clicking the submit button. and i need to display an error message beside each empty text box(that is generated by clicking add button)
im confused where to start and what exactly i have to do for this
Please help..
I add onchange method textbox;
i = 0;
var counter = 2;
$("#addButton").click(function () {
optionCount++;
i++;
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv'+i);
newTextBoxDiv.after().html('<label>Option : </label>' +
'<input type="text" onchange="Validate(this,\"ValueControl\")" class="add_input" name="textbox' + counter + '" id="textbox' + counter + '" > <input type="button" class="rem_img minusclick" id="removeButton'+i+'" alt="Remove" title="Remove" onclick="RemoveButton(\''+i+'\',\''+counter+'\')">');
newTextBoxDiv.appendTo("#TextBoxesGroup");
optionIds.push(counter);
counter++;
Create This function;
function Validate(elementObject,validType){
if(validType=="ValueControl"){
if($(elementObject).val()==''){
$(elementObject).css("background-color","#000000");
}
}
}

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