how to retrieve data from indexeddb and show in a div - javascript

I have created a function readAll() which is fetching data into the todos div but it is not showing data on the click function but it is not working data is adding successfully in the index db but it is not showing. Now I first i have empty the table after that I just have append the data into the html from the javascript.
function readAll() {
var objectStore = db.transaction("todostore").objectStore("todostore");
$("#todos").empty();
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
$("#todos").append("<tr><td>" + cursor.key + "</td><td>" + cursor.value.todo + "</td><td><button onclick=\"update('" + cursor.key + "','" + cursor.value.todo + "')\">Update</button></td><td><button onclick=\"removetodo('" + cursor.key + "','" + cursor.value.todo + "')\">Delete</button></td></tr>");
cursor.continue();
}
};
};
now I am calling the function on the click I am just calling the readAll Function
$(".clickme").click(function(){
readAll();
});
I have created a div of id view inside the div i have use a table head now I am just appending the code from the JavaScript and populate into the html
<div id="view">
<thead>
<tr class="ui-bar-d">
<th data-priority="2">Timestamp</th>
<th data-priority="1">To Do</th>
<th data-priority="3">Update</th>
<th data-priority="4">Delete</th>
</tr>
</thead>
<tbody id="todos">
</tbody>
</table>
</div>
<label for="todo">To Do:</label>
<input id="todo" type="text">
<input id="toprice" type="text">
<button class="clickme">clickme</button>
<button class="ui-shadow ui-btn ui-corner-all" onclick="add()">Add</button>

As IDB is async.You will need to call you're function in ....
transaction.oncomplete = function(event) {
$(".clickme").click(function(){
readAll();
});
};
https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction/oncomplete

Related

add dynamic order to add remove html input field

