jQuery shows "undefined" for values after unchecking checkbox - javascript

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!

Related

Onchange function for dropdown in jquery ajax

I have a script with two dropdowns that it is dependent on. The third dropdown is a price, readOnly, which is dependent on subcategory. I have given onChange but there are some problems. I could not render the price value. I am new to ajax and really need some help. I got this example and changed it to fit my needs. I need to just take price from the onClick of subcategory.
Here is my code:
<script>
$(document).ready(function(){
var count = 0;
$(document).on('click', '.add', function(){
count++;
var html = '';
html += '<tr>';
html += '<td> </td>';
html += '<input type="hidden" name="item_name[]" class="form-control item_name" />';
html += '<td><select name="item_category[]" class="form-control item_category" data-sub_category_id="'+count+'"><option value="">Select Service Type</option><?php echo fill_select_box($connect, "0"); ?></select></td>';
html += '<td><select name="item_sub_category[]" class="form-control item_sub_category" id="item_sub_category'+count+'"><option value="">Select Service Name</option></select></td>';
html += '<td><input type="text" name="item_sub_category_price[]" class="form-control item_sub_category_price" /></td>';
html +='<td><input type="text" name="nosessions[]" class="form-control nosessions" /></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-xs remove"><span class="glyphicon glyphicon-minus"></span>Remove Service</button></td>';
$('tbody').append(html);
});
$(document).on('click', '.remove', function(){
$(this).closest('tr').remove();
});
$(document).on('change', '.item_category', function(){
var category_id = $(this).find(':selected').data('foo');
var sub_category_id = $(this).data('sub_category_id');
// var sub_category_price = $(this).data('sub_category_price');
$.ajax({
url:"fill_sub_category.php",
method:"POST",
data:{category_id:category_id},
success:function(data){
var html = '<option value="">Select Sub Category</option>';
html += data;
$('#item_sub_category'+sub_category_id).html(html);
}
})
});
$(document).on('change', '.sub_category_id', function(){
alert( this.value );
});
$('#insert_form').on('submit', function(event){
event.preventDefault();
var error = '';
$('.item_category').each(function(){
var count = 1;
if($(this).val() == ''){
error += '<p>Select Item Category at '+count+' row</p>';
return false;
}
count = count + 1;
});
$('.item_sub_category').each(function(){
var count = 1;
if($(this).val() == ''){
error += '<p>Select Item Sub category '+count+' Row</p> ';
return false;
}
count = count + 1;
});
$('.item_sub_category_price').each(function(){
var count = 1;
if($(this).val() == ''){
error += '<p>Select Item price '+count+' Row</p> ';
return false;
}
count = count + 1;
});
$('.nosessions').each(function(){
var count = 1;
if($(this).val() == ''){
error += '<p>Select no of sessions '+count+' Row</p> ';
return false;
}
count = count + 1;
});
$('.packname').each(function(){
if($(this).val() == ''){
error += '<p>Select no of packname '+count+' Row</p> ';
return false;
}
});
var form_data = $(this).serialize();
if(error == ''){
$.ajax({
url:"insert.php",
method:"POST",
data:form_data,
success:function(data){
if(data == 'ok'){
$('#item_table').find('tr:gt(0)').remove();
$('#error').html('<div class="alert alert-success">Item Details Saved</div>');
}
}
});
}; else{
$('#error').html('<div class="alert alert-danger">'+error+'</div>');
}
});
});
</script>
<script>
$(document).ready(function(){
var count = 0;
$(document).on('click', '.add', function(){
count++;
var html = '';
html += '<tr>';
html += '<td> </td>';
html += '<input type="hidden" name="item_name[]" id="item_name'+count+'" class="form-control item_name" />';
html += '<td><select name="item_category[]" id="item_category'+count+'" onchange="getsubCategory('+count+')" class="form-control item_category" data-sub_category_id="'+count+'"><option value="">Select Service Type</option><?php echo fill_select_box($connect, "0"); ?></select></td>';
html += '<td><select name="item_sub_category[]" id="item_sub_category'+count+'" class="form-control item_sub_category" id="item_sub_category'+count+'"><option value="">Select Service Name</option></select></td>';
html += '<td><input type="text" name="item_sub_category_price[]" id="item_sub_category_price'+count+'" class="form-control item_sub_category_price" /></td>';
html +='<td><input type="text" name="nosessions[]" id="nosessions'+count+'" class="form-control nosessions" /></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-xs remove"><span class="glyphicon glyphicon-minus"></span>Remove Service</button></td>';
$('tbody').append(html);
});
$(document).on('click', '.remove', function(){
$(this).closest('tr').remove();
});
});
function getsubCategory(id){
var itemCategory="item_category"+id;
var subcategory_id = "item_sub_category"+id;
var category_id= $("#"+itemCategory).val();
$.ajax({
url:"fill_sub_category.php",
method:"POST",
data:{category_id:category_id},
success:function(data){
var html = '<option value="">Select Sub Category</option>';
html += data;
$('#'+subcategory_id).html(html);
}
})
}
</script>
You can do the same for others
I assume that you need to get price of the sub-category using AJAX,
$(document).on('change', '.sub_category_id', function(){
var sub_category_id = $(this).val();
$.ajax({
url:"get_sub_category_price.php",
method:"POST",
data:{sub_category_id : sub_category_id},
success:function(data){
$('#item_sub_category'+sub_category_id).parent().next().find('. item_sub_category_price').val(data);
}
});
});
get_sub_category_price.php file should get the subcategory id and echo the price.

