Custom Formatted Checkbox YUI, does not remembers the state - javascript

Please refer to the jsfiddle : http://jsfiddle.net/jLmm2/3/
{
key: "CustomeCheckbox",
label: "<input type='checkbox' id='SelectAll'> Select<br/>All",
formatter: function (elCell, oRecord, oColumn, oData) {
if (status == 'on') {
elCell.innerHTML = '<input type="checkbox" name="TRANSFER" ></input>';
} else {
elCell.innerHTML = '<input type="checkbox" name="TRANSFER" disabled="true" ></input>';
}
}
I have a custom formatted checkbox : CustomeCheckbox and a standard checkbox : Select in my datatable : container
The issue is CustomeCheckbox, does not remembers the checked state when trying to sort the table.
Can you please help me in this !!
Thanks
I have updated the YUI to update the underlying recordset in case checkbox is checked.Standard checkbox is behaving as required, but the custom formatted checkbox is still not retaining the state
dt.subscribe('checkboxClickEvent', function(oArgs) {
var elCheckbox = oArgs.target;
var elRecord = this.getRecord(elCheckbox); //record of the coloumn
var elColumn = this.getColumn(elCheckbox);
var name = elRecord.getData("Select1"); // Data in that record for the field
//alert("Checkbox was " + (elCheckbox.checked ? "" : "un") + "checked for " + name);
//alert(elCheckbox.checked);
this.getRecordSet().updateKey(elRecord, elColumn.key, elCheckbox.checked);
});

You have to listen to clicks on the checkbox and store the state in the underlying record. The table is drawn out of the record, what doesn't get to the record, it is forgotten.
See how to handle various types of controles here

Related

how to retrieve dynamically added checkbox selected value

I am adding checkbox dynamically to my html page. how can i retrieve the values when user makes selection.
var sources = source_names_list;
$.each(sources, function(index,value) {
// var checkbox1 = "<label for="+test+"<input type='checkbox' id=\"+test+\" value=\"+test+\" name=\"+test+\"></label>"
// var checkbox="<label for="+value+">"+value+"<input type='checkbox' id="+value+" value="+value+" name="+value+"></label></br>"
var checkbox1 = "<p><label><input type=\"checkbox\" id="+value+" class=\"filled-in\"/><span>" + value + "</span></label></p>"
$("#sources").append($(checkbox1));
});
I tried accessing them using their id and it didn't work.
You could get the values using the class name filled-in as a selector. You will also need to add a value to each generated checkbox.
// Sources
var source_name_list = ['news' , 'info', 'article', 'newyork,items'];
// Create all the checkboxes (adding a value to each one)
$.each(source_name_list, function(index,value) {
var checkbox = '<p><label><input type="checkbox" id="'+value+'" value="' + value + '" class="filled-in" /><span>' + value + '</span></label></p>';
$("#sources").append($(checkbox));
});
// "get selected" button
$('#get').click(function() {
// Create an array for the values
var values = [];
// Select all checkboxes by class name, and use the jQuery :checked special selector
$('.filled-in:checked').each(function() {
// Adds the value to the values array
values.push($(this).val());
});
// Log all values
console.log(values);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sources"></div>
<a id="get">Get selected</a>

Retrieving a value from innerHTML or textContent using JQuery map function

Using information I found in this question I have been able to retrieve my driver information, and combining it with rowIndex place it in the correct cell.
reservations.rows[whichRow].cells[7].innerHTML = which_driver;
reservations.rows[whichRow].cells[7].textContent = which_driver;
I've tried both and the proper data shows.
Now using information I found in another question (I can't find it) I have been using this function to retrieve the values as I loop through the selected rows (checkbox)
<script type="text/javascript">
$(function()
{
$('#submitButton').click(function(){
var values = $("#main_table table input[name=name]:checked").map(function() {
row = $(this).closest("tr");
return {
recordid : $(row).find('input[name=record_id]').val(),
firstname : $(row).find('input[name=firstname]').val(),
lastname : $(row).find('input[name=lastname]').val(),
timeneeded : $(row).find('input[name=timeneeded]').val(),
dateneeded : $(row).find('input[name=dateneeded]').val(),
pickup : $(row).find('input[name=pickup]').val(),
dropoff : $(row).find('input[name=dropoff]').val(),
drivername : $(row).find('textContent[name=driver_name]').val()
}
}).get();
console.log(values);
});
});
When I view the objects in the console all the other fields show the correct, but driver name is 'undefined'.
Is there a way to grab that information or a way to put the data from the popup into the "value" of the proper cell. So far, I haven't been able to get that data to show.
Thank you
Here's the actual from the HTML -
"<td id="driverlist" width='125' align='left' onClick="selectValue('id',this)" value="?" > <input type="text" id="driver_name" name='driver_name' "size='15' style='font-weight: 700' value=''"> </td>"
When the user clicks in the field it fires a function that returns the rowIndex and then fires the Popup, once a person is selected then it returns the value and fills in the proper cell –
I modified the map function to read
drivername : $(row).find('textContent[name=driver_name]').text()
and now it at least returns "" and not undefined. –
The solution was to use
: $(row).find('td:eq(7)').text()

How can I capture checkboxes that I'm creating programmatically?

In my code below, I'm pulling in data from SharePoint (basically an excel spreadsheet) and displaying on my page. Checkboxes are pushed to my page using .innerHTML and are given an ID programmatically.
My question: How can I determine whether those checkboxes are checked (being that they could be different each time my app loads) ?
(Once I know what is checked, I'll display more metadata on the next page based on the checks - that part I have figured out)
$.ajax({
url: "myWebsite",
type: "GET",
headers: { "ACCEPT": "application/json;odata=verbose" },
success: function(data){
$.each(data.d.results, function(index) {
var $this = $(this);
var courseName = $this.attr('Title');
var courseNumber = $this.attr('Course_x0020_Number');
var courseUrl = $this.attr('URL');
var trainingGroup = $this.attr('Training_x0020_Group');
var recurrence = $this.attr('Recurrence');
if (trainingGroup == 'Group1') {
if (recurrence == "Don't Specify") {recurrence = '';
} else recurrence = " ("+recurrence+")";
document.getElementById('officeListSpan').innerHTML += '<ul class="courseLists"><li><input type="checkbox" id="'+courseName.replace(/\s+/g, '')+'"/>'+courseName+recurrence+'</li></ul>';
}
if (trainingGroup == 'Group2') {
if (recurrence == "Don't Specify") {recurrence = '';
} else recurrence = " ("+recurrence+")";
document.getElementById('labListSpan').innerHTML += '<ul class="courseLists"><li><input type="checkbox" id="'+courseName.replace(/\s+/g, '')+'"/>'+courseName+recurrence+'</li></ul>';
}
});
},
error: function(){
alert("Failed to query SharePoint list data. Please refresh (F5).");
}
});
You will need a way to know how many checkboxes has been created. When creating the checkboxes, them id must have a generic name and a number, for example id="checkbox0", id="checkbox1 and so on, then write the ammount of checkboxes in some part of the html code and put it some hidden tag. Then when reading the checkboxes data read the ammount of checkboxes and do a for
function getCheckboxes(){
var ammount = parseInt(document.getElementById("checkBoxesAmmount"));
var checkbox;
for(var i = 0; i<ammount; i++){
checkbox = document.getElementById("checkbox"+i);
//do staff
}
return;
I hope this works for you c:
This bit of jQuery returns all the checked input boxes that are in a ul with the class courseList:
jQuery('ul.courseList input:checked')
If your question is asked because the course name might change (your checkbox IDs are based on the course name), I suggest switching to the course number instead (or an appropriate mix of the two).
If you want to know if your dynamically created checkboxes were checked and want to do this via Javascript before the form is submitted, then add a class to your checkboxes (say dynamicCourse) and look for get the checked checkboxes via jQuery('input.dynamicCourse:checked').
Also, your checkboxes in your example don't have a value attribute set. If you're submitting it to a backend, you'll probably want it to have some value (course number would be my suggestion from the looks of it).

How to get a count of checkboxes checked on pagination Jquery dataTables

Below is my code, I want to get the count of checked checkboxes of all pages in my DataTable. Please advice how to proceed
<td align="center"><input type="checkbox" align="center" id="all" class="groupCheckBox" name="emails[]" value=' . $user['id'] . '></td>
Below code I used for get the values of checked boxes in all pages on button click
$('#merge_button').click(function () {
var id = "";
var oTable = $("#userTable").dataTable();
$(".groupCheckBox:checked", oTable.fnGetNodes()).each(function () {
if (id != "") {
id = id + "," + $(this).val();
} else {
id = $(this).val();
}
document.getElementById("email").value = id;
});
});
but now I want to count the checkedboxes without button click function whenever user clicked on checkboxes and deduct count when unchecking boxes . pls advice
var table = $("#userTable").DataTable();
var countchecked = table
.rows()
.nodes()
.to$() // Convert to a jQuery object
.find('input[type="checkbox"].groupCheckBox:checked').length;
Uses the most recent API
"...please be aware that using deferRender will cause some nodes to be created only when they are required for display, so they might not be immediately available when this method is called." from https://datatables.net/reference/api/rows().nodes()
Quite easy.
$("td input[type='checkbox']:checked").length;

How to select a dynamically generated form element in jquery / javascript using its ID?

I am trying to create a row of 3 form fields dynamically when the user clicks on the ADD button / plus symbol .
Javascript code used to create the form elements is below :
<script type="text/javascript">
var field_counter = 1;
var field_limit = 5;
species = document.getElementById('species');
breed = document.getElementById('breed');
function addInput(divName){
if (field_counter == field_limit) {
alert("You have reached the limit of adding " + field_counter + " inputs");
}
else {
var dynamic_species = 'species'+field_counter; //dynamic id for species
var dynamic_breed = 'breed'+field_counter; //dynamic id for breed
var dynamic_quantity = 'quantity'+field_counter; //dynammic id for quantity
var dynamicForm = '<div class="form-group"><div class="col-md-4"><label for="'+dynamic_species+'">Animal Type</label><select class="form-control input-sm '+dynamic_species+'" id="'+dynamic_species+'"><option></option></select></div>';
dynamicForm+='<div class="form-group"><div class="col-md-4"><label for="'+dynamic_breed+'">Breed</label><select class="form-control input-sm '+dynamic_breed+'" id="'+dynamic_breed+'"><option></option></select></div>';
dynamicForm+='<div class="form-group"><div class="col-md-2"><label for="'+dynamic_quantity+'">Quantity</label><input type="number" name="quantity_export" id="'+dynamic_quantity+'" class="form-control input-sm '+dynamic_quantity+'" /></div>';
var newdiv = document.createElement('div');
newdiv.innerHTML = dynamicForm;
document.getElementById(divName).appendChild(newdiv);
document.getElementById(dynamic_species).innerHTML = species.innerHTML;
document.getElementById(dynamic_breed).innerHTML = breed.innerHTML;
field_counter++;
}
}
</script>
<div class="col-md-2" >
<label for=""> </label>
<i onclick="addInput('dynamicInput');" style="cursor: pointer; border: none;" class="fa fa-plus form-control input-sm">Add</i>
</div>
Using the above code am creating the form fields "Animal Type , Breed and Quantity ", all together in a row as shown in the image . Maximum number of rows that can be added is limited to the value of the variable "field_limit".
The value of the drop downs are initially populated from the parent drop down using the code :
species = document.getElementById('species');
breed = document.getElementById('breed');
document.getElementById(dynamic_species).innerHTML = species.innerHTML;
document.getElementById(dynamic_breed).innerHTML = breed.innerHTML;
Question : How can I select the dynamically generated ID of the new form fields .
Here is the script am using to select the first row of form fields which is in the HTML when the page loads for the first time :
$("#species").change(function(){
$('#breed').empty();
//alert($(this).val());
var param = {'id':$(this).val()};
$.ajax({
type : 'POST',
url : '<?php echo base_url();?>select_breed',
dataType : 'json',
data: param,
success : function(data)
{
var select = $('#breed');
select.empty().append(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown)
{
alert(XMLHttpRequest.responseText);
}
});
});
The second row of form fields are created dynamically with the following ID's
First Field : Animal Type : ID="species1"
Second Field : Breed : ID="breed1"
Third Field : Quantity : ID="quantity1"
I am not able to select the dynamically generated form fields using the jquery selector :- eg: $("#species1").change(function(){}); , it is not working .
What I am trying to do ?
I need to get the value of these fields using its ID attribute. Any help would be highly appreciated . Thank you .
Use event delegation for dynamic generated content like so :
// change `document` to top level parent that existed on page or
// parent container
$(document).on("change", "#species1", function(){...});
Thats because they do not exists yet when binding to it's change event.
You could add the event listener in the add_input function, or use a more abstract event handler:
$("form").on("change", ".species", function () {
var id = $(this).attr("data-id");
...
});
This will require you to drop the ID's and use class attributes instead. Which is the way to go by my opinion.
You can attach the ID's using $(speciesElement).attr("data-id", id).

Categories