AJAX: add new row to table or remove using AJAX - javascript

This is the logic:
I input something to form, and the form is AJAX live search. after I found value, I click on add button and it creates new row in existing table / tbody.
<table class="standard">
<thead>
<tr>
<td colspan="2">
Start Input barcode / Product Name
</td>
<td colspan="4">
<input type="text" size="90" value="" placeholder="Barcode / Product Name">
</td>
<td>
<button class="tambah"><i class="icon-plus"></i> Add</button>
</td>
</tr>
<tr>
<td>
No.
</td>
<td>
Kode Barang
</td>
<td>
Nama Barang
</td>
<td>
Qty
</td>
<td>
Harga
</td>
<td>
Disc %
</td>
<td>
Total
</td>
</tr>
</thead>
<tbody>
<!-- when button add is click that will add <tr></tr> here -->
</tbody>
</table>
can i do that? if so, how?
Fiddle Example: http://jsfiddle.net/anggagewor/cauPH/

You can find the pseudo code below.
$('#button_id').on('click', function(e) {
$.ajax({
url : yourUrl,
type : 'GET',
dataType : 'json',
success : function(data) {
$('#table_id tbody').append("<tr><td>" + data.column1 + "</td><td>" + data.column2 + "</td><td>" + data.column3 + "</td></tr>");
},
error : function() {
console.log('error');
}
});
});

Try this
var scntDiv = $('#p_scents');
var i = $('#p_scents tr').size() + 1;
$('#addScnt').click(function() {
scntDiv.append('<tr><td><select name="type" id="type"><option value="Debit">Debit</option><option value="Credit">Credit</option></select></td><td><select name="accounts" id="accounts"><option value="">SELECT</option><option value="One">One</option><option value="Two">Two</option></select></td><td><input type="text" name="debit_amount" id="debit_amount"/></td><td><input type="text" name="credit_amount" id="credit_amount"/></td><td>Remove</td></tr>');
i++;
return false;
});
//Remove button
$(document).on('click', '#remScnt', function() {
if (i > 2) {
$(this).closest('tr').remove();
i--;
}
return false;
});​
Here's a working example, including remove row functionality: DEMO.

$("<tr><td>.....content...<td><a class='remove'>remove</a>").appendTo("#tableid tbody").find('.remove').click(function () {
$(this).parent().parent().remove();
});

In your ajax response you can do this
$("#myTable > tbody").append('<tr><td>my data</td><td>more data</td></tr>');
'#myTable' will be replaced by your table id or class and <td>my data</td><td>more data</td> will be replaced by your content

Related

My validation does not work on added rows and autonumbering