Backbone.js - Solving method

BACKBONE and Jquery
I have a piece of code:
var ChatMessage = Backbone.View.extend({
el : '#friend-list',
events : {},
initialize : function() {},
loadMessage : function(parent_id) {
//ukrycie komunikatów etc.
$("#chat_body").html('');
$("#end-record-info").hide();
$("#end-record-load").hide();
page = 1;
this.ajax(parent_id,page); //initial data load
},
ajax : function(parent_id,page) {
$.getJSON( "/**/**/"+parent_id+"/"+page, function( json ) {
$("#end-record-load").hide();
this.build(json.message, page);
page ++; //page increment
loading = false; //set loading flag off
end_record = false;
if(json.max < page){ //no more records
end_record = true; //set end record flag on
return; //exit
}
});
},
build : function(arr, page) {
alert('dgd');
html = '';
var height = 0;
arr.reverse();
$.each(arr, function(i, data){
html += '<div class="answer '+data.side+'">';
html += '<div class="avatar">';
html += '<a href="**" target="_blank">';
html += ''+data.id+'';
html += '</a>';
html += '<div class="status offline"></div>';
html += '</div>';
html += '<div class="name">';
html += '<a href="**" target="_blank">';
html += data.username;
html += '</a>';
html += '</div>';
html += '<div class="text">';
html += data.content;
html += '</div>';
html += '<div class="time">';
if (data.side != 'left') {
html += data.dateSendMessage
}
else {
if (data.read == 0) {
html += 'xxx';
}
else {
html += 'xxx';
}
}
html += '</div>';
html += '</div>';
});
var nh = $('#chat_body').html();
$('#chat_body').html(html+nh);
if (page == 1) {
$('#chat_body .answer').each(function(i, value){
height += parseInt($(this).height());
});
height += '';
$('.chat2').scrollTop(height);
}
}
});
In AJAX method I want to build method
this.build(json.message, page);
But something does not work and I get an error.
pm2.js:67TypeError: this.build is not a function. (In 'this.build(json.message, page)', 'this.build' is undefined)
Can anyone help? What changes in this piece of code can be by the way?
Piotr
You should probably save current context before calling getJSON:
ajax : function(parent_id,page) {
var self = this;
$.getJSON( "/**/**/"+parent_id+"/"+page, function( json ) {
...
self.build(json.message, page);

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

Iterating Ajax response and creating Dynamic table on some condition

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)
}
}
}

Why is index never == 0?

<script>
var index = 0;
$.getJSON("./data/data.json", function(json) {
$.each(json, function(data) {
var html = "";
if(index == 0)
{
console.log(index + " first item");
html = "<div class='item active'>";
} else {
console.log(index + " its not 0");
html = "<div class='item'>"
}
console.log(json.length); // this will show the info it in firebug console
html += "<blockquote><div class='row'><div class='col-sm-3 text-center'><img class='img-circle' src='images/obama.jpg' style='width: 100px;height:100px;'></div><div class='col-sm-9'><p>Change will not come if we wait for some other person or some other time. We are the ones we've been waiting for. We are the change that we seek.</p><small>President Barack Obama</small></div></div></blockquote></div>";
$('body').append(html);
index++;
});
});
</script>
I need to generate 5 of these but the first one needs to be have 'item active'
If there is a better way, please let me know
Thank you for pointing out that my html was being overwritten. I updated my code but jQuery isn't actually placing my HTML into the body. so thats another question
You can add an index into the $.each method; this will span from 0 to data.length - 1
$.getJSON("./data/data.json", function(json) {
$.each(json, function(index, data) {
var html = "";
html += '<div class="item' + (index == 0 ? ' active' : '') + '">';
html += '<blockquote>...</blockquote>';
html += '</div>';
$('body').append(html);
});
});
<script>
var index = 0;
$.getJSON("./data/data.json", function(json) {
$.each(json, function(data) {
var html = "";
if(index == 0)
html = "<div class='item active'>";
else
html = "<div class='item'>";
html += "<blockquote><div class='row'><div class='col-sm-3 text-center'><img class='img-circle' src='images/obama.jpg' style='width: 100px;height:100px;'></div><div class='col-sm-9'><p>Change will not come if we wait for some other person or some other time. We are the ones we've been waiting for. We are the change that we seek.</p><small>President Barack Obama</small></div></div></blockquote></div>";
$('body').append(html);
index++;
});
});
</script>

Categories

Resources