I have a table, currently with 2 rows. Next to these rows I have an icon, which when clicked, brings up a dialog box, and in this dialog box is a button which when pressed, is to run a function which copies the selected item to another file
So pretend we're in my dialog box, and this is my code:
$(document).ready(function() {
$(function() {
$("#save").on("click", saveNote);
});
})
This calls the following function:
function saveNote() {
var OpenNote = $('.dlg_lineNote');
var row = jQuery(OpenNote.closest("tr"));
var cpyItem = row.find(".IPROD").text();
$('div#dialogD').data('dataIPROD', cpyItem);
jQuery.ajax({
url: 'B2BUNV400.PGM',
type: 'POST',
data: {
task: 'copyItem',
cpyItem: cpyItem
},
}).done(function(message) {
$("#saveComment").html("Saved");
});
}
My table has two rows with the following items:
row1: 97940G96058445V
row2: 32253216058445
Here is the html:
<tr class="altcol1">
<input type="hidden" name="IPRODa" value="97940G96058445V" />
<td class="" align="center"><span><a class="icon-sitemap split dlg_lineNote" href="#" id="dlg_lineNote" title="Copy item to LXF files" href=""></a></span></td>
<td align="center" class="IPROD">97940G96058445V</td>
<td class="text" align="center">PA</td>
<td class="text" align="center">F7940</td>
<td class="text" align="center">G9</td>
<td class="text" align="center">58</td>
<td class="text" align="center">44</td>
<td class="text" align="center">5</td>
<td class="text num" align="center">6.000</td>
</tr>
<tr class="altcol2">
<input type="hidden" name="IPRODa" value="32253216058445" />
<td class="" align="center"><span><a class="icon-sitemap split dlg_lineNote" href="#" id="dlg_lineNote" title="Copy item to LXF files" href=""></a></span></td>
<td align="center" class="IPROD">32253216058445</td>
<td class="text" align="center">PA</td>
<td class="text" align="center">F2253</td>
<td class="text" align="center">21</td>
<td class="text" align="center">58</td>
<td class="text" align="center">44</td>
<td class="text" align="center">5</td>
<td class="text num" align="center">6.000</td>
</tr>
This is the html for the dialog:
<div id="dialogD">
<button id="save">Copy Item</button>
</div>
This is jQuery I have to open said dialog:
$(document).ready(function() {
$('div#dialogD').dialog({ autoOpen: false, height: 250, width: 300 })
$('.dlg_lineNote').click(function(){
var OpenNote = $(this);
var row = jQuery(OpenNote.closest("tr"));
var cpyItem = row.find(".IPROD").text();
$('div#dialogD').data('dataIPROD',cpyItem);
jQuery.ajax(
{
url: 'B2BUNV400.PGM',
type: 'POST',
data: {task: 'copyItem', Item: cpyItem},
}).done(function(message)
{
$("#notetext").val(message);
$('div#dialogD').dialog('open');
});
$(document).ready(function() {
$(function() {
$("#save").on("click", saveNote);
});
})
})
And the result:
task=copyItem&cpyItem=97940G96058445V32253216058445
Notice cpyItem is actually retrieving both the item records in the table, instead of the item I have clicked when opening the dialog box
Whichever item I chose to 'save', it is pulling both rows...
I hope this makes sense
Appreciate any help in advance
Note: I do not use jquery very often
Edit: This is my updated code
<script>
jQuery(function() {
jQuery("input:submit, input[type=button], input[type=submit], button,
.button").button();
});
$(document).ready(function() {
$('div#dialogD').dialog({ autoOpen: false, height: 250, width: 300 })
$('.dlg_lineNote').click(function(){
var OpenNote = $(this);
var row = jQuery(OpenNote.closest("tr"));
var cpyItem = row.find(".IPROD").text();
$('div#dialogD').data('dataIPROD',cpyItem);
jQuery.ajax(
{
url: 'B2BUNV400.PGM',
type: 'POST',
data: {task: 'copyItem', Item: cpyItem},
}).done(function(message)
{
$("#notetext").val(message);
$('div#dialogD').dialog('open');
});
})
// var item = row.find(".IPROD").text();;
// $("#save").click({cpyItem: item} ,saveNote);
$('.dlg_lineNote').on('click', function() {
var row = $(this).closest("tr");
var cpyItem = row.find(".IPROD").text();
$('div#dialogD').data('dataIPROD', cpyItem);
});
function saveNote() {
jQuery.ajax({
url: 'B2BUNV400.PGM',
type: 'POST',
data: {
task: 'copyItem',
cpyItem: $('div#dialogD').data('dataIPROD') //get the value of the last selected row
},
}).done(function(message) {
$("#saveComment").html("Saved");
});
}
})
</script>
Your OpenNote variable is pointing to two objects as it's selecting by class and there's two td elements with that class.
You need to select the closest td with the class .dlg_lineNote to the item you choose to save.
How do you choose which item to save? I know you click the save button in your dialog but you need a way of relating that to a specific row
You could do it like this:
var row;
$('.dlg_lineNote').on('click', function() {
row = $(this).closest("tr");
});
function saveNote() {
var cpyItem = row.find(".IPROD").text();
$('div#dialogD').data('dataIPROD', cpyItem);
jQuery.ajax({
url: 'B2BUNV400.PGM',
type: 'POST',
data: {
task: 'copyItem',
cpyItem: cpyItem
},
}).done(function(message) {
$("#saveComment").html("Saved");
});
}
Currently you're selecting the fields from every row with $('.dlg_lineNote');.
What you need to do instead is identify the row which was clicked on. You can use a data-attribute on the button to hold the value from the row, as you do now (although in your current code the data attribute is redundant), but you need to change the location where you set the value to the moment when the row is clicked on (rather than the dialog button), so you can easily identify the right row:
$(document).ready(function() {
$('div#dialogD').dialog({ autoOpen: false, height: 250, width: 300 });
$('.dlg_lineNote').on('click', function() {
var row = $(this).closest("tr"); //use "this" to get the exact element clicked on. From here we can get to the exact tr, instead of selecting all of them at once.
var cpyItem = row.find(".IPROD").text();
$('div#dialogD').data('dataIPROD', cpyItem);
});
$("#save").click(saveNote);
});
function saveNote() {
jQuery.ajax({
url: 'B2BUNV400.PGM',
type: 'POST',
data: {
task: 'copyItem',
cpyItem: $('div#dialogD').data('dataIPROD'); //get the value of the last selected row
},
}).done(function(message) {
$("#saveComment").html("Saved");
});
}
Related
function getAnnoDetailsForTeacher(){
var tcounter = 1;
$.ajax({
url:'<%=contextPath%>/show/announcementsForTeacher',
headers: {
'Authorization':'${sessionScope.token}'
},
type:'GET',
data: {
'loginId' : '${loginId}'
},
success:function(data){
$('#annoTable tbody').empty();
for(var i=0; i<data.length;i++)
{
var aid = data[i].id;
var date = data[i].date;
var subject = data[i].subject;
var details = data[i].details;
var status = data[i].status;
$('#annoTable tbody').append('<tr data-toggle="modal" data-target="#viewTAnnoModal"><td id="tCounter'+aid+'"><strong>'+tcounter+
'</strong></td><td id="tDate'+aid+'"><strong>'+date+
'</strong></td><td id="tSubject'+aid+'"><strong>'+ subject +
'</strong></td><td id="tDetails'+aid+'" class="cell expand-small-on-hover"><strong>'+ details +
'</strong></td><td><button type="button" id="tAnnoBtn'+aid+'" onclick="viewTAnno()" class="viewbtn" data-toggle="modal" data-target="#" style="display:block;">View</button>'+
'</td>'+
......+
'</tr>');
tcounter += 1;
}
$('#tnoti').empty();
$('#tnoti').css('display','block');
$('#tnoti').append(tcounter-1);
},
error:function(e){
console.log(e)
}
});
return tcounter;
}
my goal is to unbold a row when clicked on view btn (where id is dynamic:i d="tAnnoBtn'+aid+'") inside the jQuery.
Here is the unbold jQuery
$('#tAnnoForm').on('click', '.viewbtn', function() {
const fooTCounter = document.getElementById("tCounter");
fooTCounter.innerHTML = fooTCounter
.innerHTML
.replace(/<strong>/g, "")
.replace(/<\/strong>/g, "");
const fooTDate = document.getElementById("tDate");
fooTDate.innerHTML = fooTDate
.innerHTML
.replace(/<strong>/g, "")
.replace(/<\/strong>/g, "");
const fooTSubject = document.getElementById("tSubject");
fooTSubject.innerHTML = fooTSubject
.innerHTML
.replace(/<strong>/g, "")
.replace(/<\/strong>/g, "");
const fooTDetails = document.getElementById("tDetails");
fooTDetails.innerHTML = fooTDetails
.innerHTML
.replace(/<strong>/g, "")
.replace(/<\/strong>/g, "");
});
problem is every element is created dynamically with dynamic id (td cells and buttons)
so how can i input the dynamic ids inside the unbold jQuery??
like in jQuery it should go like document.getElementById("tCounter1") where 1 is concatenated with tCounter.
also in '.viewbtn', it should go like '#tAnnoBtn1' where 1 is dynamically concatenated with tAnnoBtn.
check this viewTAnno(aid) function
function viewTAnno(aid)
{
var viewed;
$.ajax({
url:'<%=contextPath%>/show/annoViewedForTeacher',
headers: {
'Authorization':'${sessionScope.token}'
},
type:'GET',
data: {
'loginId' : '${loginId}',
'anno_id' : aid
},
success:function(data){
//alert("New Announcement Added Successsfully");
console.log(data);
viewed =data;
$('#tAnnoTable').on('click', '.viewbtn', function() {
if(viewed==0){
//get closest tr > loop through tds
$(this).closest("tr").find("td:not(:last)").each(function() {
//replace text
$(this).text($(this).text().replace(/<strong>/g, "")
.replace(/<\/strong>/g, ""))
//tcounter=tcounter-1;
$.ajax({
url:'<%=contextPath%>/show/annoViewedForTeacher',
headers: {
'Authorization':'${sessionScope.token}'
},
type:'POST',
data: {
'loginId' : '${loginId}',
'anno_id' : aid
},
success:function(data){
console.log(data);
},
error:function(e){
console.log(e)
}
});
})
}
})
},
error:function(e){
console.log(e)
}
});
return viewed;
}
i want to unbold a particular row upon clicking on view so that it also changes in db just like gmail inbox. how can i do that?
You can simply iterate through your tds where view button has been clicked then using $(this).text(..) replace <strong> tag with ''
Demo Code :
$('#annoTable').on('click', '.viewbtn', function() {
//get closest tr > loop through tds
$(this).closest("tr").find("td:not(:last)").each(function() {
//replace text
$(this).text($(this).text().replace(/<strong>/g, "")
.replace(/<\/strong>/g, ""))
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="annoTable">
<tbody>
<tr data-toggle="modal" data-target="#viewTAnnoModal">
<td id="tCounter1"><strong>1</strong></td>
<td id="tDate1"><strong>0.005997001499250375</strong></td>
<td id="tSubject1"><strong>Abc</strong></td>
<td id="tDetails1" class="cell expand-small-on-hover"><strong>Somwthing..</strong></td>
<td><button type="button" id="tAnnoBtn1" onclick="viewTAnno()" class="viewbtn" data-toggle="modal" data-target="#" style="display:block;">View</button></td>
</tr>
<tr data-toggle="modal" data-target="#viewTAnnoModal">
<td id="tCounter2"><strong>2</strong></td>
<td id="tDate2"><strong>0.005997001499250375</strong></td>
<td id="tSubject2"><strong>Abc</strong></td>
<td id="tDetails2" class="cell expand-small-on-hover"><strong>Somwthing..</strong></td>
<td><button type="button" id="tAnnoBtn2" onclick="viewTAnno()" class="viewbtn" data-toggle="modal" data-target="#" style="display:block;">View</button></td>
</tr>
</tbody>
</table>
On table row Edit button click, a form modal is opened.
I am picking that row current values so they can be default values of that form fields when modal is opened.
As I am new in jQuery I can not figure out how to pass that values in other method.
My func:
var $fruitForm = $('#edit-form')
$('.fruit_edit').on('click', function(event) {
// Get the data-id value of the modal link.
var id = $(this).data('fruit_id');
// Set the hidden input field with the id.
$('#fruit_id').val(id);
var $row = $(this).closest('tr');
// Here I am finding row value on click
var tableFruitName = $("a[data-fruit_id="+id+"]").closest("tr").find('.tableFruitName').text()
event.preventDefault();
});
// Listen for submit instead of click.
$fruitForm.on('submit', function(event) {
event.preventDefault();
// Get the values from the form.
var $form = $(this);
var id = $form.find('input[name="fruit_id"]').val();
I want for the value from upper 'onclick' to be defined in from input here
var fruitName = $('#fruitName').val(tableFruitName);
$.ajax({
type: 'PATCH',
url: '/fruit/edit',
data: JSON.stringify({
'id' : id,
'fruitName' : fruitName
}),
processData: false,
contentType: 'application/json-patch+json',
success: function () {
$("#fruit-table").load(location.href + " #fruit-table");
$('#editFruit').modal('hide');
},
error: function (xhr, status, error) {
var ErrorMessage = JSON.parse(xhr.responseText);
}
});
});
Explanation of my workflow is within comments. I don't know how to pass catched value in other method where the input is defined.
<tr>
<td class="text-center"> {{ fruit.id }} </td>
<td class="text-center tableFruitName"> {{fruit.fruitName is empty ? "N/A" : fruit.startDate }}</td>
<td class="td-actions text-center">
<a href data-toggle="modal" data-target="#editFruit" data-fruit_id="{{ fruit.id }}" class="btn btn-warning fruit_edit">
<i class="fa fa-fw fa-pencil"></i>
</a>
</td>
</tr>
I am working in ASP.NET MVC.
I am having a datatable with checkbox options to select multiple rows to send to controller for bulk update. As, I am having two different funtions with two different buttons in same view, I cant able to use Form submission method.
I am trying to send via Ajax method. But, cant able to send selected rows into an array.
Codes that I tried below:
Table:
<table cellspacing="1" cellpadding="2" style="width: 100%;" id="tblStatus" class="table table-striped table-hover table-bordered table-hd">
<thead>
<tr class="gridheader">
<td valign="middle" align="center" style="width: 2%;">
<input id="chkAll" onclick="javascript: checkAll();" type="checkbox" name="chkAll" />
</td>
<td style="width: 25%;" >Data1</td>
<td style="width: 25%;" >Data2</td>
<td style="width: 25%;" >Data3</td>
<td style="width: 25%;" >Data4</td>
</tr>
</thead>
<tbody>
#if (Model != null)
{
foreach (var m in Model)
{
<tr>
<td valign="middle" align="center" style="width: 2%;">
<input id="chkBox" name="chkBox" type="checkbox" onclick="javascript: checkManual();" value="" />
</td>
<td>Data1</td>
<td>Data2</td>
<td>Data3</td>
<td>Data4</td>
</tr>
}
}
</tbody>
</table>
Controller:
[HttpPost]
public ActionResult Update(List<StatusVM> data1)
{
return View();
}
Button to Update:
<div class="btn-group">
<button #*type="submit"*# id="btnUpdate" onclick="GetData();" name="btnUpdate" class="btn btn-block btn-success btn-flat"><span class="hide-on-mobile">Update </span><i class="fa fa-save"></i></button>
</div>
Javascript-Where I am trying to send data:
function GetData() {
var table = $('#tblStatus').DataTable();
if ($('[name="chkBox"]:checked').length <= 0) {
alert('Please select minimum one data');
}
else {
var CData = new Array();
var dd;//= $('[name="chkBox"]:checked').toArray();
$('[name="chkBox"]:checked').each(function (data) {
var rowData =table.row(this).data();
CData.push(rowData);
});
$.ajax({
type: "POST",
url: "/Test/Update",
contentType: "application/json;",
headers: { 'RequestVerificationToken': gettoken() },
data: JSON.stringify({ data1: CData }),
});
}
}
How to fix this? I want sent rows data that selected with checkbox only. Kindly help.
From just looking at your javascript, I think your main issue is that you're not mapping the data you're sending to the Controller to the object that the Update Action Method is expecting and so the Model Binding is not working.
For example, say your StatusVM object looked like this:
public class StatusVM
{
public int Id {get;set;}
public string Name {get;set;}
}
In your javascript, you'll need to map the items from your html objects to that object, so create an object that represents it like in the example below:
var cData = new Array();
for(var i = 0; i < rowData.length; i++){
cData.push(obj);
}
function GetData() {
var table = $('#tblStatus').DataTable();
if ($('[name="chkBox"]:checked').length <= 0) {
alert('Please select minimum one data');
}
else {
var CData = new Array();
$('[name="chkBox"]:checked').each(function (data) {
var rowData =table.row(this).data();
var obj = {
Id: rowData.Id,
Name: rowdata.Name
};
CData.push(obj );
});
$.ajax({
type: "POST",
url: "/Test/Update",
contentType: "application/json;",
headers: { 'RequestVerificationToken': gettoken() },
data: CData,
});
}
}
Hope that helps.
As you are creating table("DOM") in your view, row().data() will return "Array" of values of row. In your case it would be like row 1 data will be ["Data1", "Data2", "Data3"...].
In this case you have to make "StatusVM" like object in each function callback
$('[name="chkBox"]:checked').each(function(data) {
var rowData = table.row($(this).parents('tr')).data();
var obj = {
"col1": rowData[0],
"col2": rowData[1],
"col3": rowData[2]
}
CData.push(obj);
});
If you want the row return object then you have to bind DataTable with JSON.
As documentation says:
Data source object for the data source of the row. This will be an array if you use DOM sourced data, otherwise it will be the array / object / instance that is used to populate the table with data.
I am trying to re-order a list via ajax on sortable update, however after adding a new item to this list via ajax after sortable has already been initialized on page load, it does not recognize the new item with the "serialize" function. It does allow me to drag it around as though it is working, but the code that gets sent with my update function is missing the new element.
//Sort categories
$('#categories-list').find('tbody').sortable({
connectWith: 'tbody',
opacity: 0.6,
cursor: 'move',
forcePlaceholderSize: true,
update: function(e) {
var serialized = $('#categories-list tbody').sortable('serialize');
console.log(serialized);
$.post('admin/ereg_forms/set_category_position', serialized, function(data) {
if (data.status == 'error') {
alert(data.message);
}
});
}
});
//Add category submit
$("#add-category-submit").click(function(e) {
e.preventDefault();
$(".errors-block").html('');
$('#add-category-submit').hide();
$.ajax({
url: $("#add-category-form").attr('action'),
type: 'POST',
data: $('#add-category-form').serialize(),
dataType: 'json',
success: function(data) {
$('#add-category-submit').show();
//Check if server side validation passed
if (data.status == 'error') {
//Show error on popup dialog
$("#add-category-form .errors-block").html(data.message);
alert('Sorry, the information that was sent is invalid. Please review the errors at the top of the form and try again.');
} else {
var category_data = data.data;
var tableRow = '<tr class="category-row-' + category_data.id + '"><td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span>' +
'</td><td>' + category_data.title +
'</td><td></tr>'
$(tableRow).appendTo('#categories-list tbody');
resetForm($('#add-category-form'));
//Close popup window
$('#add-category').dialog('close');
$("<div title='Success!'>Category has been saved.</div>").dialog({
modal: true,
width: 'auto'
});
}
},
error: function(data) {
alert('An unknown error has occurred, please try again.');
$('#add-category-submit').show();
}
});
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<table class="data" id="categories-list">
<thead>
<tr>
<th> </th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr id="category-row-19">
<td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span></td>
<td class="category-row-title">test1</td>
</tr>
<tr id="category-row-20">
<td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span></td>
<td class="category-row-title">test</td>
</tr>
</tbody>
</table>
I have looked everywhere for a solution but have not found one that has worked. I have tried using the "refresh" function with sortable, I have tried initializing sortable inside of the success function of the ajax call to add new categories but it also does not work.
when I console.log(serialized) it only has the originally loaded elements in the array.
IDK what is going on, but this fake add works, perhaps you can emulate this? Note I cleaned up a couple syntax issues and used the ajax promise methods to better organize it.
I suggest you update your jQuery version, some better stuff in more recent versions with bug fixes.
//Sort categories
$('#categories-list').find('tbody').sortable({
connectWith: 'tbody',
opacity: 0.6,
cursor: 'move',
forcePlaceholderSize: true,
update: function(e) {
var serialized = $('#categories-list tbody').sortable('serialize');
console.log(serialized);
// $.post('admin/ereg_forms/set_category_position', serialized, function(data) {
// if (data.status == 'error') {
// alert(data.message);
// }
// });
}
});
$('#addmorefool').on('click', AddMore);
function AddMore() {
let tbody = $('#categories-list').find('tbody');
let rowscount = tbody.find('tr').length;
let newRow = '<tr id="category-row-' + rowscount + '"><td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span></td><td class="category-row-title">test' + rowscount + '</td></tr>';
tbody.append(newRow);
}
AddMore();
//Add category submit
$("#add-category-sumbit").on('click', function(e) {
//console.log("howdy");
e.preventDefault();
var myform = $("#add-category-form");
var errorBlock = myform.find(".errors-block");
errorBlock.html('');
errorBlock.dialog({
modal: true,
width: 'auto',
autoOpen: false
});
var catSub = $('#add-category-submit');
catSub.hide();
var myjax = $.ajax({
url: myform.attr('action'),
type: 'POST',
data: myform.serialize(),
dataType: 'json'
})
.done(function(data) {
catSub.show();
//Check if server side validation passed
var category_data = data.data;
var tableRow = $('<tr class="category-row-' + category_data.id + '"><td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span>' +
'</td><td>' + category_data.title +
'</td><td></tr>');
let tbody = $('#categories-list').find('tbody');
tbody.append(tableRow);
resetForm(myform);
//Close popup window (out cause have none)
//('#add-category').dialog('close');
$("<div title='Success!'>Category has been saved.</div>").dialog({
modal: true,
width: 'auto'
});
}).fail(function(data) {
//Show error on popup dialog
errorBlock.html('<span>Sorry, the information that was sent is invalid. Please review the errors at the top of the form and try again.</span>' + data.message);
errorBlock.dialog("open");
//catSub.show(); (out cause not in code)
});
});
tr td {
border: 1px solid lime;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<div id="add-category-form" action="metoo">I am an empty form, so what
<div class="errors-block">me error aggain? no way</div>
</div>
<table class="data" id="categories-list">
<thead>
<tr>
<th> </th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr id="category-row-19">
<td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span></td>
<td class="category-row-title">test1</td>
</tr>
<tr id="category-row-20">
<td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span></td>
<td class="category-row-title">test</td>
</tr>
</tbody>
</table>
<button id="addmorefool" type="button">Add More</button>
<div class="errors-block">me error</div>
<button type="button" id="add-category-sumbit">add category</button>
I ended up solving this problem, the issue was in the add category function I was applying the "class" attribute instead of using the "id" attribute for the category-row-{id}.
I am using script to print selected values from table into another div.
<script>
$(".addValues").click(function () {
$('#selection').show();
var $this = $(this),
myCol = $this.closest("td"),
myRow = myCol.closest("tr"),
targetArea = $("#selection");
var qte_input = ('<input type="text" name="kolicina" id="kolicina" placeholder="kg / m" size="10"/>');
var broj = ($("td.data-id", myRow).text());
targetArea.prepend(broj + qte_input +"<hr />");
var arr = { sifra:broj, kolicina:qte_input };
$.ajax({
url: 'script.php',
data: arr,
type: 'post',
});
});
</script>
I am trying to get selected values in script.php, multiple values will be selected and after each selection I need to type quantity that is var qte_input.
Could anyone tell me how to set var broj as input and in the same time print it to another div as selected?
html code
<table id="datatable" class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>-</th>
</tr>
</thead>
<tbody>
<?php while($r=$q->fetch()){ ?>
<tr>
<td class='data-id'><?=''. $r['Id']?> </td>
<td> <button class="addValues" value="<?=''. $r['Id']?>"><i class="ion-ios-cart-outline"></button></td>
</tr>
<?php } ?>
</tbody>
</table>
Once I click on button one value prints in div. Multiple values could be selected as displayed on the image. Once I finish selection I hit button "Pošalji zahtjev" it should pick up all
You should write a function which collect you all data from the table. After that this collection should be sent to you backend via ajax. Demo in this fiddle: https://jsfiddle.net/mgrem9gb/
/**
* Function collect the form data
*/
function collectData(container){
var data = [];
$(container).find('tbody').find('tr').each(function(index, item){
var rowData = {
id: $(item).find('td.data-id').text(),
value: $(item).find('input[name="kolicina"]').val()
};
data.push(rowData);
});
return data;
}
/**
* Excecute the data collect function and the ajax post
*/
$.ajax({
url: 'script.php',
data: collectData('#datatable'),
type: 'post',
});