how to pass the checked values of checkbox - javascript

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.

Related

JQuery display checkboxed table row data

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.

how to find duplicate dropdowns in a table using jquery?

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?

javascript save state of check boxes

I am having an issue where the current state of the checkbox is not being saved. I am new to this and any help would be appreciated. Here's the jQuery code that is partially working.
var userCityList = [];
$("#checkboxes").unbind('change').bind('change', function (event) {
var stateVal = $(':selected', $('#ResidentialLocationStateList')).val();
var cityID = $(event.target)[0].id;//stores city id
var cityVal = $(event.target)[0].value;//stores city value
if ($('#' + cityID).is(':checked')) {
if (userCityList.length < 5) {
userCityList.push(cityID);
}
else {
$('#' + cityID).prop('checked', false);
alert("5 cities have been selected");
return;
}
}//end if
if (!($("#" + cityID).is(':checked'))) {
userCityList.pop();
}
//console.log(userCityList);
});
LOGIC
When the user selects a state, a set of cities in checkboxes appear. When a user clicks a checkbox, that particular city is stored in the userCityList array. When the user clicks it again, it deletes it from the array. However, if the user changes the state, those cities are no longer checked, which does not allow one to delete it from the array, if needed.
Any suggestions?
HTML code
<div class="panel-body">
<p>Select upto 5 state/city combinations</p>
<div class="col-xs-3 no-pad-left less-width">
#*<p>Select upto 5 state/city combinations</p>*#
<select id="ResidentialLocationStateList" name="ResidentialLocationStateList" multiple></select>
</div>
<div class="col-xs-3" id="checkboxes">
</div>
</div>
UPDATE Here's the image that goes with this issue.
So when a few cities are selected and the user decides to change the state from the select element, those cities that were selected prior need to be saved.
UPDATE
Here's the AJAX code...
$("#ResidentialLocationStateList").change(function () {
url = "/ResidentialBuilding/getCityList?state=";
state = $("#ResidentialLocationStateList").val();
url = url + state;
//console.log(url);
$("#checkboxes").empty();
$.getJSON(url, function (data) {
//console.log(data);
$.each(data, function (index, value) {
//console.log(value.city);
id = value.city;
id = id.replace(/\s+/g, '');
valCity = value.city;
valCity = valCity.replace(/\s+/g, '');
$("#checkboxes").append('<input value="' + valCity + '"' + 'type=' + "'checkbox'" + 'id=' + id + '>' + value.city + '</input><br>');
});
});
});
If you're using a modern version of jQuery I would recommend using .off and .on and to use .off if you really have to.
lso the .pop() array method removes the last element but the element just clicked may not always be the one that was added last. And since, the check boxes are added dynamically, the following bind could be made at the very beginning of DOM ready and not necessarily in any event handler. Rather than give your checkboxes the same ID which leads to invalid HTML, use a class selector, .checkboxes.
Therefore, I would suggest the following code
var userCityList = [];
$(document).on("change", ".checkboxes", function() {
var stateVal = $('#ResidentialLocationStateList').val();
var cityID = this.id;//stores city id
var cityVal = this.value;//stores city value
var finalDiv = $('#final');
var tempDiv = $('#othertempdiv');
if( this.checked ) {
if( userCityList.length < 5 ) {
userCityList.push( cityID );
finalDiv.append( this );
} else {
$(this).prop('checked', false);
alert('5 cities have been selected');
}
} else {
var index = $.inArray( cityID, userCityList );
if( index > -1 ) {
userCityList.splice( index, 1 );
tempDiv.append( this );
}
}
});
Since you're -- per comments below -- replacing the selected cities each time you select a new state, you would have to have a second div which would hold all the selected cities. Un-checking any of the cities in this final div would move it back; if another state is selected, such a city would be lost.
<div id="final"></div>
Use a multidimensional array to store both state and city IDs, like userCityList [ stateVal ]:
var userCityList = [];
$("#checkboxes").unbind('change').bind('change', function (event) {
var stateVal = $(':selected', $('#ResidentialLocationStateList')).val();
var cityID = $(event.target)[0].id;//stores city id
var cityVal = $(event.target)[0].value;//stores city value
if ($('#' + cityID).is(':checked')) {
if (userCityList.length < 5) {
if(!userCityList[stateVal])userCityList[stateVal] = [];
userCityList[stateVal].push(cityID);
}
else {
$('#' + cityID).prop('checked', false);
alert("5 cities have been selected");
return;
}
}//end if
if (!($("#" + cityID).is(':checked'))) {
if(userCityList[stateVal]){
//Edited, now it can remove the city by its position (index)
var position = $.inArray(cityID, userCityList[stateVal]);
userCityList[stateVal].slice(position, 1);
}
}
});
So when you need to retrieve the checked cities for an state you can do just:
for(var i =0; i < userCityList[stateVal].length; i++){
console.log(userCityList[stateVal][i]);
}
UPDATE
The hard work is done. Now, in your ajax code, when you load a new set of checkboxes, you have to check if the checkbox was previously checked:
$("#ResidentialLocationStateList").change(function () {
url = "/ResidentialBuilding/getCityList?state=";
state = $("#ResidentialLocationStateList").val();
url = url + state;
//console.log(url);
$("#checkboxes").empty();
$.getJSON(url, function (data) {
//console.log(data);
$.each(data, function (index, value) {
//console.log(value.city);
id = value.city;
id = id.replace(/\s+/g, '');
valCity = value.city;
valCity = valCity.replace(/\s+/g, '');
$("#checkboxes").append('<input value="' + valCity + '"' + 'type=' + "'checkbox'" + 'id=' + id + '>' + value.city + '</input><br>');
//Let's check if this checkbox was previously checked
if($.inArray(id, userCityList[state])){
//if yes, let's check it again
$('#'+id).prop('checked', true);
}
});
});
});
Keep in mind that the userCityList variable must be global to store these values and you will loose your checkboxes memories if you refresh the page, of course.

