I have several checkboxes on my page that each correspond to different courses. When the user checks the checkbox I want to sent a POST request to the server to add details of their enrollment to the database.
I have the following jQuery to take note of the change:
$(function () {
$("input:checkbox").change(function () {
var fullURL = document.URL;
var url = fullURL.split('userID=');
var userID = url[1];
var courseID =
alert(userID + "and " + courseID);
$.post('/Admin/EnrolUser/', postData, function (data) {
});
});
});
On my page there are several checkbox inputs, how can I retrieve the value of the selected checkbox that fired the event and set this to the var courseID variable.
Every jQuery function that deals with collections set's the value of this to be the current element.
So...
$("input:checkbox").on("change", function(){
$(this).val(); //Element that fired event
});
Inside your change function the variable this represents your checkbox.
$("input:checkbox").change(function () {
var fullURL = document.URL;
var courseID = $(this).val();
alert(courseID);
});
jsfiddle here
Related
I have a jsp page with a checkbox declared like so
<form:checkbox path="affProgramSessionList[${status.index}].programSessionDetailId" id="checkbox_${session.id}" data-id="${session.id}" value="${session.id}" />
it is contained within a for loop and basically a checkbox is displayed for each session. That all works fine and I have no issues.
currently when a check box is checked this function is ran
$("input[id*='checkbox_']").each(function () {
$(this).click(function(){
var dataid = $(this).attr("data-id");
var divId = "fullAttendence_" + dataid;
var divIdAttendee = "attendeeType_" + dataid;
$('#' + divId).toggle(this.checked);
$('#' + divIdAttendee).toggle(this.checked);
});
});
This then results in some other checkboxes being checked and some divs that were hidden being shown.
I am now adding in functionality for if someone had checked some check boxes and saved and comes back to the page then those check boxes will be checked.
I have that part working but I can't get the function to run properly.
I have the following
if ($("input[id*='checkbox_']").is(':checked')) {
var dataid = $(this).attr("data-id");
var divId = "fullAttendence_" + dataid;
var divIdAttendee = "attendeeType_" + dataid;
$('#' + divId).toggle(this.checked);
$('#' + divIdAttendee).toggle(this.checked);
}
This function DOES get called as I tested it with a console.log.
the issue is that
var dataid = $(this).attr("data-id");
comes back as
undefined
Now my assumption right now is just that my new function to check for checked boxes and the other function that gets call are not working quite the same and my function doesn't know which check box was checked just that at least one was?
any help is really appreciated.
if ($("input[id*='checkbox_']").is(':checked')) {
... will filter out the first checked input and operate on that. If you want to iterate on all checkboxes, use this construct:
$("input[id*='checkbox_']").each(function() {
if ($(this).is(':checked')) {
// do something
}
});
I am new in select2 js so please help me for selecting value according to given order. Means when i have to store value according to user decided order.
data = [{id:1, name:xyz},{id:2, name:abc},{id:3, name:lmn}]
Suppose I want to show id [1,2] as selected but I am getting [2,1]
Add this code:
$('select').on('select2:select', function(e) {
var element = $(this).find('[value="' + e.params.data.id + '"]');
$(this).append(element);
$(this).trigger('change');
});
Or,
$("select").select2();
$("select").on("select2:select", function (evt) {
var element = evt.params.data.element;
var $element = $(element);
$element.detach();
$(this).append($element);
$(this).trigger("change");
});
I have taken the following snippet from a previously asked question on how to store the checked/unchecked status of all checkboxes on a page in localstorage:
$(function(){
var test = localStorage.input === 'true'? true: false;
$('[type="checkbox"]').prop('checked', test || false);
});
$('[type="checkbox"]').on('change', function() {
localStorage.input = $(this).is(':checked');
console.log($(this).is(':checked'));
});
When I select one of the checkboxes and then refresh the page, once it reloads every single checkbox is checked.
How would I make this store each individual checked state?
Note I may have between 0 - 50 check boxes available depending on how many outstanding records there are in my gridview so I don't have fixed input id's to use only a record id associated to each row.
If you want to rely on a localStorage solution, you may do something like this:
$(function(){
$('[type="checkbox"]').each(function () {
var $this = $(this),
name = $this.attr('name');
$this.prop('checked', localStorage[name] === 'true');
});
});
$('[type="checkbox"]').on('change', function() {
var $this = $(this),
name = $this.attr('name');
localStorage[name] = $this.is(':checked');
});
http://jsfiddle.net/mct7xgq2/
The first part is executed on page load and sets the checked state depending on the localStorage[name] value, where name is the input's name attribute.
The second part executes when any checkbox is being changed: it takes the input's name, as before, but instead of reading the value, it writes it.
IF the page would not load, it would be better to just store the values in JS object rather than using localStorage .
Just create a JS object and keep pushing values inside it and store
Client Side Solution if the page does not reload
$(function(){
var checkedItems ={};
$('[type="checkbox"]').on('change', function() {
//Store the ID value also in the localstorage
if($(this).is(':checked')){
var id = $(this).attr('id'); //Get the id if this is checked
checkedItems['id_'+id] = id;
}
});
});
If Page reloads, then your best bet is to use server side concepts like Session.
Send an AJAX request each time a particular checkbox is checked and store it in a session.
SERVER SIDE SOLUTION
$(function(){
$('[type="checkbox"]').on('change', function() {
//Store the ID value also in the localstorage
if($(this).is(':checked')){
var id = $(this).attr('id'); //Get the id if this is checked
$.ajax({
type: 'POST',
url: your server side url path, //store it in a session
data: {'id':id},
dataType: 'html',
success: function(result){
//so some functionality
}
});
}
});
});
Check out the FIDDLE LINK
This is a solution for d3.js with a ternary operator use. It compares the id of this checkbox with the values stored under key=id in localStorage.
If the value is "true" then 'this.checked' is set to 'true', else to 'null' ( null indicates: no 'checked' property)
var box = d3.selectAll(".box").each(function(){
var id = this.id;
var storageValue = localStorage.getItem(id);
this.checked = storageValue === "true" ? true : null;
});
Previously I have setItem in localStorage. The checkbox are created dynamically appended to rows in a table
rows.append('input')
.attr('type','checkbox')
which in turn is based on the data from a cvs. With the following ids for the checkboxes:
.attr("id", function(d,i) { return 'box'+' '+i; })
And the 'change' of the checkbox state:
d3.selectAll(".box").on("change", function() {
var id = this.id;
if ( this.checked ){
localStorage.setItem(id, this.checked);
}
else {
localStorage.removeItem(id);
}
});
I have thousands of rows, each with a checkbox. I did not see a major issue on the timeline inspection. So I guess that this is a good solution. I am not a d3.js expert.
the app receive a n html dive and create a page and append it to the app
I bind all link-buttons in set of pages to one function
which will do different tasks depends on the id of the page
now I have a problem when a page has more than one link-button
I need the ID of the clicked button
Html:
<a id="x">x </a>
<a id="y">y </a>
Js:
var btns = [];
$('#page-' + newpages[j].pageID + ' a').each(function () {
btns.push({
id: this.id,
value: this.value,
name: this.name
});
});
for (i in btns) {
$('#' + btns[i].id).bind('click', function () {
test(btns[i].id)
});
// bin all buttons in current page to test()
}
};
};
function test(x) {
var page = $('.ui-page-active').attr('id');
/////////
//here I'm trying to ge the ID of clicked button of that page (each ID means something)
var pos = '';
$('#' + page + ' a').click(function () {
//Get the id of this clicked item
var BID = $(this).attr("id");
alert(BID);
send(BID);
});
Why don't you just bind to the click event on each button independently? If you switch by ID anyway why go through a generic function, any shared functionality can be abstracted into a function and utilized by each click handler so you loose nothing.
I have information that comes out of a database and gets put into a list with a checkbox by each element. This is how it is currently done:
function subjects(){
$.ajax({
url: "lib/search/search.subject.php",
async: "false",
success: function(response){
alert(response);
var responseArray = response.split(',');
for(var x=0;x<responseArray.length;x++){
$("#subjects").append("<br />");
$("#subjects").append(responseArray[x]);
$("#subjects").append("<input type='checkbox' />");
}
}
});
}
it works fine, but I need a way to pick up on if a checkbox is clicked, and if it is clicked then display which one was clicked, or if multiple ones are clicked.
I can't seem to find a way to pick up on the checkboxs at all.
the response variable is "math,science,technology,engineering"
Because you are populating the Checkboxes Dynamically you need to Delegate the event
$("#subjects").on("click", "input[type='checkbox']", function() {
if( $(this).is(":checked") ) {
alert('Checkbox checked')
}
});
To better capture the data it is better if you encase the corresponding data into a span , so that it can be easier to search..
$("#subjects").append('<span>'+responseArray[x] + '</span>');
$("#subjects").on("click", "input[type='checkbox']", function() {
var $this = $(this);
if( $this.is(":checked") ) {
var data = $this.prev('span').html();
alert('Current checkbox is : '+ data )
}
});
It would be best to give your dynamically injected checkboxes a class to target them better, but based on your code try:
$("#subjects").on("click", "input", function() {
if( $(this).is(":checked") ) {
// do something
}
});
Since your input elements are added dynamically, you need to use jQuery's .on() function to bind the click event to them. In your case you need to use .on() to bind to an element that exist in the DOM when the script is loaded. In your case, the element with the ID #subjects.
This note from the docs is mainly for machineghost who downvoted my answer for no apparent reason:
Event handlers are bound only to the currently selected elements; they
must exist on the page at the time your code makes the call to .on().
To ensure the elements are present and can be selected, perform event
binding inside a document ready handler for elements that are in the
HTML markup on the page. If new HTML is being injected into the page,
select the elements and attach event handlers after the new HTML is
placed into the page.
$('#subjects input[type=checkbox]').on('click',function(){
alert($(this).prop('checked'));
});
or the change event: in case someone uses a keyboard
$('#subjects input[type=checkbox]').on('change',function(){
alert($(this).prop('checked'));
});
simple fiddle example:http://jsfiddle.net/Dr8k8/
to get the array example use the index of the inputs
alert($(this).prop('checked') +'is'+ $(this).parent().find('input[type=checkbox]').index(this)+ responseArray[$(this).parent().find('input[type=checkbox]').index(this) ]);
simplified example: http://jsfiddle.net/Dr8k8/1/
EDIT: Just for an example, you could put the results in an array of all checked boxes and do somthing with that:
$('#subjects>input[type=checkbox]').on('change', function() {
var checklist = [];
$(this).parent().find('input[type=checkbox]').each(function() {
$(this).css('background-color', "lime");
var myindex = $(this).parent().find('input[type=checkbox]').index(this);
if ($(this).prop('checked') == true) {
checklist[myindex] = responseArray[myindex];
}
});
$('#currentlyChecked').text(checklist);
});
EDIT2:
I thought about this a bit and you can improve it by using .data() and query that or store it based on an event (my button called out by its id of "whatschecked")
var responseArray = ['math', 'science', 'technology', 'engineering'];// just for an example
var myList = '#subjects>input[type=checkbox]';//to reuse
for (var x = 0; x < responseArray.length; x++) {
// here we insert it all so we do not hit the DOM so many times
var iam = "<br />" + responseArray[x] + "<input type='checkbox' />";
$("#subjects").append(iam);
$(myList).last().data('subject', responseArray[x]);// add the data
}
var checklist = [];// holds most recent list set by change event
$(myList).on('change', function() {
checklist = [];
$(myList).each(function() {
var myindex = $(this).parent().find('input[type=checkbox]').index(this);
if ($(this).prop('checked') == true) {
checklist.push($(this).data('subject'));
alert('This one is checked:' + $(this).data('subject'));
}
});
});
// query the list we stored, but could query the checked list data() as well, see the .each() in the event handler for that example
$("#whatschecked").click(function() {
var numberChecked = checklist.length;
var x = 0;
for (x = 0; x < numberChecked; x++) {
alert("Number " + x + " is " + checklist[x] + " of " + numberChecked);
}
});
live example of last one: http://jsfiddle.net/Dr8k8/5/
The general pattern to do something when a checkbox input is clicked is:
$('input[type=checkbox]').click(function() {
// Do something
})
The general pattern to check whether a checkbox input is checked or not is:
var isItChecked = $('input[type=checkbox]').is(':checked');
In your particular case you'd probably want to do something like:
$('#subjects input[type=checkbox]').click(function() {
to limit the checkboxes involved to the ones inside your #subjects element.