Insert only Checkbox Selected Row Values into a MySQL Table - javascript

Below JSFiddle link is that of a working form, where submitted form values from dynamic rows gets saved to a mysql table using ajax without any page refresh. The outcome of the form submission (i.e Success or Error) will be shown in a div which has an id 'results' using javascript.
JSFiddle Demo
Form Markup
<form name="names" id="names" method="post" action="">
<div class="container">
<div class="table-responsive">
<button type="button" class="btn btn-success addmore">Add</button>
<button type="button" class="btn btn-danger delete">Remove</button>
<br />
<table id="demo" class="table table-bordered table-condensed table-striped table-hover">
<thead>
<tr>
<th>
<input class="check_all" type="checkbox" onclick="select_all()" />
</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" class="case" />
</td>
<td>
<input class="form-control" type="text" name="fname[]" id="fname_1" required>
</td>
<td>
<input class="form-control" type="text" name="lname[]" id="lname_1" required>
</td>
</tr>
</tbody>
</table>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<div id="results"></div>
<div id="results2"></div>
</div>
<!-- ./table-responsive -->
</div>
Javascript for Add/Remove Table Rows, Checkbox Row(s) Selection
$(".delete").on('click', function() {
$('.case:checkbox:checked').parents("tr").remove();
$('.check_all').prop("checked", false);
check();
});
var i = $('table tr').length;
$(".addmore").on('click', function() {
count = $('table tr').length;
var data = "<tr><td><input type='checkbox' class='case'/></td>";
data += "<td><input class='form-control' id='fname_" + i + "' name='fname[]' required/></td>";
data += "<td><input class='form-control' id='lname_" + i + "' name='lname[]' required/></td></tr>";
//alert(data);
$('table').append(data);
row = i;
i++;
});
function select_all() {
$('input[class=case]:checkbox').each(function() {
if ($('input[class=check_all]:checkbox:checked').length == 0) {
$(this).prop("checked", false);
} else {
$(this).prop("checked", true);
}
});
}
function check() {
obj = $('table tr').find('span');
$.each(obj, function(key, value) {
id = value.id;
var selected = $('#' + id).html(key + 1);
});
}
Javascript for Form Submission using Ajax
// form submission through ajax
$(document).ready(function() {
$(function() {
$("#names").on("submit", function(e) {
e.preventDefault();
$.ajax({
type: "post",
url: "savename.php",
data: $(this).serialize(),
success: function(response) {
if (response == "Name creation successfull.") {
$("#results").html('<div class="alert alert-success"><button type="button" class="close">×</button>' + response + '</div><br>');
} else {
$("#results2").html('<div class="alert alert-success"><button type="button" class="close">×</button>' + response + '</div><br>');
}
//timing the alert box to close after 5 seconds
window.setTimeout(function() {
$(".alert").fadeTo(500, 0).slideUp(500, function() {
$(this).remove();
});
}, 2000);
//Adding a click event to the 'x' button to close immediately
$('.alert .close').on("click", function(e) {
$(this).parent().fadeTo(500, 0).slideUp(500);
});
$('#names')[0].reset();
},
error: function(response) {
alert(response);
}
});
});
});
});
What I like to implement is this,
User first selects the rows which he/she wants to insert into the mysql table by selecting the checkbox at the beginning of each row.
After selecting the rows, upon clicking the submit button only those selected row values should be inserted into the mysql table.
Tried to implement this by trying out the solutions from various posts similar to this one on this site but was not successful.

Used the solution provided by the user skobaljic (Thank you very much) in this stackoverflow post. Using this code now am able to post only those form values which are from the selected rows to a mysql table.
Updated JSFiddle Working Demo
Following line is for debugging purpose only, comment out after you are done.
$('.submit_data').text(toPost);
While the code works and gets the job done, am just a novice when it comes to javascript, so need expert opinion to mark this post as solved.

Related

How can append td in same row in table using jQuery