i have this code for add/remove dynamic input:
JS:
$(function () {
$("#btnAdd").bind("click", function () {
var div = $("<tr />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$("body").on("click", ".remove", function () {
$(this).closest("tr").remove();
});
});
function GetDynamicTextBox(value) {
var number = Math.random();
return '<td id="' + number + '"><input name = "DynamicTextBox" type="text" value = "' + value + '" class="form-control" /></td>' + '<td><select name="" class="form-control"><option> Select</option><option> Male</option><option> Female</option></select></td>' + '<td><input name = "DynamicTextBox" type="radio" value = "' + value + '" /></td>' + '<td><input name = "DynamicTextBox" type="checkbox" value = "' + value + '" /></td>'+'<td><input name = "order" type="number" value = "" /></td>' + '<td><button type="button" class="btn btn-danger remove"><i class="fas fa-times"></i></button></td>'
}
HTML:
<p> </p>
<h5 class="text-center">Dynamic Control : Text Box, Dropdown List, Radiobox and Checkbox</h5>
<section class="container">
<div class="table table-responsive">
<table class="table table-responsive table-striped table-bordered">
<thead>
<tr>
<td>TextBox</td>
<td>Dropdown List</td>
<td>Radio</td>
<td>CheckBox</td>
<td>Order</td>
<td>BTN</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="fas fa-plus"></i> Add </button></th>
</tr>
</tfoot>
</table>
</div>
</section>
this code work true for me but how do can i add dynamic order(from 1 to ...) for each row(td). my mean add order input from number 1 and add +1 number from last order number.
demo is here
update: (my need)
You need to just modify the JS code logic. The below example shows the use of variable count and its usage.
Here, the variable count is declared as 1 initially and as per the "Add" click the count value has been incremented by 1. Same way the count is been decremented by 1 when we are deleting/removing the the "tr" column.
$(function () {
var count = 1;
$("#btnAdd").bind("click", function () {
var div = $("<tr />");
div.html(GetDynamicTextBox("", count));
$("#TextBoxContainer").append(div);
count++;
});
$("body").on("click", ".remove", function () {
$(this).closest("tr").remove();
count--;
});
});
The click function will have one more argument count which is used for the rendering/displaying of the count value in the order field.
function GetDynamicTextBox(value, count) {
var number = Math.random();
return '<td id="' + number + '">
<input name = "DynamicTextBox" type="text" value = "' + value + '" class="form-control" />
</td>' + '
<td>
<select name="" class="form-control">
<option> Select</option>
<option> Male</option>
<option> Female</option>
</select>
</td>' + '
<td>
<input name = "DynamicTextBox" type="radio" value = "' + value + '" />
</td>' + '
<td>
<input name = "DynamicTextBox" type="checkbox" value = "' + value + '" />
</td>'+'
<td>
<input name = "order" type="number" value = "' + count + '" /></td>' + '
<td>
<button type="button" class="btn btn-danger remove"><i class="glyphicon glyphicon-remove-sign"></i></button>
</td>'
}
The above code works when we are removing the row from the last column.
If you are removing in-between the row from the list of tr tags you will find the order columns values are not arranged properly.
The below code is used for the removing the tr tag in-between the row and as well as the from the last tr tag. This code will be flexible for removing the tr row from anywhere in the list as well as updating the order row in the incremental way.
$("body").on("click", ".remove", function () {
var deleteElement = $(this).closest("tr");
var countOfDeleteElement = $(deleteElement).find("#order").val();
var lastElementCount = count - 1;
if (countOfDeleteElement !== lastElementCount) {
// It will come inside this if block when we are removing inbetween element.
var remainingElements = deleteElement.nextAll('tr'); // get all the below elemnts from the removing element.
// updating all remainingElements value of the order column
remainingElements.each((i, ele) => {
$(ele).find("#order").val(countOfDeleteElement);
countOfDeleteElement++;
})
}
deleteElement.remove();
count--;
});

How to edit and update values in a dynamic table using JQuery?

Below is code for adding inputs into a dynamic table and for each row an edit button is also generated, my question is how would I pass the values in the table back into the input fields when I click on the edit button of a specific row and then update the specific row based on the changes made to the values in the input fields when i click on the update row button.
$("#btnAdd").on('click', function() {
let row = '<tr> <td>' + $("#insert-name").val() + '</td> <td>' + $("#insert-surname").val() + '</td> <td>' + "edit" + '</td> </tr>'
$('tbody').append(row);
$('td:contains("edit")').html("<button type='button'>" + "edit" + "</button>").on('click', function() {
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div>
<label for="insert-name">Name:</label>
<input type="text" id="insert-name">
</div>
<div>
<label for="insert-surname">Surname:</label>
<input type="text" id="insert-surname">
</div>
</form>
<button type="button" id="btnAdd">Add to Table</button>
<button type="button" id="btnUpdate">Update row</button>
<table>
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Surname</th>
<th scope="col">Edit</th>
</tr>
</thead>
<tbody id="tbody"></tbody>
</table>
Check this (Read JS comments)
$("#btnAdd").on('click', function() {
let row = '<tr> <td>' + $("#insert-name").val() + '</td> <td>' + $("#insert-surname").val() + '</td> <td>' + "edit" + '</td> </tr>'
$('tbody').append(row);
$('td:contains("edit")').html("<button type='button' class='edit'>" + "edit" + "</button>").on('click', function() {
});
});
//--------------------------------------------------------//
$(document).on("click",".edit",function(){ // Click function on class '.edit' (your appended button)
var name = $(this).parents("tr").find("td:eq(0)").html(); // Search for 'name' depending on this edit button parent.
var surname = $(this).parents("tr").find("td:eq(1)").html(); // Search for 'surname' depending on this edit button parent.
var rowNumber = $(this).parents("tr").index() // Get index of this edit button parent 'row'.
$("#edit-name").val(name); // Read the name and put it in '#edit-name' inside '.editArea'.
$("#edit-surname").val(surname); // Read the surname and put it in '#edit-surname' inside '.editArea'.
$(".saveEdits").attr("for",rowNumber); // Store this row index as attribute in '.saveEdits' button to be able to pass it to the other function that saves data.
$(".editArea").fadeIn(300); // Show the edit box.
});
$(".saveEdits").click(function(){ // Function to save data
var rowNumber = parseInt($(this).attr("for")); // Get the row number that we already define in the prev. function.
$('td:eq(0)','tr:eq('+(rowNumber+1)+')').html($("#edit-name").val()); // Update 'td' content depending on the 'tr' index.
$('td:eq(1)','tr:eq('+(rowNumber+1)+')').html($("#edit-surname").val()); // Update 'td' content depending on the 'tr' index.
});
$(".cancel").click(function(){ // Button to cancel edit.
$("#edit-name").val(""); // Empty value.
$("#edit-surname").val(""); // Empty value.
$(".saveEdits").attr("for","0"); // Set row number to zero.
$(".editArea").fadeOut(300); // Hide edit area.
});
.editArea{
display:none;
background:#fff;
padding:10px;
border:1px solid #ddd;
border-radius:5px;
box-shadow:0 0 0 #000;
width:50%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form>
<div>
<label for="insert-name">Name:</label>
<input type="text" id="insert-name">
</div>
<div>
<label for="insert-surname">Surname:</label>
<input type="text" id="insert-surname">
</div>
</form>
<button type="button" id="btnAdd">
Add to Table
</button>
<table>
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Surname</th>
<th scope="col">Edit</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
<div class='editArea'>
<label>Name</label>
<input type="text" id="edit-name">
<br>
<label>Surname</label>
<input type="text" id="edit-surname">
<hr>
<button class='saveEdits' for="0">Save edits</button>
<button class='cancel'>Cancel</button>
</div>
</body>
</html>
Here is a solution with edit row in just within existent inputs
var counter = 0;
var current_row = null;
$("#btnAdd").on('click', function() {
if (current_row == null) {
if ( $("#insert-surname").val().length && $("#insert-name").val().length ) {
let row = '<tr data-row="'+counter+'"> <td>' + $("#insert-name").val() + '</td> <td>' + $("#insert-surname").val() + '</td> <td>' + "edit" + '</td> </tr>'
$('tbody').append(row);
counter++;
}
} else {
var select_row = $('tr[data-row='+current_row+']');
let cells = $(select_row).find('td');
$(cells[0]).text($("#insert-name").val());
$(cells[1]).text($("#insert-surname").val());
}
clear_input();
$('td:contains("edit")').html("<button type='button'>" + "edit" + "</button>").on('click', function() {
let cells = $(this).parents('tr').find('td');
$("#insert-name").val($(cells[0]).text());
$("#insert-surname").val($(cells[1]).text());
current_row = $(this).parents('tr').data('row');
});
});
$('#btnCancel').on("click", () => clear_input());
function clear_input() {
current_row = null;
$("#insert-name").val('');
$("#insert-surname").val('');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div>
<label for="insert-name">Name:</label>
<input type="text" id="insert-name">
</div>
<div>
<label for="insert-surname">Surname:</label>
<input type="text" id="insert-surname">
</div>
</form>
<button type="button" id="btnAdd">Add to Table</button>
<button type="button" id="btnCancel">Cancel</button>
<table id='data-table'>
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Surname</th>
<th scope="col">Edit</th>
</tr>
</thead>
<tbody id="tbody"></tbody>
</table>
Now let's begin with what wrong with the OP's solution. OP is trying to add event listner to an element which hasn't been created yet. The way we listen to dynamic data is through event delegation.
So for this:
<tbody>
// dynamic <tr></tr>
</tbody>
We would attach our listener to some parent of it (not necessarily the closest parent) i.e., <tbody> in this case which is part of the dom when we run our js code.
I'm sure that there are various ways of doing it, but I gave it a shot by sticking close to your actual solution. Check it out:
function addToTable() {
// insertion into row
let name = $("#insert-name").val();
let surname = $("#insert-surname").val();
let row = `<tr>
<td>${name}</td>
<td>${surname}</td>
<td><button>Edit</button></td>
</tr>`;
$('#tbody').append(row);
// clearing input fields
$("#insert-name").val("");
$("#insert-surname").val("");
}
function editTable() {
let name = $("#insert-name").val();
let surname = $("#insert-surname").val();
// looking for tr with "active" class
let row = $("#tbody tr.active");
let rowArr = row[0].children;
rowArr[0].innerHTML = name;
rowArr[1].innerHTML = surname;
row[0].classList.remove("active");
// clearing input fields
$("#insert-name").val("");
$("#insert-surname").val("");
}
$("#btnAdd").on('click', function() {
let isEdit = $("#btnAdd").hasClass("edit");
if (isEdit) {
editTable();
} else {
addToTable();
}
// remove class "edit"
$("tbody").removeClass("edit");
});
// Adding event listner to the parent (event delegation)
$("#tbody").on('click', function(e) {
$("#btnAdd").addClass("edit");
// pass table data to input fields
let row = e.target.closest("tr");
row.classList.add("active");
let rowArr = row.children;
$("#insert-name").val(rowArr[0].innerHTML);
$("#insert-surname").val(rowArr[1].innerHTML);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form>
<div>
<label for="insert-name">Name:</label>
<input type="text" id="insert-name">
</div>
<div>
<label for="insert-surname">Surname:</label>
<input type="text" id="insert-surname">
</div>
</form>
<button type="button" id="btnAdd">
Add to Table
</button>
<table>
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Surname</th>
<th scope="col">Edit</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>

Get details of Peoplepicker field from another list in Sharepoint 2013

I am having a functionality in a custome form where if I select a Resource name (people picker column), the remaining EmpID,
Projects and Manager columns has to filled. All these columns are in a list named "EmpDetails".
I tried using CAML query but couldn't succed. This is my code:
<tr class="container">
<div id="container">
<table id="table">
<thead>
<tr>
<th>Resource Name</th>
<th>EmpID</th>
<th>Projects</th>
<th>Manager</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><span id="resourcename"></span></td>
<td><input type="text" id="txtempid" placeholder="Emp ID"/></td>
<td><input type="text" id="txtprojects" placeholder="Projects"/></td>
<td><input type="text" id="txtreportmgr" placeholder="Reporting Manager"/></td>
<td><input type="button" id="delrow" value="-" onclick="deleteRow(this)"/> </td>
<td><input type="button" id="addrow" value="+" onclick="addRow()"/> </td>
</tr>
</tbody>
</table>
</div>
</tr>
Javascript code:
$( document ).ready(function() {
ConvertoToRequestPeoplePicker('resourcename');
BindData();
});
function BindData()
{
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
context = new SP.ClientContext.get_current();
LoadingMessage();
SPLoaded();
});
}
function SPLoaded()
{
try
{
var resourceInfoList = context.get_web().get_lists().getByTitle('EmpDetails');
var resourceInfoQuery = new SP.CamlQuery();
resourceInfoQuery.set_viewXml( '<View>' +
'<ViewFields>' +
'<FieldRef Name=\'EmpID\' />' +
'<FieldRef Name=\'Projects\' />' +
'<FieldRef Name=\'Manager\' />' +
'</ViewFields>' +
'<Query>' +
'<Where>' +
'<Value Type="User">' + itm.get_item("Employee").get_lookupId() + '</Value>'+
'</Where>' +
'<OrderBy>' +
'<FieldRef Name="Title" Ascending="TRUE" />' +
'</OrderBy>' +
'</Query>' +
'</View>');
var resourceInfoListItems = resourceInfoList.getItems(resourceInfoQuery);
context.load(resourceInfoListItems);
context.executeQueryAsync(Function.createDelegate(null, LoadConfigurationValues), Function.createDelegate(this, function (sender, arg) { alert("Error in getLoginUser : " + arg.get_message()); waitDialogLoad.close(SP.UI.DialogResult.OK); }));
}
catch(ex)
{
alert("Something went wrong : "+ex.message);
waitDialogLoad.close(SP.UI.DialogResult.OK);
}
}
I am beginner in SharePoint and got the above code from some site. I couldn't whether this is correct code or no. Please help.
It seems that your CAML-query isn't valid...
the 'Where'-part of such a query must be formed like:
<Where>
<compareOperator>
<Value/>
<FieldRef/>
</compareOperator>
</Where>
the compareOperator is usually something like "Eq", "Lt" etc.
the value usually gets a type attribute and the fieldref is defining which field in a list (or library) item should be compared to the value in the query.
putting all that together we get an example like:
<View>
<Query>
<Where>
<Geq>
<FieldRef Name='ID'/>
<Value Type='Number'>1</Value>/Geq>
</Where>
</Query>
</View>
For a more in-depth look you can check out the sp jsom how-to ;>

HTML table with editable fields accessed in javascript.

I am trying to build a table that will allow users to change the value of a cell(s) and then "submit" that data
to a JavaScript (only please) method that turns the tables data into a json dataset.
I started by trying to updated the value of just one field. QTY in this case. I am able to loop over the table and get the static values, but I am not able to catch the user input value.
question: What is a JavaScript only (if possible) way to capture user change(able) values from a table?
function updateQTY() {
//getData from table
//gets table
var lines = "";
var oTable = document.getElementById('items');
//gets rows of table
var rowLength = oTable.rows.length;
var line = "";
//loops through rows, skips firts row/header
for (i = 1; i < rowLength; i++) {
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
var qty = oCells.item(2).innerHTML;
//alert("qty: " + wty);
qty = qty.substr(oCells.item(2).innerHTML.indexOf('value=') + 7);
qty = qty.substr(0, qty.indexOf('" class='));
//alert(qty);
line = line +
'{ "item": "' + oCells.item(0).innerHTML + '",' +
' "discription": "' + oCells.item(1).innerHTML + '",' +
' "qty": "' + qty + '"},'
}
//alert(line);
var jsonData = JSON.parse('[' + line + '{"quickwayto":"dealwith,leftbyloop"}]');
alert("lines: " + JSON.stringify(jsonData));
}
<form action='#'>
<table class='mdl-data-table mdl-js-data-table' id='items'>
<thead>
<tr>
<th>item</th>
<th>discription</th>
<th>QTY</th>
</tr>
</thead>
<tbody>
<tr>
<td class='mdl-data-table__cell--non-numeric'> widget_1 </td>
<td class='mdl-data-table__cell--non-numeric'>it's fun</td>
<td>
<div class='mdl-textfield mdl-js-textfield'><input type='text' name='qty1' id='value1' value='5' class='mdl-textfield__input'></div>
</td>
</tr>
<tr>
<td class='mdl-data-table__cell--non-numeric'> widget_2 </td>
<td class='mdl-data-table__cell--non-numeric'>it's super fun</td>
<td>
<div class='mdl-textfield mdl-js-textfield'><input type='text' name='qty2' id='value2' value='5' class='mdl-textfield__input'></div>
</td>
</tr>
</tbody>
</table>
<div>
<input type='button' value='update' onclick='updateQTY()' class='mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect'>
</div>
</form>
THANK YOU
Instead of selecting the entire td element, retrieve only what you really need using querySelector (or use jQuery if possible). Find the input element and access the value, it's a lot easier than doing all of that unecessary parsing of the inner html of the entire cell.
function updateQTY() {
//getData from table
//gets table
var lines = "";
var oTable = document.getElementById('items');
//gets rows of table
var rowLength = oTable.rows.length;
var line = "";
//loops through rows, skips firts row/header
for (i = 1; i < rowLength; i++) {
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
var qty = oCells.item(2).querySelector(".mdl-textfield__input").value;
line = line +
'{ "item": "' + oCells.item(0).innerHTML + '",' +
' "discription": "' + oCells.item(1).innerHTML + '",' +
' "qty": "' + qty + '"},'
}
//alert(line);
var jsonData = JSON.parse('[' + line + '{"quickwayto":"dealwith,leftbyloop"}]');
alert("lines: " + JSON.stringify(jsonData));
}
<form action='#'>
<table class='mdl-data-table mdl-js-data-table' id='items'>
<thead>
<tr>
<th>item</th>
<th>discription</th>
<th>QTY</th>
</tr>
</thead>
<tbody>
<tr>
<td class='mdl-data-table__cell--non-numeric'> widget_1 </td>
<td class='mdl-data-table__cell--non-numeric'>it's fun</td>
<td>
<div class='mdl-textfield mdl-js-textfield'><input type='text' name='qty1' id='value1' value='5' class='mdl-textfield__input'></div>
</td>
</tr>
<tr>
<td class='mdl-data-table__cell--non-numeric'> widget_2 </td>
<td class='mdl-data-table__cell--non-numeric'>it's super fun</td>
<td>
<div class='mdl-textfield mdl-js-textfield'><input type='text' name='qty2' id='value2' value='5' class='mdl-textfield__input'></div>
</td>
</tr>
</tbody>
</table>
<div>
<input type='button' value='update' onclick='updateQTY()' class='mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect'>
</div>
</form>
You need to use document.getElementById('value2').value instead of .innerHTML.indexOf('value=')
You're making yourself a lot of work here. You have a table. All you need to do is convert that to JSON. I would suggest you look at the library below that does that in around one line of native java-script.
http://www.developerdan.com/table-to-json/

How to get checked checkbox table value in jquery

In my table I have 2 rows please see my screen shot,suppose I click first check box means I want to take that id ** and **to_area value in jquery how can do this,I tried but I can not get please help some one
$(document).ready(function() {
$('#chemist_allotment_btn').click(function() {
if ($('#chemist_allotment_form').valid()) {
$.ajax({
url: 'update_chemist_bulk_transfer.php',
type: 'POST',
data: $('form#chemist_allotment_form').serialize(),
success: function(data) {
var res = jQuery.parseJSON(data); // convert the json
console.log(res);
if (res['status'] == 1) {
var htmlString = '';
$.each(res['data'], function(key, value) {
htmlString += '<tr>';
htmlString += ' <td class="sorting_1"><div class="checkbox-custom checkbox-success"><input type="checkbox" id="checkboxExample3" name="getchemist" class="getchemist" value="' + value.id + '"><label for="checkboxExample3"></label></div></td>';
htmlString += '<td>' + value.id + '</td>';
htmlString += '<td>' + value.name + '</td>';
htmlString += '<td>' + value.area + '</td>';
htmlString += '<td>' + value.to_area + '</td>';
htmlString += '<td>' + value.address + '</td>';
htmlString += '</tr>';
});
$('#SampleDT tbody').empty().append(htmlString);
$('#get_to_area').click(function() {
var id = $('input[name=getchemist]:checked').val();
if ($(".getchemist").prop('checked') == true) {
alert(id);
alert(value.to_area);
} else {
alert('Please Check');
}
});
} else {
$('#SampleDT tbody').empty().append('No Datas Found');
}
},
});
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="well white">
<table id="SampleDT" class="datatable table table-hover table-striped table-bordered tc-table">
<thead>
<tr>
<th>Select</th>
<th>Id</th>
<th>Doctor Name</th>
<th>From Area</th>
<th>To Area</th>
<th>Address</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<center>
<div class="form-group">
<button type="button" class="btn btn-primary" style="text-align:left;" id="get_to_area">Transfer Area</button>
</div>
</center>
</div>
Firstly, add classes to each <td>, like <td class='id'>[Your id]</td>
Similarly for all the elements doctor-name, to-area, etc and a class to each <tr> like row-select
Somewhat like this:
<tr class="row-select">
<td class="select">...</td>
<td class="id">...</td>
<td class="to-area">...</td>
.
.
.
</tr>
Use jQuery like this:
$('.row-select').click(function(){
var id,toArea,checkBox;
id = $(this).find('.id').html(); //get the ID field
toArea = $(this).find('.to-area').html(); //get the to-area field
checkBox = $(this).find('.select > input');
checkbox.prop('checked',!checkbox.prop('checked'));
})
This code will get you he value no mater where you click on the row, and also invert the selection on the checkbox
To get the values of rows selected when the form is submitted run a loop like this
$('.row-select input:checked').each(function(){
var id,toArea,checkBox;
id = $(this).closest('tr').find('.id').html(); //get the ID field
toArea = $(this).closest('tr').find('.to-area').html(); //get the to-area field
})
EDIT
All together:
$(document).ready(function() {
$('#btnSubmit').click(function() {
$('.row-select input:checked').each(function() {
var id, name;
id = $(this).closest('tr').find('.id').html();
name = $(this).closest('tr').find('.name').html();
alert('ID: ' + id + " | Name: " + name);
})
})
$('#btnSelectAll').click(function() {
$('.row-select input').each(function() {
$(this).prop('checked', true);
})
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border=1>
<tr class="row-select">
<td class="check">
<input type="checkbox" />
</td>
<td class="id">12</td>
<td class="name">Jones</td>
</tr>
<tr class="row-select">
<td class="check">
<input type="checkbox" />
</td>
<td class="id">10</td>
<td class="name">Joseph</td>
</tr>
</table>
<button id="btnSelectAll">Select all</button>
<button id="btnSubmit">Get Value</button>
Process step-by-step:
Give the td you need some classes (from-a & to-a);
Initialize an empty array all (we'll store the data inside it later on);
Create a function that is triggered by the checkbox change
Inside the function you need to know which checkbox has changed, what's the state of it, what tr does it belong to and at the end what are the TO AREA and FROM AREA values.
If the state = checked we will add the values to the all (our small data storage);
If the state = not-checked we will remove the value from the all array;
Finally when we are done with selecting and deselecting rows by pressing the button we can get the values of the selected rows.
var all = [];
$('input[type="checkbox"]').change(function(){
var checkbox = $(this);
var state = checkbox.prop('checked');
var tr = checkbox.parents('tr');
var from = tr.children('.from-a').text();
var to = tr.children('.to-a').text();
if(state){
all.push(from + ' -> ' + to);
}else{
var index = all.indexOf(from + ' -> ' + to);
all.splice(index, 1);
}
})
$('#get_to_area').click(function(){
alert(all);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="well white">
<table id="SampleDT" class="datatable table table-hover table-striped table-bordered tc-table">
<thead>
<tr>
<th>Select</th>
<th>Id</th>
<th>Doctor Name</th>
<th>From Area</th>
<th>To Area</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr id="1">
<td><input type="checkbox"></td>
<td>1</td>
<td>Nick</td>
<td class="from-a">Kosur</td>
<td class="to-a">Nath Pari</td>
<td>Address</td>
</tr>
<tr id="2">
<td><input type="checkbox"></td>
<td>2</td>
<td>John</td>
<td class="from-a">Rusok</td>
<td class="to-a">iraP htaN</td>
<td>sserddA</td>
</tr>
</tbody>
</table>
<center>
<div class="form-group">
<button style="text-align:left;" id="get_to_area">Transfer Area</button>
</div>
</center>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
This is just the basic concept, you can modify it to suit your needs, I'll be happy to help you if you get stuck.
You can also use this fiddle:
In JS:
$('#get_to_area').click(function () {
var id = $('input[name=getchemist]:checked').val();
if ($('input[name=getchemist]').is(':checked')) {
var ID = $('input[name=getchemist]').parent().parent().siblings('td.chkid').html();
var TO_Area = $('input[name=getchemist]').parent().parent().siblings('td.toarea').html();
}
else {
alert('Please Check');
}
});
In Html:
if (res['status'] == 1) {
var htmlString = '';
$.each(res['data'], function (key, value) {
htmlString += '<tr>';
htmlString += ' <td class="sorting_1"><div class="checkbox-custom checkbox-success"><input type="checkbox" id="checkboxExample3" name="getchemist" class="getchemist" value="' + value.id + '"><label for="checkboxExample3"></label></div></td>';
htmlString += '<td class="chkid">' + value.id + '</td>';
htmlString += '<td>' + value.name + '</td>';
htmlString += '<td>' + value.area + '</td>';
htmlString += '<td class="toarea">' + value.to_area + '</td>';
htmlString += '<td>' + value.address + '</td>';
htmlString += '</tr>';
});
I'm guessing you need values of each td whose checbox are checked. This piece of code should get you started.
As you can see, Code loops through each checkbox which is checked, gets contents inside its corresponding td.
var Result = new Array();
$('.checkbox-custom input[type="checkbox"]:checked').each(function(){
var _this = $(this).closest('tr').find('td');
var id= $(_this).eq(0);
var name = $(_this).eq(1);
................... //Similar way for the others
Result.Push(id,name,....)
});

Categories