There is a table which contains an user dropdown per row. Needs to prevent to select duplicate users in the table.
I have written js function for it.But it's not accomplish the requirements.
HTML
Javascript function
function checkDuplicateUserId(obj){
var user_id=$("#"+obj.id+" option:selected").val();
$('tbody#data tr select').each(function (i, row) {
if ($('tbody#data tr select').find('option[value="' + $(this).val() + '"]').size() > 1) {
alert();
}
});
}
function checkAlreadySelected(obj){
checkDuplicateUserId(obj);
var num = parseInt($(obj).attr('num'));
var user_id=$("#"+obj.id+" option:selected").val();
var next_user_id=$("#user_id_"+eval(num+1)+" option:selected").val();
if(user_id && typeof next_user_id == 'undefined'){
var row = updateSrNo(num);
$("#data").append(row);
}
}
Why this alert() not prompted while i choose the duplicate user from the table?
Related
This question already has answers here:
Getting values of elements in same row when button is clicked, one button per row
(2 answers)
Closed last year.
I have this function which creates a table in a modal popup and the table gets populated from data in an array passed in from an ajax call. Now on the click of a button in the modal popup I need to get the value of item.TimedPathwayID that has its radio button checked and add it to a hidden field.
function PopulateTimedPathwaysTable(tblData) {
var tbody = $('#tblTimedPathways tbody');
$.map(tblData.d, function (item) {
tr = $('<tr></tr>');
tr.append('<td class="pathwayID">' + item.TimedPathwayID + '</td>');
tr.append('<td>' + item.TimedPathwayName + '</td>');
tr.append('<td><input type="radio" class="radioSelection" name="timedPathwaySelection"" />');
tbody.append(tr);
});
$('input[name=timedPathwaySelection]:first').attr('checked', true);}
}
I've been fiddling with this kind of thing but with no joy and the radio button in the first row is checked by default so this can't really be tied to a click event if a user just accepts the default without clicking. So how can I do it please?
$('body').on('click', '.radioSelection', function () {
var $tbl = $('#tblTimedPathways tbody');
var $dataRow = $tbl.closest('tr');
var id = $dataRow.find('td').eq(0).html();
});
.closest goes up the html tree, so tbody.closest(tr) is unlikely to be what you want.
you need to then go back down to the cell that contains the data you want.
let $this = $(this); //this is the radio button
let id = $this.closest("tr").find("td.pathwayID").text();
I would also echo that I would generally add the id as an attribute to the row to remove the necessity of the find later.
//sample data
let data = {
d: [{
TimedPathwayID: 1,
TimedPathwayName: "test"
},
{
TimedPathwayID: 2,
TimedPathwayName: "test"
},
{
TimedPathwayID: 3,
TimedPathwayName: "test"
}
]
};
function PopulateTimedPathwaysTable(tblData) {
var tbody = $('#tblTimedPathways tbody');
$.map(tblData.d, function(item) {
tr = $('<tr></tr>');
tr.append('<td class="pathwayID">' + item.TimedPathwayID + '</td>');
tr.append('<td>' + item.TimedPathwayName + '</td>');
tr.append('<td><input type="radio" class="radioSelection" name="timedPathwaySelection"" />');
tbody.append(tr);
});
$('input[name=timedPathwaySelection]:first').attr('checked', true);
}
//populate it
PopulateTimedPathwaysTable(data);
$('body').on('click', '.radioSelection', function () {
let $this = $(this); //this is the radio button
//console.log($this);
let id = $this.closest("tr").find("td.pathwayID").text();
console.log(id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tblTimedPathways">
<tbody>
</tbody>
</table>
I want to be able to delete checkbox-selected rows but when I click on "Delete Selected", both the table on the web page and MySQL database stay unchanged. How do I get the selected rows from both the web page and the database to be deleted?
Edit: I'm now able to delete the rows but only the first row, despite selecting more than one checkbox, or selecting another checkbox not on the first row. Also, if I want to delete another entry, I will have to first refresh the page before deleting another one.
datatable.php
<div class="row well">
<a type="button" class="delete_all btn btn-primary pull-right">Delete Selected</a>
</div>
<script type="text/javascript">
$(document).ready(function($)
{
function create_html_table (tbl_data) {
tbl +='<table>';
tbl +='<thead>';
tbl +='<tr>';
tbl +='<th rowspan="3"><input type="checkbox" id="master"></th>';
// More table headers
tbl +='</tr>';
tbl +='</thead>';
tbl +='<tbody>';
$.each(tbl_data, function(index, val)
{
var row_id = val['row_id'];
//loop through ajax row data
tbl +='<tr id="row" row_id="'+row_id+'">';
tbl +='<td><input type="checkbox" class="sub_chk"></td>';
tbl +='<td>'+(index + 1)+'</td>';
tbl +='<td><div col_name="filename">'+val['filename']+'</div></td>';
// More data
tbl +='</tr>';
});
tbl +='</tbody>';
tbl +='</table>';
}
var ajax_url = "<?php echo APPURL;?>/ajax.php" ;
// Multi-select
$(document).on("click","#master", function(e) {
if($(this).is(':checked',true))
{
$(".sub_chk").prop('checked', true);
}
else
{
$(".sub_chk").prop('checked',false);
}
});
//Delete selected rows
$(document).on('click', '.delete_all', function(event)
{
event.preventDefault();
var ele_this = $('#row') ;
var row_id = ele_this.attr('row_id');
var allVals = [];
$(".sub_chk:checked").each(function()
{
allVals.push(row_id);
});
if(allVals.length <=0)
{
alert("Please select row.");
}
else {
var data_obj=
{
call_type:'delete_row_entry',
row_id:row_id,
};
ele_this.html('<p class="bg-warning">Please wait....deleting your entry</p>')
$.post(ajax_url, data_obj, function(data)
{
var d1 = JSON.parse(data);
if(d1.status == "error")
{
var msg = ''
+ '<h3>There was an error while trying to add your entry</h3>'
+'<pre class="bg-danger">'+JSON.stringify(data_obj, null, 2) +'</pre>'
+'';
}
else if(d1.status == "success")
{
ele_this.closest('tr').css('background','red').slideUp('slow');
}
});
}
});
});
</script>
ajax.php
//--->Delete row entry > start
if(isset($_POST['call_type']) && $_POST['call_type'] =="delete_row_entry")
{
$row_id = app_db()->CleanDBData($_POST['row_id']);
$q1 = app_db()->select("select * from data where row_id='$row_id'");
if($q1 > 0)
{
//found a row to be deleted
$strTableName = "data";
$array_where = array('row_id' => $row_id);
//Call it like this:
app_db()->Delete($strTableName,$array_where);
echo json_encode(array(
'status' => 'success',
'msg' => 'deleted entry',
));
die();
}
}
//--->Delete row entry > end
I've seen other similar SO questions like this one but I don't think it is applicable to my code.
My output:
To achieve what you want, you have to select the good elements the right way. For example, an HTML id must be unique, so giving all your elements the same id="row" won't work. Using your class will be enough. Then you have to consider that each will execute the function separately for all your selected elements, so that if you want to do things for each element, all the code must be inside.
I optimized a little your code by getting rid of allVals variable, if its only goal is to test if rows have been selected, you can directly test .length on your selection. I renamed variables so that it's more clear which is what.
Also it's not very clear in the question if the "Please wait....deleting your entry" text should appear in the button or in each row, i assumed it was in the button, and it will help you differentiate all elements from how they are selected.
//Delete selected rows
$(document).on('click', '.delete_all', function(event)
{
event.preventDefault();
//'click' is called on the button, so 'this' here will be the button
var button = $(this) ;
var checked_checkboxes = $(".sub_chk:checked");
if(checked_checkboxes.length <=0)
{
alert("Please select row.");
}
else {
button.html('<p class="bg-warning">Please wait....deleting your entry</p>');
//next code will be executed for each checkbox selected:
checked_checkboxes.each(function(){
var checkbox = $(this);
var row_id = checkbox.attr('row_id');
var data_obj=
{
call_type: 'delete_row_entry',
row_id: row_id,
};
$.post(ajax_url, data_obj, function(data)
{
var d1 = JSON.parse(data);
if(d1.status == "error")
{
var msg = ''
+ '<h3>There was an error while trying to add your entry</h3>'
+'<pre class="bg-danger">'+JSON.stringify(data_obj, null, 2) +'</pre>'
+'';
//you still have to do something with your message, keeping in mind that a separate message will be generated for each separate $.post (one is emitted for each checked checkbox)
}
else if(d1.status == "success")
{
checkbox.closest('tr').css('background','red').slideUp('slow');
}
});
});
}
});
So I know there are a few posts about this but I haven't found them to helpful so I'm hoping this will shed new light on my problem.
I'm trying to to get data from a check-boxed row in a HTML table. At the moment I only want to display it on a windows.alert or in the Visual Studio console. But eventually I'm going to post the data to a database.
My code:
$(document).ready(function () {
$('#button').click(function () {
var id = [];
$(':checkbox:checked').each(function (i) {
id[i] = $(this).val();
});
if (id.length === 0) {
alert("Please select at least one checkbox");
}
else {
$.post('http://localhost/Dynamic/?Insert');
}
});
});
I've tried alert($(this).text()) but that just appears empty.
Help would be appreciated.
If it helps this is how I populate the table:
var tableName = 'table1'
$.ajax({
url: 'http://localhost/Dynamic?prod=' + tableName,
dataType: 'Json',
success: function (Results) {
$.each(Results, function () {
var row = "";
for (i = 0; i < this.length; i++) {
var input = '<td>' + this[i] + '</td>';
row = row + input;
}
$('#table1 tbody:last-child').append('<tr>' + row + '<td> <input class="checkBox" type="checkbox" id="count"/> </td></tr>');
});
}
});
As you can see the table is populated dynamically so it can be populated by different tables.
your selector is wrong. $(':checkbox:checked') should be $('.checkbox:checked').
maybe try to change to different class name.
$('.mycheckbox:checked').each(function (i) {
id[i] = $(this).val();
});
I've gotten it to work, I created a global array and added all the values to that. I then created a counter and set each checkbox's ID to the counters value. I then increment the counter before looping back around to sort with the next row of data.
Then When I want to choose data. I check the checkbox's of the data. Press the button then I get the Id's of each of the checkbox's. I then put the checkbox id into the array to get the value before adding it to an array which I then post.
I am using jquery datatables to make my table searchable. I have a dropdown that filters a gender column:
$("#genderDrop").on("change", function(e) {
var gender = $(this).val();
formTable.column(2).search(gender).draw();
});
this works fine, but now I want to be able to remove the filter when the user selects "all" from the dropdown. Here is my attempt:
$("#genderDrop").on("change", function(e) {
var gender = $(this).val();
if (gender != "all") {
formTable.column(2).search(gender).draw();
} else {
formTable.column(2).search("").draw();
}
});
Instead of removing the filter this just searches for an empty string, but I can't work out how to change this so it removes the filter. I also tried:
formTable.column(2).search("*").draw();
and
formTable.column(2).search().draw();
but without any success.
You can use the option All from gender select with empty value:
<option value="">All</option>
them your code will work:
$("#genderDrop").on("change", function(e) {
var gender = $(this).val();
formTable.column(2).search(gender).draw();
});
Using DataTables example as base: http://jsfiddle.net/PauloSegundo/g15xakh5/
you can try the below:
function fnResetAllFilters() {
var oSettings = oTable.fnSettings();
for (iCol = 0; iCol < oSettings.aoPreSearchCols.length; iCol++) {
oSettings.aoPreSearchCols[iCol].sSearch = '';
}
oTable.fnDraw();
}
To remove all filters and global filters, please refer to below link:
https://datatables.net/plug-ins/api/fnFilterClear
Try this way:
var table = $('#tableHere').DataTable().destroy();
table.state.clear();
in this fiddle
I have a button add which when clicked adds input datas to a new row as given in the screenshot.The group button is used for creating a group of user numbers.Suppose I want to create a group friends which will contains mobile numbers of 1st row,2nd row and last row. So for this I will just select the checkboxes of 1st row,2nd row and the last row.Then after pressing the group button it will create a group.Group name along with group members(mobile numbers) should be stored in database.So i am using ajax.Please tell me how to pass mobile numbers of selected rows.
following is the jquery
var val=0;
$(document).ready(function(){
$('#btn1').click(function(){
if($(".span4").val()!="")
{
$("#mytable").append('<tr id="mytr'+val+'"></tr>');
$("#mytr"+val).append('<td class=\"cb\"><input type=\"checkbox\" value=\"yes\" name="mytr'+val+'" checked ></td>');
$(".span4").each(function () {
$("#mytr"+val).append("<td >"+$(this).val()+"</td>");
});
val++;
}
else
{
alert("please fill the form completely");
}
});
$('#btn2').click(function(){
var creat_group=confirm("Do you want to creat a group??");
if(val>1){
alert(creat_group);
}
});
});
What is group and why do i want it?
Suppose if i have some 100 records,out of that some are java employee,some are .net employee and some are mainframe
Suppose if i want to send sms only to java employee,if i am not having group then out of 100 records
I have to manually check who are java employees.So in order to avoid that I want to create groups 1 for java,1 for .net and another for mainframe.So in order to send sms to only java people I can select the java group and send sms
Try this,
var obj={};// add this
$('#btn1').click(function () {
if ($(".span4").val() != "") {
$("#mytable").append('<tr id="mytr' + val + '"></tr>');
$tr=$("#mytr" + val);
$tr.append('<td class=\"cb\"><input type=\"checkbox\" value=\"yes\" name="mytr' + val + '" checked ></td>');
$(".span4").each(function () {
$tr.append("<td >" + $(this).val() + "</td>");
});
// add below code
var arr={};
name=($tr.find('td:eq(1)').text());
email=($tr.find('td:eq(2)').text());
mobile=($tr.find('td:eq(3)').text());
arr['name']=name;arr['email']=email;arr['mobile']=mobile;
obj[val]=arr;
// add upto above line
val++;
} else {
alert("please fill the form completely");
}
});
Also Update and add below code,
$(document).on('click', '#btn2',function () {
var creat_group = confirm("Do you want to creat a group??");
if (creat_group) {
console.log(obj);
}
});
// to get the checked data only
$(document).on('change','#mytable input:checkbox',function () {
if(!this.checked)
{
key=$(this).attr('name').replace('mytr','');
obj[key]=null;
}
});
Demo
As said in my comment here's my answer, you need to add that to your $('#btn2').click():
Working Fiddle
$(document).ready(function () {
$('#btn2').click(function () {
var checkedRows = $('#mytable').find("input:checked").parent().parent();
var total = checkedRows.length;
var info = [];
for(i = 0; i < total; i++){
var row = $(checkedRows[i]).children();
var tmpInfo = [];
tmpInfo["name"]= row[1].innerHTML;
tmpInfo["email"]= row[2].innerHTML;
tmpInfo["phone"]= row[3].innerHTML;
info.push(tmpInfo);
}
console.log(info);
$.post('yourpage', info, function(){
//on success code, can be an alert or anything you want.
});
});
});
Explanation: Basicly we first find all the checked checkboxes parent row and create an array (checkedRows);
Then we loop through this array (it's much quicker than using $.each) and add the table cell 1 2 and 3's inner HTML to the info array. (td 0 is the checkbox's cell so we don't need it);
Send info to your server, it should be an array of n sub-arrays (depending on how many rows were checked), the sub-arrays will be holding the name, email and phone.