$(document).ready(function() {
$('.zk_btn').click(function(e) {
var pass_symbol= $('#' + lastid).val();
var split_id = lastid.split("_");
var nextindex = Number(split_id[1]) + 1;
$.ajax({
url:"record_count_3.php?pass_symbol=" + pass_symbol,
method:"POST",
success:function(data)
{
var json = JSON.parse(data);
var txt = '';
if(json.length > 0){
for(var i=0;i<json.length;i++){
txt = "<td>"+json[i].openrate+"</td><td>"+json[i].highrate+"</td><td>"+json[i].lowrate+"</td><td>"+json[i].closerate+"</td>";
$("#example > tbody > tr").append(txt);
}
$('#example > tbody').append('<tr class="txt_ '+ nextindex +'"><td><input type="text" id="txt_'+ nextindex +'" name="symbol" class="txtfield" /></td></tr> </tbody>');
}
$('.content').html(data);
}
})
});
});
I have a problem iam fetching data from ajax call and move in json varibale.when write symbol in input box and fetching records and display in 1st td,and append in new row. and another insert symbol and click submit button fetching the record and display in second td but problem second record display in first row and second row just like screen shot. mcb records display in 2nd row not in 1st row. please suggest my mistake
<table id='example' border='1' cellspacing='1' cellpadding='1' style='width:900px;' >
<thead>
<th> Marksymbol</th>
<th class='namecol '> Openrate</th>
<th class='namecol'> Highrate</th>
<th class='namecol'> Lowrate</th>
<th class='namecol'> Closerate</th>
</tr>
</thead>
<tbody>
<tr class ='txt_1'>
<td > <input type='text' name="symbol" id='txt_1' class='txtfield'/>
</td>
</tr>
</table>
<input type="button" id= "btnclick" class="zk_btn zk_btn_submit" name="submit1" value="SUBMIT"/>
It's working now
$('#example tr:last').closest('tr').append(txt);

Record deletion by selecting checkbox works fine on first page of Jquery datatables but not in second page

I am new to jquery datatables ,I tried may solution given in the stackoverflow but nothing works for me
So please suggest me what should i to according to my code(easy and simple solution with explanation).
Problem statement-
i implemented checkbox to delete the multiple records of table,
Jquery Datatable works fine on first page, when i click the check all checkbox on first page it checks all the check box of that page and delete the record but if i am in second page and click check all checkbox then it return to first page, also it will not delete the record if i select the records of two different pages
< script >
//Delete conformation message
/***************************/
//SelectAll checkBox
/****************************/
$(document).ready(function() {
$('#testtable').dataTable();
$('#checkall').click(function() {
if (this.checked) {
$('.delete_checkbox').each(function() {
this.checked = true;
$(this).closest('tr').addClass('removeRow');
});
} else {
$('.delete_checkbox').each(function() {
this.checked = false;
$(this).closest('tr').removeClass('removeRow');
});
}
});
/********************************/
//Select indivisual checkBox
/*******************************/
$('.delete_checkbox').click(function() {
if ($(this).is(':checked')) {
$(this).closest('tr').addClass('removeRow');
} else {
$(this).closest('tr').removeClass('removeRow');
}
});
/*******************************/
//Deletion of Data
/***********************************/
$('#delete_all').click(function() {
var checkbox = $('.delete_checkbox:checked').prop('checked', this.checked);;
if (checkbox.length > 0) {
var result = confirm("Are you sure");
if (result == true) {
var checkbox_valu = [];
$(checkbox).each(function() {
checkbox_valu.push($(this).val());
});
$.ajax({
url: "delete.php",
method: "POST",
data: {
checkbox_id: checkbox_valu
},
success: function() {
$('.removeRow').fadeOut(1500);
location.reload(true)
}
});
} else {
return false;
}
} else {
alert("Select atleast one records");
}
});
/******************************************/
});
<
/script>
<style>.removeRow {
background-color: #FF0000;
color: #FFFFFF;
}
</style>
<html>
<head>
<title>Delete Multiple Records using PHP Ajax with Animated Effect</title>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.4/css/jquery.dataTables.min.css">
</head>
<body>
<div class="container">
<br />
<div class="table-responsive">
<h3 align="center">Delete Multiple Records using PHP Ajax with Animated Effect</h3><br />
<div class="table-responsive">
<table id="testtable" class="table table-bordered">
<thead>
<tr>
<th width="10%">
<form method="post" action="">
<input type="checkbox" id="checkall" autocomplete="off" />
<button type="button" id="delete_all" class="btn btn-danger btn-xs">Delete</button>
</form>
</th>
<th width="20%">Name</th>
<th width="38%">Address</th>
<th width="7%">Gender</th>
<th width="25%">Designation</th>
<th width="5%">Age</th>
</tr>
</thead>
<?php
foreach($result as $row)
{
echo '
<tr>
<td>
<input type="checkbox" autocomplete="off" class="delete_checkbox" value="'.$row["id"].'" />
</td>
<td>'.$row["name"].'</td>
<td>'.$row["address"].'</td>
<td>'.$row["gender"].'</td>
<td>'.$row["designation"].'</td>
<td>'.$row["age"].'</td>
</tr>
';
}
?>
</table>
</div>
</div>
</div>
</body>
</html>
.
Your page is reloading because your table is inside a form element, and because your action does not have a target the page will just submit to itself. Try
$('#buttonId').click( function(event) {
event.preventDefault();
});
to stop the form submitting the page since you are handling it in JavaScript.
Your function to delete rows does not work on multiple pages because the elements on the other [DataTables] pages do not exist in the DOM. When you click page 2 or whatever, DataTables will redraw the table element to show the new values and the old values are hidden. Paging is just a limit of so many results and DataTables is smart enough to throw that into paging.

