I am creating a table at run time using Jquery and binding the unique id to the checkbox.
$.getJSON('/api/Test/SelectionList' + '/' + ID)
.done(function (data) {
$.each(data, function (key, val) {
var myRow = $("<tr/>");
//$("<td> <input type='checkbox' ></input> </td>").text(val.IsActive).appendTo($(myRow));
var items = "";
items += '<input type="checkbox" id=' + val.FacilityID + ' ';
if (val.IsSelected) {
items += 'checked/>';
}
else {
items += '/>';
}
//$("<td/>").text(val.IsActive).appendTo($(myRow));
$("<td> " + items + "</td>").appendTo($(myRow));
$("<td/>").text(val.Facilityname).appendTo($(myRow));
$("<td/>").text(val.RegionName).appendTo($(myRow));
$("<td/>").appendTo($(myRow));
myRow.appendTo($("#Table"));
});
})
User can check and uncheck the checkboxex, On click of save i want to store the value of (table) all check boxex with checked/unchecked state with the ID.
I want to loop through the full table, and store the data as id#1 for checked box and id#0 for unchecked box in a same array.
I am bit new to jquery, So not getting the syntax. Please suggest.
Updated, here is the fiddle http://jsfiddle.net/MQQSv/1/
<table>
<tr>
<td>one</td>
<td>
<input type="checkbox" id='1' checked/></td>
</tr>
<tr>
<td>two</td>
<td>
<input type="checkbox" id='2' /></td>
</tr>
</table>
$('#save-btn').on('click', function() {
var output = []
$("table td input[type=checkbox]").each(function(){
id = $(this).attr("id");
output.push( id + "#" + ($(this).is(":checked") ? "1" : "0"))
})
console.log(JSON.stringify(output));
})
you can try this :
push id into two different array
$(document).ready(function() {
// bind click event to save-btn
$('#save-btn').on('click', function() {
// init two array
// (if you want to use var out of on's callback function, you need to do declaration outside)
var checkedList = [],
uncheckedList = [];
// push ckecked id into checkedList
$('input:checked').each(function() {
checkedList.push($(this).attr('id'));
});
// push unckecked id into uncheckedList
$('input').not(':checked').each(function() {
uncheckedList.push($(this).attr('id'));
});
});
});
Related
I have a list of radio button and table. If one radio button is checked I want to add the value of it to the table and hide it from the radio button list. Also, if the value is deleted from the table, I want to show it back in the radio button list. Any ideas please on how to do that.
My Radio button:
foreach (var item in Model.ServicesList)
{
<div class="col-md-4">
<div class="funkyradio-default">
#Html.RadioButtonFor(model => model.SelectedServiceID, #item.ServiceID, new { #class = "form-control ", #id = #item.ServiceID, #required = "required", title = "يرجى أختيار الخدمة" })
<label name="ServiceName" id="ServiceName_#item.ServiceID" for="#item.ServiceID"> #item.ServiceName</label>
#Html.ValidationMessageFor(model => model.SelectedServiceID, "", new { #class = "validation-label" })
</div>
</div>
}
My table:
<div class="row ">
<div class="col-6">
<table class="table main-table" id="ServicesTable">
</table>
</div>
</div>
MY Jquery fuction to add selected values to table. It is working fine, but I did not know how to hide the radio button if it is already selected and its value is added to the table.
function AddNewService() {
var SelectedServiceID = $('[name="SelectedServiceID"]:checked').val();
$.ajax({
type: "Post",
url: '/IndividualLicense/CheckServiceRequirment',
data: { "SelectedServiceID": $('[name="SelectedServiceID"]:checked').val(), "MainServiceID": $('#MainServiceID').val() },
success: function (data) {
if (data.Result == true) {
var table = document.getElementById("ServicesTable");
var Services = [];
Services.push({
'SelectedServiceID': SelectedServiceID,
'MainServiceID': $("#MainServiceID").val(),
'ServiceName': $("#ServiceName_" + SelectedServiceID).text(),
});
for (i = 0; i < Services.length; i++) {
var content = "<tr style='border-bottom: 1px solid #dee2e6;'>"
for (i = 0; i < Services.length; i++) {
content += '<td>' + Services[i].ServiceName + '</td>';
content += "<td><div><button id='" + Services[i].SelectedServiceID + "' class='btn btn-view delete' name='delete' type='button'>حذف</button></div></td>";
content += '<td style="display:none">' + Services[i].SelectedServiceID + '</td>';
content += '<td style="display:none">' + Services[i].MainServiceID + '</td>';
}
content += "</tr>"
$('#ServicesTable').append(content);
}
}
});
}
The easiest way is to use data attribute .. see the next example
$(document).ready(() => {
// checkbox change event when input checked/unchecked
$(document).on('change', 'input:checkbox' , (e) => {
if(e.target.checked){ // if checked
const serviceID = $(e.target).val(); //get its value
$(e.target).closest('li').remove(); // remove the closest li
$('table').append(rowHTML(serviceID)); // append to the table with id value
}
});
// delete the row
$(document).on('click' , ".btn.delete" , (e) => {
const get_row = $(e.target).closest('tr'); // get closest row/tr
const get_row_id = get_row.attr('data-serviceID-row'); // get the data-serviceID-row from <tr data-serviceID-row="5">
get_row.remove(); // remove the row
$('ul').append(inputHTML(get_row_id)); // append the li with input to the ul
});
});
// The HTML
function rowHTML(serviceID){
return '<tr data-serviceID-row="'+ serviceID +'"><td>Service ID '+ serviceID +'</td><td><span class="btn delete">Delete</span></td></tr>';
}
function inputHTML(serviceID){
return '<li><input type="checkbox" value="'+ serviceID +'" />Service ID '+ serviceID +'</li>';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr data-serviceID-row="5">
<td>Service ID 5</td>
<td><span class="btn delete">Delete</span></td>
</tr>
</table>
<h3>CheckBoxes</h3>
<ul>
<li><input type="checkbox" value="1"/>Service ID 1</li>
<li><input type="checkbox" value="2"/>Service ID 2</li>
<li><input type="checkbox" value="3"/>Service ID 3</li>
<li><input type="checkbox" value="4"/>Service ID 4</li>
</ul>
I have dynamically generated checkbox based on JSON data and that is generated by jQuery. I need to dynamically generate checkbox class name. Here is my code that is generated a checkbox
<td>
<label class="switch">
<input
id="chkEnabled"
checked
type="checkbox"
onchange="checkedorUncheked(' + result.data.resultSet[i].id + ',' + count + ')" class="chkEnabled"' + count +' >
<span class="slider round"></span>
</label >
</td>
Here class="chkEnabled"' + count +' I'm incrementing class value but when I call the method checkedorUncheked I get count value but not getting the class value. Here I console it
` this.checkedorUncheked = function (item, item2) {
//console.log('.chkEnabled' + item2);
$('.chkEnabled' + item2).change(function () {
console.log(item2);`
I'm not able to console inside change event because of class name.
when HTML elements are dynamically generated, you need to rebind the events of the generated element
Try
this.checkedorUncheked = function (item, item2) {
//console.log('.chkEnabled' + item2);
$('.chkEnabled' + item2).on('change',function () {
console.log(item2);
Use on() method instead of directly using .change(), but in comments as suggested don't generate class, generate Id instead and use the same.
then code becomes
$('#chkEnabled' + item2).on('change',function () {
console.log(item2);
UPDATE
<input
id=' + result.data.resultSet[i].id + '
checked
type="checkbox"
onchange="checkedorUncheked(this);" count=' + count +' >
<span class="slider round"></span>
function checkedorUncheked (e){
var itme1 = $(e).attr('id'); /// for id
var item2 = $(e).attr('count'); // count
if($(e).prop('checked') == true){
//do something
}
else{
/// do another
}
}
I want to loop through a form with Javascript but my problem is that I have another form in the first form.
I'd like to loop through the first form only, not the inner one. I found this method on an other post :
var table = $("#table_cultures tbody");
table.find('tr').each(function (i) {
var $tds = $(this).find('td'),
productId = $tds.eq(0).text(),
product = $tds.eq(1).text(),
Quantity = $tds.eq(2).text();
// do something with productId, product, Quantity
alert('Row ' + (i + 1) + ':\nId: ' + productId
+ '\nProduct: ' + product
+ '\nQuantity: ' + Quantity);
});
This method works but loop through the both forms.
EDIT 1 :
The html looks like :
<form>
<table>
<tr>
<td>Something here</td>
</tr>
<tr>
<td>
<form>
<table>
//tr td ...
</table>
</form>
</td>
</tr>
</table>
</form>
nesting of <form> elements is not allowed
please see:
https://www.w3.org/TR/html5/forms.html#the-form-element
"...Flow content, but with no form element descendants..."
I have a html table with 4 columns and multiple rows
column1 : simple text
column2 : simple text
column3 : select list with 2 values
column4 : Button that performs some operation
At run time, I want to get the selected / entered values for all the columns of that row against which column4 button is clicked. I know a little of JavaScript/jQuery.
Here is the static table code
<table id="invoiceTbl" border="1">
<thead>
<tr>
<th>Broker info</th>
<th>Receivable Amount</th>
<<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody></tbody>
</table>
And I am populating table i.e. inserting data on AJAX call like this:
$.ajax({
type: "POST",
data: $('#searchDetails').serialize(),
async: false,
cache: false,
url: "/opsadmin/search.json",
dataType: 'json',
success: function (result) {
var i = 1;
$.each(result, function (index, value) {
alert(index + ": " + value.brokerInfo);
$('table#invoiceTbl TBODY').append('<tr> <td>' + i + '</td><td>' + value.brokerInfo + '</td><td>' + value.receivableAmount + '</td><td><select name="act" id="s"><option>PENDING</option><option>CLEARED</option></select></td><td><input type="button" value="Process" onclick="updateStatus(\'' + index + '\')"</input></td></tr>');
i++;
});
}
});
return false;
First set the unique ID to each of your "select" with help of index like:
'<select name="act" id="s'+ index +'">'
and pass the index with "updateStatus(index)" function call.
function updateStatus(index) {
$('#s'+index).val(); // value of selected box.
}
$("#invoiceTbl input[type=button]").click(function(e){
$(e.target).closest("tr").find("td").slice(0,2).each(function(){
console.log($(this).text());
});
});
On #button click you will get an array (arr) that holds the values of the clicked row cells:
$('#button').on('click', function() {
var arr = [];
$(this).closest('tr').find('td').each(function() {
var that = $(this);
if (that.find('input[type="text"]').length > 0) {
arr.push(that.find('input[type="text"]').val());
} else if (that.find('select').length > 0) {
arr.push(that.find('select').val());
} else {
arr.push(that.text());
}
});
alert(arr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>text</td>
<td>text2</td>
<td>
<select>
<option value="opt1">opt1</option>
<option value="opt2">opt2</option>
<option value="opt3">opt3</option>
</select>
</td>
<td><button id="button">Click</button></td>
</tr>
</tbody>
</table>
There's already a few good answers, but my solution is a bit different:
$("#invoiceTbl tr").each(function(){
var select = $(this).find("select");
var button = $(this).find("button");
button.click(function(){
alert(select.val());
});
});
If you also want the content of the other columns, that's a bit more difficult:
$("#invoiceTbl tr").each(function(){
var tr = $(this);
var button = $(this).find("button");
button.click(function(){
tr.find("td").each(function(){
var select = $(this).find("select");
var td_button = $(this).find("button");
if(!td_button.length)
{
if(select.length)
console.log(select.val());
else
console.log($(this).text());
}
});
});
});
Check out https://jsfiddle.net/cgfjewoe/ to see it run.
I'm developing an app who can register for university courses. they add select their register type,course type ,batch and their subjects. i'm putting subjects on the table when they selecting a course type also the batch. So they can select subjects, after they add it will put into the selected subjects table. My code will work on when they are working # first time. but suddenly they are changed they are register type,course type and batch it will list down the subjects. BUT when they selecting a subject it will add two table trs to the selected subjects Tables. Why is that ?
JQUERY
$("#subjectsTable").on('change', '.selectedSubjects', function (event) {
event.stopPropagation();
var selectedReg = $('#CouserFinder option:selected').val();
var selectedCouse = $('#CourseSet option:selected').val();
var selectedBatch = $('#alreadyBatchSorting option:selected').val();
if(selectedBatch != "Select Your Batch"){
var shouldChecked = $("#CT_No_Of_SubjectsCount").val();
var bol = $(".selectedSubjects:checkbox:checked").length >= shouldChecked;
$(".selectedSubjects:checkbox").not(":checked").attr("disabled",bol);
if ($(this).is(":checked")) {
var indexChecked = $(this).closest("tr").attr("data-index");
alert(indexChecked);
var selectedSCode = $(this).closest("tr").find(".selectedSCode").text();
$("#selectesSubjectsRecodes tr:last").after("<tr data-index=" + indexChecked + "><td>" + selectedReg + "</td><td>" + selectedCouse + "</td><td>" + selectedSCode + "</td><td>" + selectedBatch + "</td></tr>");
} else {
var indexAdded = $(this).closest("tr").attr("data-index");
var findRow = $("#selectesSubjectsRecodes tr[data-index='" + indexAdded + "']");
findRow.remove();
}
}
else{
alert("Warning!: Select Your Batch");
$(this).prop('checked', false)
}
});
HTML
<tr class="success" data-index="10">
<td>
<input class="selectedSubjects" type="checkbox" name="selectedSubjects">
</td>
<td class="selectedSCode">BCS-DIP-UID</td>
<td class="selectedSName">UID</td>
</tr>
SELECTED SUBJECT CODE (get it from the DOM )
<tr data-index="10">
<td>BCS-DIP-S3</td>
<td>BCS-DIP</td>
<td>BCS-DIP-UID</td>
<td>BCS-DIP-APR/2014-002</td>
</tr>
<tr data-index="10">
<td>BCS-DIP-S3</td>
<td>BCS-DIP</td>
<td>BCS-DIP-UID</td>
<td>BCS-DIP-APR/2014-002</td>
</tr>
Screen Shot
As you can see it will adding two trs.why is that ?
You are binding a new event handler to $("#subjectsTable .selectedSubjects") every time you call that function. The problem will stem from the fact that your javascript is in a function which is being called multiple times.