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>
Related
I have a sidebar with checkboxes (<input>) and corresponding names (<a>).
I can't get values from <a> tags.
I need when user ticks checkboxes and presses the button to get values of corresponding names and pass the names to a backend function to get calendars for that names from sheet data.
I wrote this code and logged the data (logged the names param at the very beginning of a backend function) and there were correct names in the log at first.
But then without changes to the code I stopped receiving any logs, so I assumed the backend function stopped being called.
What's wrong with my code?
//get button by id, on click run function
document.getElementById("btn").addEventListener("click", requestCheckedCalendars)
The client-side functions:
//getting checked checkboxes and names
function getCheckedNames() {
//getting all checkboxes
var allCheckboxes = Array.from(document.getElementsByClassName("filled-in"));
//getting all <a> tag elements as a native Array.
var names = Array.from(document.getElementsByTagName("a"));
var namesArr = []
for (var i = 1; i < allCheckboxes.length; i++) {
//checked/unchecked property of a checkbox
var check = allCheckboxes[i].checked
//if checked
if (check === true) {
//shift to get corresponding names
var j = i + 1
//getting a name value
var name = names[j].firstChild.nodeValue;
//pushing a name to the array
namesArr.push(name)
}
}
return namesArr
}
//getting calendars for chosen names from backend
function requestCheckedCalendars() {
var chosenNames = getCheckedNames();
// Submit these names to the backend, to receive their calendar events.
google.script.run
.withUserObject(chosenNames)
.withSuccessHandler(requestCalendarEvents)
.loopToGetCals(JSON.stringify(chosenNames))
}
An Html template - I created <a> elements containing names while was looping script properties:
//creating a new <a> tag
var newATag = document.createElement("a")
//set a class to a new tag
newATag.setAttribute("class", "collection-item");
// add the URL attribute
newATag.setAttribute("href", "https://www.blah.com");
//setting unique IDs
newATag.setAttribute("id", "a" + i);
// Add names to it
var newText = document.createTextNode(name);
//append the text with names to the tag
newATag.appendChild(newText);
//add item to the mother collection element
collection.appendChild(newATag);
The collection element (where I put my <a> elements) is from MaterialixeCss site:
<div class="collection" id = "coll">
</div>
//collection element from Materializecss site
var collection = document.getElementById("coll")
Getting Values from Checkboxes
html fragment:
<br /><input type="checkbox" id="chk1" name="Checks" value="1" /><label for="chk1">One</label>
<br /><input type="checkbox" id="chk2" name="Checks" value="2" /><label for="chk2">Two</label>
<br /><input type="checkbox" id="chk3" name="Checks" value="3" /><label for="chk3">Three</label>
<br /><input type="button" id="chkbtn" value="SaveChecks" onClick="saveChecks();" />
JavaScript:
function saveChecks() {
var chA=document.querySelectorAll('input[type="checkbox"][name="Checks"]:checked');
var cbA=[];
console.log('Checkboxes: %s',JSON.stringify(chA));
for(var i=0;i<chA.length;i++) {
console.log('id: %s name: %s value: %s',chA[i].id,chA[i].name,chA[i].value);
cbA.push({id:chA[i].id,name:chA[i].name,value:chA[i].value});
}
google.script.run.displayCheckBoxes(cbA);
}
Some Google Script to display values:
function displayCheckBoxes(chA) {
var ss=SpreadsheetApp.getActive();
var html='';
for(var i=0;i<chA.length;i++) {
html+=Utilities.formatString('<br />id: %s name: %s value: %s', chA[i].id,chA[i].name,chA[i].value);
}
var userInterface=HtmlService.createHtmlOutput(html);
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Checked Boxes');
}
The Rendered Html:
The Rendered dialog:
Values from anchors
function getAnchors() {
var aA=document.getElementsByTagName("a");
for(var i=0;i<aA.length;i++) {
//for(key in aA[i]){console.log('key: %s value: %s',key,aA[i][key]);} //display all possible values
console.log('href: %s text: %s',aA[i].href, aA[i].text);
}
}
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;
$ctr = 0;
foreach($authspons as $authspons_list){
$ctr++;
echo "<input type='checkbox' id='id_list'".$ctr."'"." name='authspons[]'"." class='list_check' value='".$authspons_list->authspons_position." ".$authspons_list->authspons_lname.",".$authspons_list->authspons_fname." ".$authspons_list->authspons_mname." ".$authspons_list->authspons_cmpny.'; '."'".">" .$authspons_list->authspons_position." ".$authspons_list->authspons_lname.",".$authspons_list->authspons_fname." ".$authspons_list->authspons_mname." ".$authspons_list->authspons_cmpny."</input> <br />";
echo "<input type='text' class='text_list' id='tbox".$ctr."'"."name='authsponsid[]' value='".$authspons_list->authspons_id."; "."'"." >";
}
I have a generated list coming from database, the checkboxes contains the personal details, while the textboxes contains the "ID" of each items in the checkboxes.
This is my jquery code:
$('#list').click(function(){
var final = '';
var final2='';
$('.list_check:checked').each(function(){
var values = $(this).val();
final += values;
var val_id = $('.text_list').val();
final2 +=val_id;
});
$("#coauth").val(final);
$("#coauthid").val(final2);
$("#coauthspons").modal("hide");
});
Getting value from checkboxes is okay. My problem is: the output from the textbox is always the last value of the number of checkboxes that is checked.
Like this:
1st checkbox = 1st textbox(value="1");
2nd checkbox = 2nd textbox(value="2");
when i check the two options, the textbox only results to:
1st checkbox = 1st textbox(value="2");
2nd checkbox = 2nd textbox(value="2");
How do I get the result of each of the expected checkbox and its textbox value?
here var val_id = $('.text_list').val();
you are giving the same value for all the elements irrespective of their index
try like this
var val_id = $(this).next().val(); //this gives value of next i.e .text_list element
$('#list').click(function(){
var final = '';
var final2='';
$('.list_check:checked').each(function(){
var raw_value = $(this).val();
var id_value = raw_value.split("||");
var values = id_value[1];
final += values;
var val_id = id_value[0];
final2 +=val_id;
});
$("#coauth").val(final);
$("#coauthid").val(final2);
//alert(final2);
$("#coauthspons").modal("hide");
});
Thanks #Bhadra for your answer. it gives me an idea but I found a better solution to my own problem. I put all the values in the checkbox then I use split function to separate the "ID" from the original checkbox values(fname,mname,lname).
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
I have 5 asp.net checkboxes in webform ...i want as the checkboxes checked and unchecked then its text will be added in textbox i.e if checkbox 1 and checkbox9 will be checked then in textbox the text will be 1,9 and if checkbox1 is unchecked then the textbox text will be 9
How to do this using javascript, vb.net or Jquery
I dont have any idea how to do it ...
CODE I FOUND :
<script type="text/javascript">
function Test(control, value) {
var str = '';
$('#<%=txtTest.ClientID %> :checked').each(function() {
str = str + ', ' $(this).val();
});
$('#<%=txtTest.ClientID %>').val(str);
</script>
ITS NOT WORKING ...
Something like this, you need to give the checkboxes a class of checkBoxClass. The following has NOT been tested!
$(function() {
$(".checkBoxClass").each("click", function() { // whenever a checkbox is clicked
var str = "";
/* get all checked checkboxes of this name - class can be used too,
but using name, you can have sets of checkboxes */
$("input[name=$(this).attr('name')] :checked").each(function() {
str += ", " + $(this).val(); // append the value
});
// add it to the textfield, if there is something to add
$("#<%=txtTest.ClientID %>").val(str?str.substring(2):"");
});
});