Validate form using Jquery with border and blur effects

I wish to validate a simple table form using jquery. So far I have a for loop that loops through all the fields and checks if they are empty. Then I have another for loop that checks to see if the age is within a certain range. And finally, the last loop checks to see if the email is in the correct RegEx pattern.
Currently only the first loop is working while the others are not being looped through. I have tried to do console.logs and it confirmed that the other loops are not being touched. Any ideas or help would be appreciated!
Semi working Code pen: https://codepen.io/anon/pen/ZXVmQz?editors=1010
Code:
HTML
<section class="container">
<div class="table table-responsive">
<table class="table table-responsive table-striped table-bordered" id="data-table">
<thead>
<tr>
<td>Name</td>
<td>Age</td>
<td>Email</td>
</tr>
</thead>
<tbody id="TextBoxContainer">
</tbody>
<tfoot>
<tr>
<th colspan="5">
<button id="btnAdd" type="button" class="btn btn-primary" data-toggle="tooltip" data-original-title="Add more controls"><i class="glyphicon glyphicon-plus-sign"></i> Add </button></th>
</tr>
</tfoot>
</table>
</div>
JQuery
function validate(input) {
var isValid;
var filter = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
var email = $('.email').val();
var length = $('.data').length;
console.log($('.email').val());
var rowInputLength = $("#TextBoxContainer input").length;
for (var i=0; i<rowInputLength; i++) {
if (!($(input[i]).val() == "" )) {
isValid = true;
validBorder($(input[i]));
if ($('input[type=number]') && !($(input[i]).val()<= 2 || $(input[i]).val() >= 100)) {
isValid = true;
console.log($('#age').val());
validBorder($(input[i]));
}
if ('$(input[i][type=email])' && filter.test(email)) {
isValid = true;
validBorder($(input[i]));
}
}
else {
isValid = false;
invalidBorder($(input[i]));
}
}
return isValid;
}
How the table is created
function GetDynamicTextBox(value1, value2, value3) {
return '<td><input name = "DynamicTextBox" id="name" type="text" value = "" placeholder = "' + value1 + '" class="form-control data" /></td>' +
'<td><input name = "DynamicTextBox" id="age" type="number" min="3" max="100" value = "" placeholder = "' + value2 + '" class="form-control data" /></td>' +
'<td><input name = "DynamicTextBox" id="email" type="email" value = "" placeholder="' + value3 + '" class="form-control data email" /></td>' +
'<td><button type="button" class="btn btn-danger remove"><i class="glyphicon glyphicon-remove-sign"></i></button><button type="button" class="btn btn-success edit"><i class="glyphicon glyphicon-ok"></i></button></td>';
}
When this button is pressed:
$(function () {
$("#btnAdd").bind("click", function () {
var div = $("<tr />");
div.html(GetDynamicTextBox("Enter Name", "Enter Age", "Enter Email"));
$("#TextBoxContainer").append(div);
$('#btnAdd').attr("disabled", "disabled");
$(".data").blur(function() {
validate($(this))
});
});
});
You lacked the relevant piece of code in the question, had to find it in your pen.
In your anonymous "Add Row" function you need to call validation with all of the input fields, using the selector you attempted to use can be done like so:
validate( $( ".data" ) )
Also other issues found in validate method: $(input[i]).val() is a string, convert it to a number using prefix +, +$(input[i]).val()

how to search a user in a bootstrap table of users?

