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
}
});
Related
I am creating a dynamic dropdown list out of checkboxes. What I want is when the dropdown changes (on select) I want it to check the checkboxes with the same values or perhaps with the same name? I also want it to do vice versa, if you check a checkbox the select dropdown should change as well.
Here is my codepen - http://codepen.io/BryanBarrera/pen/QEXVxY
I am having issues writing this. Here is what I have. What is the best approach for this? How do I match up elements to change or check the checkboxes?
Any idea or suggestions would be much apprecated
"use strict";
var checkBoxes = $('.form-item'),
checkBox = $('input[type="checkbox"]'),
$select = $('<select></select>').appendTo('body').wrap('<div class="select-dropdown"></div>');
checkBoxes.each(function (n) {
var dataText = $(this).find('label').text();
var dataValue = $(this).find('input').val();
$select.append('<option value="' + dataValue + '">' + dataText + '</option>');
});
$select.on('change', function(){
var checkboxvalue = $(this).val();
var a = $(this).filter(function(){return this.value=='checkboxvalue'});
console.log(a);
console.log(checkboxvalue);
if (checkboxvalue == $(this).val() ) {
// alert('yup');
}
});
This will do the trick:
$select.on('change', function(){
var checkboxvalue = $(this).val();
$('input[value='+checkboxvalue+']').prop('checked', true);
});
checkBox.on('change', function(){
var selectValue = $(this).val();
$select.val(selectValue)
});
You probably want some other function to handle multiple selection, because you dropdown obviosly don't support multiple selection like checkboxes.
Example
You're setting the value of the checkbox element, but not actually checking the box. You also need to do this:
$('#checkbox-selector').prop('checked', true);
This question already has an answer here:
checked checkbox will remain through pagination
(1 answer)
Closed 8 years ago.
I have a problem here using .load() ajax/jquery when I use it in pagination. the status of my checkbox will not remain when I go to another page. For example I checked 2 items in page 1 then when I go to page 2 to select another item then when I go back to page 1 to test if my checked item remain checked. unfortunately it became unchecked maybe because of the .load(). Please help me if there is alternative to use aside .load() to remain my checkbox checked.
here is my code for .load() ajax:
<script type="text/javascript">
$(document).ready(function() {
$("#results").load("fetch_pages.php", {'page':0}, function() {$("#1-page").addClass('active');});
$(".paginate_click").click(function (e) {
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]);
$('.paginate_click').removeClass('active');
$("#results").load("fetch_pages.php", {'page':(page_num-1)}, function(){
});
$(this).addClass('active');
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#results").load("fetch_pages.php", {'page':0}, function() {$("#1-page").addClass('active');}); //initial page number to load
$('body').on('click', '.paginate_click', function(e){
// Get all the checked boxes and store their ID in an array
var ticked = [];
$('.tick:checked').each(function(){
ticked.push($(this).attr("id"));
});
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]);
$('.paginate_click').removeClass('active');
$("#results").load("fetch_pages.php", {'page':(page_num-1)}, function(){
// Content has loaded but is still raw
// We loop through IDs and check'em
ticked.forEach(function(val, i){
$(val).prop('checked', true);
});
});
$(this).addClass('active');
return false;
});
});
</script>
hi #charleshaa it doesnt work this is what i did to my script
and here is my checkbox code
echo "<div id='a'><input type='checkbox' class='tick' name='items[$i]' id='$i' value='". $item['ItemID'] ."' >".$item['ItemName']."</div>";
What's wrong?? Im badly need help
You need to keep you checked boxes in a variable so you can recheck them after the load.
First add a class to your checkboxes class="tick".
Then you would :
$(".paginate_click").click(function (e) {
// Get all the checked boxes and store their ID in an array
var ticked = [];
$('.tick:checked').each(function(){
ticked.push($(this).attr("id"));
});
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]);
$('.paginate_click').removeClass('active');
$("#results").load("fetch_pages.php", {'page':(page_num-1)}, function(){
// Content has loaded but is still raw
// We loop through IDs and check'em
ticked.forEach(function(val, i){
$(val).prop('checked', true);
});
});
$(this).addClass('active');
return false;
});
EDIT:
Also, it is preferable not to use the .click() notation, instead, you should always use .on()
In this example, you would write it like this :
$('body').on('click', '.paginate_click', function(e){
//code
});
It is much better for performance as it only attaches one event listener to body, instead of attaching one to every .paginate_click.
Check my comment about the unique IDs and you should be good to go.
I am using Bootstrap's accordion widget to contain several forms i.e. each panel contains one form. When the last panel is selected, the data from the other panels is meant to be posted which will be used to graph the data. However, I am unable to get to the posting part as I cannot figure out which panel is currently selected. I know that this has to do with a class of active or inactive, but I don't think bootstrap's accordion supports that functionality unlike jquery accordion.
I am trying to figure out the first part i.e. check if the user has clicked on the last panel. In my HTML code it has an id of #results. Here's a jsfiddle that demonstrates the issue I am facing. It does not seem to trigger the second alert function when the user clicks on the #results tag, not sure why.
Sample javascript code:
$('#accordion').on('show.bs.collapse', function () {
$('#results').click(function () {
alert("works"); //testing purposes
});
});
Why don't you do?
$('#results').click(function (){
alert("clicked");
});
Just remove the accordion function and you'll get the on click event directly
Is this what you want?
Fiddle: Demo
take this outside the on function
$('#results').click(function (){
alert("clicked");
});
This is an old thread but I wanted to post an answer as the expected result is not suggested.
What you need to do here is to handle the currently selected collapse items with the event handler. If you use the this keyword for this, you can access the values of the selected object (For example only one item in the form).
Here you can get the $(".collapse") element.
You can get the index number of the active item with $(this).parent().index().
Likewise, you can get the id of the active item with $(this).attr('id').
Your jQuery structure would be:
$(".collapse").on('show.bs.collapse', function(){
//0,1,2,etc..
var index = $(this).parent().index();
//collapseOne, collapseTwo, etc..
var id = $(this).attr('id')
//alert('Index: ' + index + '\nItem Id: ' + id );
console.log('Index: ' + index)
console.log('Item Id: ' + id)
if(id === 'collapseFour')
{
var username = $('#username').val();
var email = $('#email').val();
var age = $('#age').val();
//here you can check the data from the form
$("#result").html("<p> UserName: " + username + "</p> <p> EMail: " + email + "</p> <p> Age: " + age + "</p>");
}
});
I've included a working example here for you (jsfiddle).
$('#accordion').on('show.bs.collapse', function (accordion) {
var $activeCard = $(accordion.delegateTarget.children);
});
or
$('#accordion').on('show.bs.collapse', function () {
var $activeCard = $(this.children);
});
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.
I have two checkboxes:
<input id="outside" type="checkbox" value="1" data-gid="41820122" />
<input id="inside" type="checkbox" value="1" data-gid="41820122" />
I've made them mutually exclusive with:
$(function(){
//mutually exclusive checkboxes
$("input[data-gid]").click(function(){
var gid = $(this).attr('data-gid');
var fid = $(this).attr('id');
var checkboxes = $("input[data-gid=" + gid + "][id!=" + fid + "]");
checkboxes.attr("checked", false);
});
});
This works fine. But I also want to add additional click functionality to the 'inside' checkbox. I want it to enable/disable a textarea on the same form, so I've done this:
$('#application_inside').click(function() {
if ($(this).is(':checked')) {
return $('textarea').removeAttr('disabled');
} else {
return $('textarea').attr('disabled', 'disabled');
}
});
So, if the 'inside' checkbox is checked, the textarea will be enabled, if it's not checked, the textarea should be disabled.
The problem is that if the 'inside' checkbox is checked, and the user then checks the 'outside' checkbox, the 'inside' becomes unchecked (as it should be), but the textarea remains enabled. This appears to be because the 'inside' checkbox was never actually clicked by the user.
I've tried working around this with the following:
$(function(){
//mutually exclusive checkboxes
$("input[data-gid]").click(function(){
var gid = $(this).attr('data-gid');
var fid = $(this).attr('id');
var checkboxes = $("input[data-gid=" + gid + "][id!=" + fid + "]");
checkboxes.attr("checked", false);
checkboxes.triggerHandler("click"); //new code to fire any click code associated with unchecked boxes
});
});
But this just throws the browser in a loop, since the two different click events end up calling each other.
How can I keep my mutually exclusive code while still allowing the enable/disable code for the 'inside' checkbox to work?
You can create a custom event that you trigger when you click on #application_inside. Also you will fire this custom event when you uncheck other boxes because of the exclusiveness.
Here is an example: http://jsfiddle.net/gs78t/2/
you may try something like this
var insideChanged = function() {
if ($('#inside').is(':checked')) {
return $('textarea').removeAttr('disabled');
} else {
return $('textarea').attr('disabled', 'disabled');
}
};
$('#application_inside').click(insideChanged);
$(function(){
//mutually exclusive checkboxes
$("input[data-gid]").click(function(){
var gid = $(this).attr('data-gid');
var fid = $(this).attr('id');
var checkboxes = $("input[data-gid=" + gid + "][id!=" + fid + "]");
checkboxes.attr("checked", false);
insideChanged(); //new code to fire any click code associated with unchecked boxes
});
});