Iterating Ajax response and creating Dynamic table on some condition - javascript

I am trying to create a dynamic table with ajax response.
And want to put condition on check box like if item.statuscheck =1 will print checked Box with name and if item.statuscheck =0 unchecked box will display with same name.
i am able to display name dynamically. But problem is coming with check box.
Here is the code i am trying with. Please help me on this issue.
success(response)
{
$.each(response,function(index,item){
var status;
if(index >=0 and index <= 4)
{
if(item.statusCheck = 1)
{
status = <input type ="checked" checked/>
}
else{
status = <input type="checked" />
}
var content = '<td>'+ status + '</td>'
+<td>' + item.fieldName +'<td>';
$("#tableId").appent(content)
}
}
}

("#tableId").append(content)
Change appent to append

compare operator is == not = assign.Also careful 'and "
success(response)
{
$.each(response,function(index,item){
var status;
if(0 >= index <= 4)
{
if(item.statusCheck == 1)
{
status = '<input type ="checkbox" checked/>';
}
else{
status = '<input type="checkbox" />';
}
var content = '<td>'+ status + '</td>'
+'<td>' + item.fieldName +'<td>';
$("#tableId").append(content);
}
}
}

var content = item.statusCheck == 1 ? '<td><input type="checkbox" checked="checked" />'+item.fieldName+'</td>' : '<td><input type="checkbox" />'+item.fieldName+'</td>';
$("#tableId").append($(content));

Its not type = "checked" its type = "checkbox"
success(response)
{
$.each(response,function(index,item){
var status;
if(index >=0 and index <= 4)
{
if(item.statusCheck = 1)
{
status = <input type ="checkbox" checked/>
}
else{
status = <input type="checkbox"/>
}
var content = '<td>'+ status + '</td>'
+<td>' + item.fieldName +'<td>';
$("#tableId").appent(content)
}
}
}

Related

jQuery shows "undefined" for values after unchecking checkbox

I am new to jQuery and AJAX and I was trying to set up a script that displays a MySQL table which can be updated. I included a checkbox to update various entries at the same time. It works fine but if I uncheck the checkbox, all values change to "undefined".
Here is my code:
$(document).ready(function(){
function fetch_data()
{
$.ajax({
url:"select.php",
method:"POST",
dataType:"json",
success:function(data)
{
var html = '';
for(var count = 0; count < data.length; count++)
{
var bezahlstatus = data[count].bezahlstatus;
var guest_amount = data[count].guest_amount;
html += '<tr>';
html += '<td><input type="checkbox" id="'+data[count].id+'" data-email="'+data[count].email+'" data-guest_amount="'+data[count].guest_amount+'" data-date_reservation="'+data[count].date_reservation+'" data-menu_own="'+data[count].menu_own+'" data-bezahlstatus="'+data[count].bezahlstatus+'" class="check_box"></td>';
html += '<td>'+data[count].email+'</td>';
html += (guest_amount == "") ? "<td>0</td>" : "<td>"+guest_amount+"</td>";
html += '<td>'+data[count].date_reservation+'</td>';
html += '<td>'+data[count].menu_own+'</td>';
html += (bezahlstatus == null || bezahlstatus == "") ? "<td>nicht bezahlt</td>" : "<td>"+data[count].bezahlstatus+"</td>";
}
$('tbody').html(html);
}
});
}
fetch_data();
$(document).on('click', '.check_box', function() {
var html = '';
var guest_amount = $(this).data('guest_amount');
var bezahlstatus = $(this).data('bezahlstatus');
if(this.checked)
{
html = '<td><input type="checkbox" id="'+$(this).attr('id')+'" data-email="'+$(this).attr('email')+'" data-guest_amount="'+$(this).attr('guest_amount')+'" data-date_reservation="'+$(this).attr('date_reservation')+'" data-menu_own="'+$(this).attr('menu_own')+'" data-bezahlstatus="'+$(this).attr('bezahlstatus')+'" class="check_box" checked></td>';
html += '<td><input type="text" name="email[]" class="form-control" value="'+$(this).data("email")+'" /></td>';
html += (guest_amount == "") ? '<td>0</td>' : '<td>'+guest_amount+'</td>';
html += '<td>'+$(this).data('date_reservation')+'</td>';
html += '<td><select name="menu_own[]" id="menu_own_'+$(this).attr('id')+'" class="form-control"><option value="Hauptmenü 1">Hauptmenü 1</option><option value="Hauptmenü 2">Hauptmenü 2</option><option value="Hauptmenü 3">Hauptmenü 3</option></select></td>';
html += '<td><select name="bezahlstatus[]" id="bezahlstatus_'+$(this).attr('id')+'" class="form-control"><option value="">nicht bezahlt</option><option value="bezahlt">bezahlt</option></select></td><input type="hidden" name="hidden_id[]" value="'+$(this).attr('id')+'" />';
}
else
{
html = '<td><input type="checkbox" id="'+$(this).attr('id')+'" data-email="'+$(this).attr('email')+'" data-guest_amount="'+$(this).attr('guest_amount')+'" data-date_reservation="'+$(this).attr('date_reservation')+'" data-menu_own="'+$(this).attr('menu_own')+'" data-bezahlstatus="'+$(this).attr('bezahlstatus')+'" class="check_box"></td>';
html += '<td>'+$(this).data('email')+'</td>';
html += (guest_amount == "") ? '<td>0</td>' : '<td>'+guest_amount+'</td>';
html += '<td>'+$(this).data('date_reservation')+'</td>';
html += '<td>'+$(this).data('menu_own')+'</td>';
html += (bezahlstatus == null || bezahlstatus == "") ? '<td>nicht bezahlt</td>' :
'<td>'+bezahlstatus+'</td>';
}
$(this).closest('tr').html(html);
$('#menu_own_'+$(this).attr('id')+'').val($(this).data('menu_own'));
$('#bezahlstatus_'+$(this).attr('id')+'').val($(this).data('bezahlstatus'));
});
$('#update_form').on('submit', function(event){
event.preventDefault();
if($('.check_box:checked').length > 0)
{
$.ajax({
url:"update.php",
method:"POST",
data:$(this).serialize(),
success:function()
{
alert('Der Eintrag wurde erfolgreich aktualisiert.');
fetch_data();
}
});
}
});
});
I tried to find the mistake in the code section where the checkbox is checked but I am unable to find it. Could someone please help me?
Thank you in advance!

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 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">

Check all or uncheck all in multi checkbox

I have this code for multi check-box
HTML:
<fieldset data-role="collapsible">
<legend>Pick one</legend>
<div data-role="controlgroup" id="ZIBI" align="right" >
</div>
</fieldset>
jQuery/JavaScript:
myArray1 = new Array(
"1","2","3","4","5","6"
);
$("#ZIBI").html('');
for (var i = 0; i < myArray1.length; i++) {
row = myArray1[i];
$("#ZIBI").append(
'<label for=' + row + '>' + row + '</label>' +
'<input type="checkbox" name="favcolor" id=' + row + ' value=' + row + '>');
}
$('#ZIBI').trigger('create');
how to check all or uncheck all by pressing any button ?
thanks
In this JsFiddle you'll find a method to check/uncheck all checkboxes within a given div, using a checkbox with id _main:
function checkAll(e){
e = e || event;
var from = e.target || e.srcElement
,cbs = this.querySelectorAll('input'), i=1;
if (/^_main$/i.test(from.id)){
for (;i<cbs.length;i+=1){
cbs[i].checked = from.checked;
}
} else {
var main = document.querySelector('#_main')
,j = cbs.length;
for (;i<cbs.length;i+=1){
j -= cbs[i].checked ? 0 : 1;
}
main.checked = j === cbs.length ? true : false;
}
}
Update
New elements should be added to $(".selector").controlgroup("container") not $(".selector") directly. If you add them to main div, elements won't be styled as a _controlgroup`.
You need to refresh .checkboxradio("refresh") checkbox or radio to apply jQM styles. Another point, .trigger("create") is deprecated as of jQM 1.4 and replaced with .enhanceWithin().
myArray1 = new Array(
"1", "2", "3", "4", "5", "6");
/* remove previous elements */
$("#ZIBI").controlgroup("container").html('');
for (var i = 0; i < myArray1.length; i++) {
row = myArray1[i];
/* add new ones to container */
$("#ZIBI").controlgroup("container").append(
'<label for=' + row + '>' + row + '</label>' +
'<input type="checkbox" name="favcolor" id=' + row + ' value=' + row + '>');
}
/* refresh controlgroup and enhance elements within */
$("#ZIBI").controlgroup().enhanceWithin();
/* check/uncheck on button click */
$("#foo").on("click", function () {
var status = $("#ZIBI [type=checkbox]").eq(0).prop("checked") ? false : true;
$("#ZIBI [type=checkbox]").prop("checked", status).checkboxradio("refresh");
});
Demo
You can try this:
HTML:
<fieldset data-role="collapsible">
<legend>Pick one</legend>
<div data-role="controlgroup" id="ZIBI" align="right" >
</div>
</fieldset>
<input type="checkbox" id="all" value="Toggle" />
jQuery:
$('#all').on('click', function() {
if(this.checked) {
$('#ZIBI').find('input[type=checkbox]').prop('checked', true);
} else {
$('#ZIBI').find('input[type=checkbox]').prop('checked', false);
}
});
Working Fiddle.

Categories

Resources