I'm developing an application for users management with spring mvc. I'm using this bootstrap table in my jsppage which make me do a research on the data in the table .
In my table the data of users is retreived from database . this is the code :
<div class="col-md-9">
<form action="#" method="get">
<div class="input-group">
<!-- USE TWITTER TYPEAHEAD JSON WITH API TO SEARCH -->
<input class="form-control" id="system-search" name="q"
placeholder="Search for" required> <span
class="input-group-btn">
<button type="submit" class="btn btn-default">
<i class="glyphicon glyphicon-search"></i>
</button>
</span>
</div>
</form>
<table class="table table-list-search">
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>Surname</th>
<th>email</th>
<th>contact</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<c:forEach items="${listUsers}" var="user">
<tbody>
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.surname}</td>
<td>${user.email}</td>
<td>${user.contact}</td>
<td>
<p data-placement="top" data-toggle="tooltip" title="Edit">
<button class="btn btn-primary btn-xs" data-title="Edit"
data-toggle="modal"
onclick="location.href='<c:url value="/modifier/${user.id}" />'">
<span class="glyphicon glyphicon-pencil"></span>
</button>
</p>
</td>
<td>
<p data-placement="top" data-toggle="tooltip" title="Delete">
<button class="btn btn-danger btn-xs" data-title="delete"
data-delete='${user.id}' data-toggle="modal"
data-target="#confirm-delete" data-href="/supprimer/${user.id}">
<span class="glyphicon glyphicon-trash"></span>
</button>
</p>
</td>
</tr>
</tbody>
</c:forEach>
</table>
</div>
and this is the script which do the research on the table :
$(document).ready(function() {
var activeSystemClass = $('.list-group-item.active');
//something is entered in search form
$('#system-search')
.keyup(function() {
var that = this;
// affect all table rows on in systems table
var tableBody = $('.table-list-search tbody');
var tableRowsClass = $('.table-list-search tbody tr');
$('.search-sf').remove();
tableRowsClass
.each(function(i, val) {
//Lower text for case insensitive
var rowText = $(val).text().toLowerCase();
var inputText = $(that).val().toLowerCase();
if (inputText != '') {
$('.search-query-sf').remove();
tableBody
.prepend('<tr class="search-query-sf"><td colspan="6"><strong>Searching for: "'
+ $(that).val()
+ '"</strong></td></tr>');
} else {
$('.search-query-sf').remove();
}
if (rowText.indexOf(inputText) == -1) {
//hide rows
tableRowsClass.eq(i).hide();
} else {
$('.search-sf').remove();
tableRowsClass.eq(i).show();
}
});
//all tr elements are hidden
if (tableRowsClass.children(':visible').length == 0) {
tableBody.append('<tr class="search-sf"><td class="text-muted" colspan="6">No entries found.</td></tr>');
}
});
});
but when I've changed to dynamic table I have this result which make the word searching for : repeated n times !
I tried to change the code of the script but I failed to have the right script.
could some one help me please ?
It looks like this might be the problem
tableRowsClass.each(function(i, val) {
//Lower text for case insensitive
var rowText = $(val).text().toLowerCase();
var inputText = $(that).val().toLowerCase();
if (inputText != '') {
$('.search-query-sf').remove();
tableBody.prepend('<tr class="search-query-sf"><td colspan="6"><strong>Searching for: "'+ $(that).val()+ '"</strong></td></tr>');
.each means that you're adding <tr class="search-query-sf"><td colspan="6"><strong>Searching for: "'+ $(that).val()+ '"</strong></td></tr> to the start (because it's prepend) of your table, one for every element using .table-list-search tbody tr
try just moving tableBody.prepend('<tr class="search-query-sf"><td colspan="6"><strong>Searching for: "'+ $(that).val()+ '"</strong></td></tr>'); outside of the .each() so that it only runs once.
I echo Jamie's answer, but I'd do a bit more refactoring.
I would move the searching out into its own function and pass the required rows collection and search string into it.
I would also move the check for search text outside the each loop, because the value is available outside the loop and doesn't change.
$(document).ready(function() {
var activeSystemClass = $('.list-group-item.active');
var searchTable = function(rows, searchStr){
var searching = false;
rows.each(function(i, val){
var rowText = $(val).text().toLowerCase();
if (rowText.indexOf(searchStr) == -1) {
//hide rows
rows.eq(i).hide();
} else {
$('.search-sf').remove();
rows.eq(i).show();
}
if (rows.children(':visible').length == 0) {
tableBody.append('<tr class="search-sf"><td class="text-muted" colspan="6">No entries found.</td></tr>');
}
}
};
//something is entered in search form
$('#system-search')
.keyup(function() {
var that = this;
// affect all table rows on in systems table
var tableBody = $('.table-list-search tbody');
var tableRowsClass = $('.table-list-search tbody tr');
var inputText = $(that).val();
$('.search-sf').remove();
if (inputText != ''){
$('.search-query-sf').remove();
searchTable(tableRowsClass, inputText.toLowerCase())
tableBody.prepend('<tr class="search-query-sf"><td colspan="6"><strong>Searching for: "' + inputText + '"</strong></td></tr>');
}
});
});
An alternative to using javascript to create the repeating table row could be to use the hidden attribute and use javascript to remove that attribute whenever the .keyup event fires. You can then use javascript to set the value of a span tag with the search query. I couldn't get this example to work on jsFiddle or plunker, but i made an example. (this is pure raw JS with no styling)
<head>
<script type="text/javascript">
function doSearch(){
document.getElementById("searchingForRow").removeAttribute("hidden");
document.getElementById("searching").innerHTML = document.getElementById("system-search").value
}
</script>
</head>
<body>
<div class="col-md-9">
<div class="input-group">
<form>
<div>
<input id="system-search" placeholder="Search for" >
<button type="submit" class="btn btn-default" onclick="doSearch()">
Search
</button>
</div>
</form>
</div>
<table>
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>Surname</th>
<th>email</th>
<th>contact</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tr class="search-query-sf" id="searchingForRow" hidden>
<td colspan="6"><strong>Searching for: <span id="searching"></span></strong></td>
</tr>
<tbody>
<tr>
<td>An Example data this does nothing</td>
</tr>
</tbody>
</table>
this example, when the search button is clicked, removed the hidden attribute, making that row visible, and set's the span in the row to the value of the textbox.
it's essentially what you are trying to do.
with this method, it doesn't matter how many times the code to remove the hidden attribute is called, nothing will render more than once.

Display ajax response in Table

display.html :
<div id="display_result" style="display: none"><table class="table">
<p style="float: right;" >Select All<input type="checkbox" class="allcb" data-child="chk" checked/> </p>
<thead>
<tr>
<th>Die No</th>
<th> Status </th>
<th> Location </th>
<th>Select</th>
</tr>
</thead>
<tbody>
</table>
<div id ="issue_button">
<input type="submit" id="submit" class="btn btn-success " value="Recieve" style="width: 150px;"></div>
</div>
Ajax:
var data = JSON.stringify($("#form").serializeArray());
// alert(data);
$.ajax({ // Send the credential values to another checker.php using Ajax in POST menthod
type: 'POST',
data: {
list: data
},
url: 'die_recieving_process.php',
success: function(data) ){
$('#display_result').html(data);
}
});
die_recieving_process.php
while($fetch = mysql_fetch_array($query))
{
if($fetch[1] == "Table Rack" )
{
echo '<tr class="success"><td>'.$fetch[0].'</td><td>'.$fetch[1].'</td><td>'.$fetch[3] . '</td> <td><input type=checkbox class="chk" id=check_box value= '.$fetch[2].' name= check_list[] </td> </tr>';
}
else
{
echo '<tr class="warning"><td>'.$fetch[0].'</td><td>'.$fetch[1].'</td><td>'.$fetch[3] . '</td> <td><input type=checkbox class="chk" id=check_box value= '.$fetch[2].' name= check_list[] checked </td> </tr>';
}
}
Hi friends in display.html I have to display the result processed in die_recieving_process.php . In ajax i've sent all the value to die_recieving_process.php and after fetching the result i've to display the result in display.html
First in you Javascript, you have 2 errors:
Your code overrides existing contents of div, which is the whole table...
And you have one unnecessary bracket in success function declaration
So change this:
success: function(data) ){
$('#display_result').html(data);
}
To this:
success: function(data) {//remove unnecessary bracket
$('#display_result tbody').html(data);//add data - to tbody, and not to the div
}
By the way, using $.post() you can write your javascript code shorter, like this:
var data = JSON.stringify($("#form").serializeArray());
$.post('die_recieving_process.php',{list:data},function(responseData){
$('#display_result tbody').html(responseData); //added to tbody which is inside #display_result
$('#display_result').show();
});
Second you need to close your tbody tag inside the table
Create html table with empty body tags and body id = tBody for example:
<table>
<caption>Smaple Data Table</caption>
<thead>
<tr>
<th>Field 1</th>
<th>Field 2</th>
</tr>
</thead>
<tbody id="tBody"></tbody>
</table>
Use the jquery ajax to load json data in the created table after load button is clicked assuming that my json file is storing userData like userName, age, city:
$('#btnLoadAll').click(function () {
$.ajax({
url: "url/data.json",
dataType: 'json',
success: function (resp) {
var trHTML = '';
$.each(resp, function (i, userData) {
trHTML +=
'<tr><td>'
+ userData.userName
+ '</td><td>'
+ userData.age
+ '</td><td>'
+ userData.city
+ '</td></tr>';
});
$('#tBody').append(trHTML);
},
error: function (err) {
let error = `Ajax error: ${err.status} - ${err.statusText}`;
console.log(error);
}
})
});
If you do not see result, try to remove style="display: none" in display.html

Categories