how to make input fields editable?

I have this fiddle which is having user tab.In user tab ,there are three fields which accepts name,mobile and email.When a user fills all the three and hits add button then a row is inserted.Now i want to make the new added row editable.This means that I want to keep 2 bootstrap buttons edit and delete.So if delete is pressed then the entire row will be deleted and if edit is pressed then the entire will be editable where user can change the mobile number,name and email.Can any body please tell me how to do.
This js code adds new rows
$('#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 + '" unchecked ></td>');
$(".span4").each(function () {
$tr.append("<td >" + $(this).val() + "</td>");
});
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;
val++;
} else {
alert("please fill the form completely");
}
This question is so specific to the OP scenario, so i will try to make the answer a bit more general.
I'm no expert here, but it seems you already capture the user's input and cloned it when they click Add to a new td. Therefore from what I understood is that you need to edit/delete the data from the new created td.
We have a table that contains several fields. We want to apply the following action on them
1- Add
2- Edit
3- Delete
Maybe this isn't the best practice, in short, my approach for this was to insert two spans for each data value:
One hidden that contains an input text field (inputSpan).
Another just contains plain text value (dataSpan).
Whenever you want to edit, dataSpan (just a data container) will disappear and inputSpan (text input field) appears instead enabling you to edit the text field. Once you edit and click Save the data in the text field will be cloned to replace the data in dataSpan. So basically dataSpan is just a reflection to inputSpan text field.
Here is an updated demo:
JSFiddle >> FullView Fiddle
I suggest for readability purposes, you break your code down into small function, it will make life easier, just sayin. So here general logic for your idea:
deleteRow = function (trID) {
// delete code goes here, remove the row
$(trID).remove();
}
manageEdit = function (tdNo) {
if ($("#edit-btn" + tdNo).html() === "Edit") {
$("#save-btn" + tdNo).show();//show save button
$("#edit-btn" + tdNo).html("Cancel");//change edit to cancle
editRow(tdNo);//call edit function
} else if ($("#edit-btn" + tdNo).html() === "Cancel") {
$("#save-btn" + tdNo).hide();//hide save button
$("#edit-btn" + tdNo).html("Edit");//change back edit button to edit
cancelEditRow(tdNo);
}
}
editRow = function (tdNo) {
$(".inputSpan" + tdNo).show();//show text input fields
$(".dataSpan" + tdNo).hide();//hide data display
}
cancelEditRow = function (tdNo) {
//looop thru 3 input fields by id last digit
for (var i = 0; i < 3; i++) {
//get input span that contain the text field
var inputSpan = $("#inputSpan" + tdNo + "-" + i);
//get the data span that contain the display data
var dataSpan = $("#dataSpan" + tdNo + "-" + i);
//text field inside inputSpan
var textField = inputSpan.find('input:text');
inputSpan.hide();//hide input span
textField.val(dataSpan.html());//take original data from display span and put it inside text field to cncle changes.
dataSpan.show();//show data span instead of edit field
}
}
saveRow = function (tdNo) {
//same as edit, but we reverse the data selection.
for (var i = 0; i < 3; i++) {
var inputSpan = $("#inputSpan" + tdNo + "-" + i);
var dataSpan = $("#dataSpan" + tdNo + "-" + i);
var textField = inputSpan.find('input:text');
inputSpan.hide();
dataSpan.html(textField.val());//take data from text field and put into dataSpan
dataSpan.show();
}
$("#edit-btn" + tdNo).html("Edit");//change text to edit
$("#save-btn" + tdNo).hide();//hide same button.
}
Here where I add the spans:
var tdCounter = 0;
$(".span4").each(function () {
var tid = val+"-"+tdCounter;
$tr.append("<td id='#mytd"+tid+"'>
<span id='inputSpan"+tid+"' class='inputSpan"+val+"' style='display:none'>
<input type='text' id='#input"+tid+"' value='"+ $(this).val() + "' /></span>
<span id='dataSpan"+tid+"' class='dataSpan"+val+"'>"+$(this).val()+"</td>");
tdCounter++;
});
Here I just append the buttons to call the functions, each button works for it's own row:
$tr.append("<td><botton id='edit-btn" + val + "' class='btn' onclick=manageEdit('" + val + "');>Edit</botton></td>");
$tr.append("<td><botton style='display:none' id='save-btn" + val + "' class='btn' onclick=saveRow('" + val + "');>Save</botton></td>");
$tr.append("<td><botton id='delete-btn" + val + "' class='btn' onclick=deleteRow('" + trID + "');>Delete</botton></td>");
Below is a sample function, it wont do everyhing you need, but it shows the jquery functions and one possibility how to do it. I only enabled editing name field, and deleting.
You would have to add other fields, + copy id data for the input.
js Fiddle
window.deleteRow = function (tar) {
$(tar).parent().remove();
}
window.editRow = function (tar) {
var row = $(tar).parent(),
cells, name;
cells = row.find("td");
name = $(cells.get(1)).text();
$(cells.get(1)).text('');
$(cells.get(1)).append('<input type="text" value="' + name + '">');
}
window.saveData = function() {
var data = {};
data.name = "some name";//get this from your input
data.email= "some email";//get this from your input
data.phone= "some phone";//get this from your input
$.get("http://yourphpsite.com", data, function(data, status) {
//data contains your server response
if (data.somepositiveservermessage) {
$("#user_notification_field").text("data saved");
$("#user_notification_field").show();
});
}

Unable to get the Text box value in Javascript

I am using Jquery Tokeninput to select multiple values but when i tried to select the values in text box it's always coming blank I am using below Jquery function to retreive the val.
Please refer to to my previous question on stack Here
var values = $("#txtTest").val();
$("#Button1").click(function() {
alert(values);
return false;
});
Please find the screen shot or same.
The text box is not actually what holds the selections its a list
$("#Button1").click(function() {
var txt = '';
$("#txtTest").prev('ul').find('li:not(:last-child)').each(function(){
txt += $(this).text()+ " ";
});
//alert(val());
alert(txt);
return false;
});
EDIT
That's just a hack to get what you wanted but the library has a method to get the values in the list selector.tokenInput("get");
$("#Button1").click(function() {
var txt = '';
$.each($("#txtTest").tokenInput('get'), function(){
txt += this.id + " " + this.name;
});
//alert(val());
alert(txt);
return false;
});
USe
var values = $("#txtTest").attr('value');

Categories