I have a function where i can add rows and autonumbering. The add rows works when you click the "add row" button, and auto numbering works when you press Ctrl+Enter key when there's 2 or more rows. My problem is, my validation does not work on my autonumbering.
For example: when I type manually the "1" on the textbox, it works.
But when I do my auto numbering, "Not good" does not appear on my 2nd
textbox.
Is there anything I missed? Any help will be appreciated.
//this is for adding rows
$("#addrow").on('click', function() {
let rowIndex = $('.auto_num').length + 1;
let rowIndexx = $('.auto_num').length + 1;
var newRow = '<tr><td><input class="auto_num" type="text" name="entryCount" value="' + rowIndexx + '" /></td>"' +
'<td><input name="lightBand' + rowIndex + '" value="" class="form" type="number" /> <span class="email_result"></span></td>"' +
'<td><input type="button" class="removerow" id="removerow' + rowIndex + '" name="removerow' + rowIndex + '" value="Remove"/></td>';
$("#applicanttable > tbody > tr:last").after(newRow);
});
//this is for my validation
$(document).on('change', 'input[name*=lightBand]', function() {
var lightBand1 = $(this).val(); //get value
var selector = $(this) //save slector
selector.next('.email_result').html("") //empty previous error
if (lightBand1 != '') {
/*$.ajax({
url: "<?php echo base_url(); ?>participant/check_number_avalibility",
method: "POST",
data: {
lightBand1: lightBand1
},
success: function(data) {*/
selector.next('.email_result').html("NOT GOOD"); //use next here ..
/* }
});*/
}
});
// this is for autonumbering when ctrl+enter is pressed.
const inputs = document.querySelectorAll(".form");
document.querySelectorAll(".form")[0].addEventListener("keyup", e => {
const inputs = document.querySelectorAll(".form");
let value = parseInt(e.target.value);
if ((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) {
inputs.forEach((inp, i) => {
if (i !== 0) {
inp.value = ++value;
}
})
}
});
Add a row and type any number at number textbox column and press ctrl+enter. You'll see the "Not good" is not working on added rows. It'll only work if you enter the number manually per row.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<table class="table table-bordered" border="1" id="applicanttable">
<thead>
<tr>
</tr>
</thead>
<tbody>
<div class="row">
<tr>
<th>#</th>
<th>Number</th>
<th>Action</th>
</tr>
<tr id="row_0">
<td>
<input id="#" name="#" class="auto_num" type="text" value="1" readonly />
</td>
<td class="labelcell">
<input value="" class="form" name="lightBand1" placeholder="" id="lightBand1" />
<span class="email_result"></span>
</td>
<td class="labelcell">
<input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove">
</td>
</tr>
</div>
</tbody>
<tfoot>
<tr>
</tr>
<tr>
<button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
</tr>
</tfoot>
</table>
You can call your event handler i.e : change whenever you change your input values by auto numbering . So , use $(this).trigger("change") where this refer to input where value is changed .
Demo Code :
$("#addrow").on('click', function() {
let rowIndex = $('.auto_num').length + 1;
let rowIndexx = $('.auto_num').length + 1;
var newRow = '<tr><td><input class="auto_num" type="text" name="entryCount" value="' + rowIndexx + '" /></td>"' +
'<td><input name="lightBand' + rowIndex + '" value="" class="form" type="number" /> <span class="email_result"></span></td>"' +
'<td><input type="button" class="removerow" id="removerow' + rowIndex + '" name="removerow' + rowIndex + '" value="Remove"/></td>';
$("#applicanttable > tbody > tr:last").after(newRow);
});
//this is for my validation
$(document).on('change', 'input[name*=lightBand]', function() {
var lightBand1 = $(this).val(); //get value
var selector = $(this) //save slector
selector.next('.email_result').html("") //empty previous error
if (lightBand1 != '') {
/*$.ajax({
url: "<?php echo base_url(); ?>participant/check_number_avalibility",
method: "POST",
data: {
lightBand1: lightBand1
},
success: function(data) {*/
selector.next('.email_result').html("NOT GOOD"); //use next here ..
/* }
});*/
}
});
// this is for autonumbering when ctrl+enter is pressed.
$(document).on('keyup', '.form', function(e) {
let value = parseInt(e.target.value);
if ((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) {
//loop through all values...
$(".form").each(function(i) {
if (i !== 0) {
$(this).val(++value); //assign new value..
$(this).trigger("change") //call your change event to handle further...
}
})
}
})
Add a row and type any number at number textbox column and press ctrl+enter. You'll see the "Not good" is not working on added rows. It'll only work if you enter the number manually per row.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<table class="table table-bordered" border="1" id="applicanttable">
<thead>
<tr>
</tr>
</thead>
<tbody>
<div class="row">
<tr>
<th>#</th>
<th>Number</th>
<th>Action</th>
</tr>
<tr id="row_0">
<td>
<input id="#" name="#" class="auto_num" type="text" value="1" readonly />
</td>
<td class="labelcell">
<input value="" class="form" name="lightBand1" placeholder="" id="lightBand1" />
<span class="email_result"></span>
</td>
<td class="labelcell">
<input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove">
</td>
</tr>
</div>
</tbody>
<tfoot>
<tr>
</tr>
<tr>
<button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
</tr>
</tfoot>
</table>

jQuery Map To Retrieve Comma Separated Values Separately

I am using multiple text box to insert data into database table. So doing few researches and used online resources to make it work. But stuck into one basic thing, I guess. The issue is with the jQuery mapping. Let me share the code here:
//Add row to the table
$('#btnAddRow').on('click', function() {
var $clone = $('#tblQuesAns tbody tr:last').clone();
$clone.find('input').val('')
$('#tblQuesAns tbody').append($clone);
});
//Add more rows for option
$('body').on('click', '.addOptions', function() {
$(this).parent().append('<div><input class="txtOptions" type="text" /></div>');
});
//Get text box values
$('#btnGetValues').on('click', function() {
const allData = $('#tblQuesAns tbody tr').map(function() {
const $row = $(this),
question = $row.find('.txtQuestion').val(),
options = $row.find('.txtOptions').map(function() {
return this.value;
}).get().join(" ");
//return { question, options };
alert(question + ' ' + options.replace(/\s+/g, "_"));
}).get();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button id="btnAddRow" type="button">
Add Row
</button>
<button id="btnGetValues" type="button">
Get Values
</button>
<table id="tblQuesAns" border="1">
<thead>
<tr>
<th>Question</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input class="txtQuestion" value="Capital of Englnad" />
</td>
<td>
<input class="txtOptions" value="London" />
<span class="addOptions">(+)</span>
</td>
</tr>
<tr>
<td>
<input class="txtQuestion" value="Current Pandemic" />
</td>
<td>
<input class="txtOptions" value="Corona" />
<span class="addOptions">(+)</span>
</td>
</tr>
</tbody>
</table>
By default, jQuery map uses comma and I tried to remove those by using replace method as follows:
options.join(' ').replace(/\s+/g, "_")
Now I may have options that may contain comma. For example:
Question Options
Question 1 New York
Jakarta
London, Paris
Munich
So problem is, the values having space from text boxes also get replaced with the underscore sign replace(/\s+/g, "_"). So I get this output:
New_York_Jakarta_London,_Paris_Munich
But my expected output is this:
New York_Jakarta_London, Paris_Munich
I tried a different way that works but in this case all the text box values get concatenated:
var options = $("input[name*='txtOptions']");
var str = "";
$.each(options, function(i, item) {
str += $(item).val();
});
The problem with the above is, when I've different questions say question 1, question 2, it'll merge all the options to both of them. Though I want specific options for both questions.
Something like this?
//Add row to the table
$('#btnAddRow').on('click', function() {
var $clone = $('#tblQuesAns tbody tr:last').clone();
$clone.find('input').val('')
$('#tblQuesAns tbody').append($clone);
});
//Add more rows for option
$('body').on('click', '.addOptions', function() {
$(this).parent().append('<div><input class="txtOptions" type="text" /></div>');
});
//Get text box values
$('#btnGetValues').on('click', function() {
const allData = $('#tblQuesAns tbody tr').map(function() {
const $row = $(this),
question = $row.find('.txtQuestion').val(),
options = $row.find('.txtOptions').map(function() {
return this.value;
}).get().join("_");
return {question,options}
}).get()
const x = allData.map(item => `${item.question}_${item.options}`).join(" ")
console.log(x)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button id="btnAddRow" type="button">
Add Row
</button>
<button id="btnGetValues" type="button">
Get Values
</button>
<table id="tblQuesAns" border="1">
<thead>
<tr>
<th>Question</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input class="txtQuestion" value="Capital of England" />
</td>
<td>
<input class="txtOptions" value="London" />
<span class="addOptions">(+)</span>
</td>
</tr>
<tr>
<td>
<input class="txtQuestion" value="Current Pandemic" />
</td>
<td>
<input class="txtOptions" value="Corona" />
<span class="addOptions">(+)</span>
</td>
</tr>
</tbody>
</table>

how to increase button id when button clicks

I have a button, when click the button i need to increase the button id
This is my button
<input type="button" id="repeataddon-1" name="repeataddon"
class="repeataddon" value="add" >
and the script as
$(document).on( "click",'.repeataddon',function( ) {
hoteladdons();
alert(this.id);
});
can i use this code for my other table attributes which i want to increase their id as the same
<table width="100%" class="book-table" >
<tr>
<th>Addon Name</th>
<th>No of Addons</th>
<th>Rate</th>
<th>Addon Amount</th>
</tr>
<tr>
<td>
<article>
<span>
<?php echo $hoteladdon; ?>
</span>
</article>
</td>
<td>
<article>
<span>
<select class="noofaddons" name="noofaddons" id="noofaddons-1">
<?php
for($i=0;$i<5;$i++){
echo "<option value='$i'>".$i."</option>";
}
?>
</select>
</span>
</article>
</td>
<td><label id="addonprice-msg-1"></label> </td>
<td><label id="addontotal-msg-1"></label></td>
</tr>
</table>
Just like below
$(document).ready(function() {
$('.repeataddon').click(function() {
// hoteladdons();
var temp = $(this).attr('id').split('-');
$(this).attr('id', temp[0] + '-' + (parseInt(temp[1]) + 1));
console.log($(this).attr('id'));
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="repeataddon-1" name="repeataddon" class="repeataddon" value="add">
Here is what I did:
$(document).on("click", '.repeataddon, .noofaddons, .addonprice-msg, .addontotal-msg', function () {
var sp = $(this).attr('id').split("-");
if (isNaN(sp[sp.length - 1]) == false) {
$(this).attr('id', $(this).attr('id').split("-").slice(0, $(this).attr('id').split("-").length - 1).join("-") + '-' + (parseInt($(this).attr('id').split("-")[$(this).attr('id').split("-").length - 1]) + 1));
} else {
$(this).attr('id', $(this).attr('id') + '-1');
}
});
Here is the JSFiddle demo
Inspect element to see the change while you click on the button

multiple functions in javascript fail when in one file

I have been working on a webpage with some simple form validation and submit using javascript functions and ajax. I have written a function that validates a form and then submits it to another php page. I have then created a second form and validating/submitting javascript function. Both work separately, so I don't think it is my functions that are wrong, however when I try to put them into one js file to call them, only one of the functions works. I can remove the other re-upload it and it calls fine. I would appreciate it if someone could spot what I am doing wrong.
$(function () {
$('.error').hide();
});
function publication(){
$('.error').hide();
var title = $("input#title").val();
if (title == "") {
$("label#title_error").show();
$("label#title_error").css("color", "red");
$("input#title").focus();
return false;
}
var author = $("input#author").val();
if (author == "") {
$("label#author_error").show();
$("label#author_error").css("color", "red");
$("input#author").focus();
return false;
}
var publisher = $("input#publisher").val();
if (publisher == "") {
$("label#publisher_error").show();
$("label#publisher_error").css("color", "red");
$("input#publisher").focus();
return false;
}
var avail = $("input#avail").val();
if (avail == "") {
$("label#avail_error").show();
$("label#avail_error").css("color", "red");
$("input#avail").focus();
return false;
}
var info = $("textarea#info").val();
if (info == "") {
$("label#info_error").show();
$("label#info_error").css("color", "red");
$("textarea#info").focus();
return false;
}
var webaddr = $("input#webaddr").val();
var YYYY = $("input#YYYY").val();
var img = $("input#img").val();
var dataString = 'title='+ title + '&author=' + author + '&publisher=' + publisher + '&avail=' + avail + '&info=' + info + '&YYYY=' + YYYY + '&webaddr=' + webaddr + '&img=' + img;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "/includes/add_publication.php",
data: dataString,
success: function() {
$('#event_form').html("<div id='message'></div>");
$('#message').html("<h2>Publication Added</h2>")
.append("<p>The publication has been added to the database.</p>")
.hide()
.fadeIn(1500);
}
});
return false;
}
function events(){
$('.error').hide();
var eventname = $("input#eventname").val();
if (eventname == "") {
$("label#event_error").show();
$("label#event_error").css("color", "red");
$("input#eventname").focus();
return false;
}
var venue = $("input#venue").val();
if (venue == "") {
$("label#venue_error").show();
$("label#venue_error").css("color", "red");
$("input#venue").focus();
return false;
}
var info = $("textarea#info").val();
if (info == "") {
$("label#info_error").show();
$("label#info_error").css("color", "red");
$("textarea#info").focus();
return false;
}
var webaddr = $("input#webaddr").val();
var DD = $("input#DD").val();
var MM = $("input#MM").val();
var YYYY = $("input#YYYY").val();
var DD2 = $("input#DD2").val();
var MM2 = $("input#MM2").val();
var YYYY2 = $("input#YYYY2").val();
var img = $("input#img").val();
var dataString = 'eventname='+ eventname + '&venue=' + venue + '&info=' + info + '&webaddr=' + webaddr + '&DD=' + DD + '&MM=' + MM + '&YYYY=' + YYYY + '&DD2=' + DD2 + '&MM2=' + MM2 + '&YYYY2=' + YYYY2 + '&img=' + img;
//alert (eventString);return false;
$.ajax({
type: "POST",
url: "/includes/add_event.php",
data: dataString,
success: function() {
$('#event_form').html("<div id='message'></div>");
$('#message').html("<h2>Event Added</h2>")
.append("<p>The event has been added to the database.</p>")
.hide()
.fadeIn(1500);
}
});
return false;
}
The publication and events functions are called via click handlers in the HTML (here it's publication):
<table width="100%" id="publication">
<tr>
<td width="20%">Title:</td>
<td>
<input name="title" type="text" id="title" size="50" />
</td>
<td width="30%">
<label class="error" for="title" id="title_error">This field is required.</label>
</td>
</tr>
<tr>
<td colspan="2"></td>
</tr>
<tr>
<td>Author:</td>
<td>
<input name="author" type="text" id="author" size="50" />
</td>
<td>
<label class="error" for="author" id="author_error">This field is required.</label>
</td>
</tr>
<tr>
<td colspan="2"></td>
</tr>
<tr>
<td>Publisher:</td>
<td>
<input name="publisher" type="text" id="publisher" size="50" />
</td>
<td>
<label class="error" for="publisher" id="publisher_error">This field is required.</label>
</td>
</tr>
<tr>
<td colspan="2"></td>
</tr>
<tr>
<td>Publication Year:</td>
<td>
<input name="YYYY" type="text" id="YYYY" size="4" />
</td>
</tr>
<tr>
<td colspan="2"></td>
</tr>
<tr>
<td>Website:</td>
<td>http://
<input name="webaddr" type="text" id="webaddr" size="50" />
</td>
</tr>
<tr>
<td colspan="2"></td>
</tr>
<tr>
<td>Availability:</td>
<td>
<input name="avail" type="text" id="avail" size="30" />
</td>
<td>
<label class="error" for="avail" id="avail_error">This field is required.</label>
</td>
</tr>
<tr>
<td colspan="2"></td>
</tr>
<tr>
<td valign="top">Publication Information:</td>
<td>
<textarea rows="4" cols="50" name="info" id="info"></textarea>
</td>
<td>
<label class="error" for="info" id="info_error">This field is required.</label>
</td>
</tr>
<tr>
<td colspan="2"></td>
</tr>
<tr>
<td>Image Name:</td>
<td>
<input name="img" type="text" id="img" size="50" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="submit" class="button" id="pubs_btn" value="Add" onclick="publication()" />
</td>
</tr>
</table>
As you can hopefully see there are three things happening here. 1: all error messages are being hidden on page load, second and third are my two functions - publication and events. I have several verified fields which get given a rec error message if they are blank. I am then sending all the variables into a string to be submitted via ajax to a php file to insert them into my sql database.
I could be missing something as simple as a semi-colon somewhere - but as I have never written multiple functions in one file I haven't worked that out.
You have a syntax error:
var eventString = 'eventname='+ eventname + '&venue=' + venue + '&info=' + info '&webaddr' + webaddr + '&DD' + DD + '&MM' + MM + '&YYYY' + YYYY + '&DD2' + DD2 + '&MM2' + MM2 + '&YYYY2' + YYYY2 + '&img' + img;
// Here ------------------------------------------------------------------------^
This prevents your JavaScript from being correctly parsed, thereby preventing your code from being run when the click occurs.
Your web browser was telling you about this: If you open your web console or developer tools, you'll see the error listed.

Adding row to table with datepicker

I am trying to add row with button click in table(Add Row). I am trying to add 2 fields dynamically.
1) slno
2) Date/ Time.
My problems :
1) Row is not getting added.
2) How to assign datepicker to "Date /Time" field, added dynamically.
Jsfiddle is http://jsfiddle.net/RXzs7/12/
Pl help.
html code :
<script>
$(document).ready(function() {
$('.date').each(function() {
$(this).datepicker({ minDate:"-1m",maxDate:"0" });
});
});
</script>
<body>
<div id="lpage_container">
<div class="lform_container">
<h3>DETAILS OF LOCAL CONVEYANCE EXPENSES :</h3>
<form id="localexpenses" action="">
<table summary="local expense" id="localexpense_table" width="500" border="1">
<thead>
<tr>
<th width="1%" align="center"><strong>Sl.
No.</strong></th>
<th width="7%" align="center">
<strong>Date/Time</strong></th>
<th width="8%" align="center">
<strong>Remove</strong></th>
</tr>
</thead>
<tbody bgcolor="#CCCCCC">
<tr>
<td width="1%" align="center"><input type="text"
name="lsrno_00" id="srno_00" size="1" value="0"></td>
<td width="7%" align="center"><input type="text" class="date"
name="ldate_00" id="ldate_00" value="" size="8"></td>
<td> </td>
</tr>
</tbody>
</table>
<table summary="local buttons" width="500" border="1">
<tr>
<td align="right"><input type="button" value="Add Row"
id="add_ExpenseRowlocal">
</tr>
</table>
</form>
</div><!-- END subject_marks -->
<div class="clearfix"></div>
</div>
JS code :
$(function(){
// GET ID OF last row and increment it by one
var $lastChar =1, $newRow;
$get_lastID = function(){
var $id = $('#localexpense_table tr:last-child td:first-child input').attr("name");
$lastChar = parseInt($id.substr($id.length - 2), 10);
console.log('GET id: ' + $lastChar + ' | $id :'+$id);
$lastChar = $lastChar + 1;
$newRow = "<tr> \
<td><input type='text' name='lsrno_0"+$lastChar+"' value='0"+$lastChar+"' size='1'readonly /></td> \
<td><input type='text' class='date' name='ldate_0"+$lastChar+"' id='date_0"+$lastChar+"' size='8'/></td> \
<td><input type='button' value='Remove' class='del_ExpenseRowlocal' /></td> \
</tr>";
return $newRow;
};
// ***** -- START ADDING NEW ROWS
$('#add_ExpenseRowlocal').on("click", function(){
if($lastChar <= 9){
$get_lastID();
$('#localexpense_table tbody').append($newRow);
} else {
alert("Reached Maximum Rows!");
}
});
$(document).on("click", ".del_ExpenseRowlocal", function(){
$(this).closest('tr').remove();
$lastChar = $lastChar-2;
});
});
What jQuery version are you using? In your fiddle you have not added jQuery via the framework tab but under extenral resources you have two versions: 1.6.2 and 1.11.0. When I try and run it I get an error in the console that $().onis not a function. .on() came in jQuery 1.7 so if you are using 1.6.2 then you cannot use .on().
As for the date picker, when you run
$('.date').each(function() {
$(this).datepicker({ minDate:"-1m",maxDate:"0"
});
in your document ready you add a date picker to all field with class date which currently exist. You must add the date picker to the new date fields after you have added the row to the DOM. Something like
$('.date', $('#localexpense_table tbody tr').filter(':last')).each(function() {
$(this).datepicker({ minDate:"-1m",maxDate:"0" });
});
after your .append() call should work.
Working fiddle (needs some styles fixing for the added rows)

Categories

Resources