I'm using Eric Hynds jQuery MultiSelect Widget that is being populated from a javascript file. A checkbox is created with label attached under a 'Main' checkbox if a Main is checked. How can I set it up to where the dynamically created checkbox removes if that corresponding Main is unchecked? Please see my fiddle to illustrate my problem http://jsfiddle.net/3u7Xj/76/
$(document).ready(function() {
$(".multiselect").multiselect({
header: "Choose up to 5 areas total",
click: function (event, ui) {
var number1=$("#dropdown1").children(":checked").length,
number2=$("#dropdown2").children(":checked").length;
if (ui.checked && ((number1 + number2 >=2) || $(this).children(":checked").length >= 2)) {
return false;
}
var lbl = ui.value;
if(ui.checked){
var ctrl = '<input type="checkbox" name="chk" checked="checked" class="chk" id="'+lbl+'">';
$("[id^=Main]:checked").each(function(){
$(this).nextAll('.holder:first').append('<div>'+ctrl+lbl+'</div>');
});
}
else {
$("[id^=Main]:checked").each(function(){
$(this).nextAll('.holder:first').find('div input[id="'+lbl+'"]').parent().remove();
});
}
},
selectedList:5
});
});
Something like this?
$("[id^=id]:checked",false).each(function(){
$(this).nextAll('.holder:first').find('div input[id="'+lbl+'"]').parent().remove();
});
Or
if(ui.checked = false){
$(this).nextAll('.holder:first').find('div input[id="'+lbl+'"]').parent().remove();
}
else{};
how about adding this?
$("input[name^=chkMain]").change(function(){
if($(this).not(':checked')){
$(this).next('label').next('.holder').html('');
}
});
http://jsfiddle.net/3u7Xj/77/
is that what you meant?
Try this
else {
$("[id^=Main]:checked").each(function(){
$(this).nextAll('.holder:first').find('#' + lbl).parent().remove();
})
}
Demo
I also added a functionality that unchecks the children of a main if it is unchecked. Remove the code
$(".checkers").click(function() {
if(!$(this).is(':checked')) {
$(this).nextAll('.holder:eq(0)').find('div input').attr("checked", this.checked);
}
});
if you don't want that functionality. You could also change .attr("checked", this.checked) to .parent().remove() if you wanted to remove the check boxes instead
If you wanted to do the opposite, meaning check the boxes then the Main, you could use the following
var checkedOnes = $('#dropdown1').nextAll('.ui-multiselect-menu').find('ul li input:checked');
for(var i = 0; i < checkedOnes.length; i++) {
var lbl = checkedOnes.eq(i).attr('value');
var ctrl = '<input type="checkbox" name="chk" checked="checked" class="chk" id="'+lbl+'">';
$("[id^=Main]:checked").each(function(){
$(this).nextAll('.holder:first').append('<div>'+ctrl+lbl+'</div>');
});
}
Updated Demo
Related
I have about ten check boxes that each implement different functions. I am trying to make one master checkbox that will
a) check all 10 checkboxes;
b) implement the functions in each
I have gotten one to work but for some reason, when I check it, the others aren't checked until I move my mouse off of the master checkbox (after checking it). Bizarre, right? Here is the code for the master checkbox and the sub-checkboxes. (I have to warn you that I am a little new to javascript and it's possible that this is terribly written. Advice in that direction also welcome.)
/*change all buttons of a single genre*/
$("a[id^="+genre+"_]").attr("class", modereplacement+"Button" + " showButton");
$("a[id^="+genre+"_]").attr("onClick", function(index, currentValue){ return currentValue.replace(mode, modereplacement) ; });
$("#"+"all_"+genre+'_cur').attr("onClick",function(index, currentValue){ return currentValue.replace(mode, modereplacement) ; });
/*check all checkboxes*/
if (category =='All')
{
$("#"+"alls_cur").attr("onClick",function(index, currentValue){ return currentValue.replace(mode, modereplacement) ; });
for (var i = 0 ; i < 13 ; i++)
{
/*change individual buttons*/
var currentgenre = allgenre[i];
$("a[id^="+currentgenre+"_]").attr("class", modereplacement+"Button" + " showButton");
$("a[id^="+currentgenre+"_]").attr("onClick", function(index, currentValue){ return currentValue.replace(mode, modereplacement) ; });
/*change Quick button*/
$("#"+"all_"+currentgenre+'_cur').attr("onClick",function(index, currentValue){ return currentValue.replace(mode, modereplacement) ; });
$("#"+"all_"+currentgenre+'_cur').prop("checked", (mode == "offx"));
}
}
And here is the HTML that implements the 'Check All' aka 'Watch All' buttons:
<td><a class='quickButton'>Watch All</a></td>
<td><input type='checkbox' id='alls_cur' onclick=\"watchgenre( $user_id,'All','alls', 'offx', 1);\" ></input></td>
<td><input type='checkbox' $checkname id='alls_fut' onclick=\"watchgenre( $user_id,'All','alls', 'offx', 2);\" ></input></td>
Thanks for any advice you are able to give
try to use events (like onclick ) in jQuery like this_
$("selector").on("click", callbackOrFunction)
something like this? http://jsfiddle.net/swm53ran/118/
the below shows a snippet of the code in teh demo. the demo is showing that there are 5 check boxes and 1 check all checkbox. each box, when checked, triggers its div to have a colored background. when unchecked, it's background changes to white. the check all checkbox checks all the other check boxes and triggers their actions with the line: $(this).trigger('change');. This line of code simulates a .change() event for each of the checkboxes
<div>
<input type="checkbox" class="chkbox check1"/> Background gray <br/>
</div>
<div>
<input type="checkbox" class="chkbox check2"/> Background lightgray <br/>
</div>
<input type="checkbox" class="checkAll"/> Check All
$(document).ready(function() {
$('.checkAll').on('change', function() {
if($(this).is(':checked')) {
$('.chkbox').each(function() {
$(this).prop('checked', true);
$(this).trigger('change');
});
}
});
$('.check1').on('change', function() {
if($(this).is(':checked')) {
$(this).closest('div').css('background-color', 'gray');
}
else {
$(this).closest('div').css('background-color', 'white');
}
});
$('.check2').on('change', function() {
if($(this).is(':checked')) {
$(this).closest('div').css('background-color', 'lightgray');
}
else {
$(this).closest('div').css('background-color', 'white');
}
});
});
hope this helps!
btw, just in case you didnt know .change() or .on('change') is an event triggered when the state of the checkbox changes (from checked to unchecked and vice versa)
I have dynamically created a list of checkboxes inside a table:
$("#employeeRegister").append('<tr><td><input type="checkbox" class = "check" name ="chk'+i+'" value="'+this.employeeMobileNo+'$'+this.employeeEmailId+'" </td></tr>');
The above code runs 10 times inside a loop to generate 10 checkboxes dynamically.
I tried using this below code to see if a checkbox is checked.
$(document).ready(function () {
$(document).on("click", "#smsbutton", function () {
console.log('alert');
$("input:checkbox[name=type]:checked").each(function () {
alert(checked);
});
});
});
smsbutton is a button on whose click event I want to get checkboxes that are checked. But it does not work. What do I do to get all checked checkboxes?
Try this:
$("input.check:checked").each(function() {
alert(this.name + " is checked");
});
just use an attribute selector like
$(document).on("click","#smsbutton", function(){
$('input[type="checkbox"]:checked');
console.log($('input[type="checkbox"]:checked').serialize());
});
OR
$(document).on("click","#smsbutton", function(e){
if (e.handled !== true) {
e.handled = true;
e.preventDefault();
$('input[type="checkbox"]:checked').each(function() {
console.log(this.value);
});
}
});
I have a HTML form with checkboxes as below,
when I select ALL, other check boxes {HR, FINANCE, IT, SALES} should get checked
When I un select ALL, other checkboxes {HR, FINANCE, IT, SALES} should get unchecked
When everything is checked and of one the checkboxes {HR, FINANCE, IT, SALES} is unchecked, ALL should be unchecked
Below is the markup of my HTML.... how can I so it using jQuery/javascript ????
<input type="checkbox" name="Dept" value="ALL"/>
<input type="checkbox" name="Dept" value="HR"/>
<input type="checkbox" name="Dept" value="FINANCE"/>
<input type="checkbox" name="Dept" value="IT"/>
<input type="checkbox" name="Dept" value="SALES"/>
Try this
jQuery > 1.6
// Cache the selectors as they are being multiple times
var $all = $('input[value=ALL]'),
$inputs = $('input');
$all.change(function () {
// Set the other inputs property to the all checkbox
$inputs.not(this).prop('checked', this.checked);
});
// Change event for all other inputs
$inputs.not($all).change(function () {
var $others = $inputs.not($('input[value=ALL]'));
// Get the checked checkboxes
var $checked = $others.filter(function () {
return this.checked;
});
// If length is not equal then uncheck the All checkbox
if ($others.length !== $checked.length) {
$all.prop('checked', false);
}
});
jQuery 1.4.4
var $all = $('input[value=ALL]'),
$inputs = $('input');
$all.change(function () {
var allChk = this;
$inputs.each(function() {
this.checked = allChk.checked;
});
});
$inputs.not($('input[value=ALL]')).change(function () {
var $others = $inputs.not($('input[value=ALL]'));
var $checked = $others.filter(function () {
return this.checked;
});
if ($others.length !== $checked.length) {
$all[0].checked = false;
}
});
jQuery > 1.6 Fiddle
jQuery 1.4.4 Fiddle
Try this,
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});
where case is the class added to othe check boxes
For online demo visit,
http://viralpatel.net/blogs/multiple-checkbox-select-deselect-jquery-tutorial-example/
DEMO
$('input[type="checkbox"][name="Dept"]').change(function () {
if (this.value == 'ALL') {
$('input[name="Dept"]').prop('checked', this.checked);
}
});
Updated Demo with jQuery 1.5.2
$('input[type="checkbox"][name="Dept"][value="ALL"]').change(function () {
$('input[name="Dept"]').attr('checked', this.checked);
});
$('input[type="checkbox"][name="Dept"]:gt(0)').change(function () {
if (!this.checked) {
$('input[name="Dept"][value="ALL"]').removeAttr('checked');
}
if ($('input[type="checkbox"][name="Dept"]:gt(0)').length == $('input[type="checkbox"][name="Dept"]:gt(0):checked').length) {
$('input[type="checkbox"][name="Dept"][value="ALL"]').attr('checked',true);
}
});
Here's one way to do it:
$(document).ready(function() {
var $cbs = $('input[name="Dept"]').click(function() {
if (this.value==="ALL")
$cbs.prop("checked", this.checked);
else if (!this.checked)
$cbs[0].checked = false;
});
});
Jawdroppingly good demo: http://jsfiddle.net/MNbDw/2/
Note that obviously my code above has a hardcoded assumption that the "ALL" checkbox will be the first one (at the point where I unchecked it using $cbs[0]). You could change the else if case to do this instead:
$cbs.filter('[value="ALL"]').prop("checked",false);
Demo: http://jsfiddle.net/MNbDw/3/
Or change your html to give that particular checkbox an id or whatever.
UPDATE: The .prop() method was introduced in jQuery 1.6. For version 1.5.2 (as mentioned in a comment) use .attr() instead as shown here (though 1.5.2 is so old that jsfiddle doesn't actually offer it as an option so I had to add it under "External Resources"): http://jsfiddle.net/MNbDw/9/
I have a small requirement,
We have restore the textbox data that was cleared previously.
Below is my HTMl code
<table>
<tr><td><input type="textbox"></td></tr>
<tr><td><input type="checkbox"></td></tr>
</table>
Here is my JQuery Code
$('TABLE TR TD').find(':checkbox').change(function()
{
if($(this).prop('checked'))
{
$(this).parents('TR').siblings('TR').find('input').val("")
}
if(!$(this).prop('checked'))
{
$(this).parents('TR').siblings('TR').find('input').val(?)
}
});
My Requirement is to clear the textbox content if checkbox is checked. And if i deselect it the textbox should be restored with previous data.
Please someone help me.
Use a global variable to store the previous data -
var prevData;
then modify your code this way -
$('TABLE TR TD').find(':checkbox').change(function()
{
if($(this).prop('checked'))
{
var $element = $(this).parents('TR').siblings('TR').find('input')
prevData = $element.val();
$element.val("");
}
else
{
$(this).parents('TR').siblings('TR').find('input').val(prevData);
}
});
When the checkbox is being checked, before clearing the value, store it using the jQuery .data() API.
<table>
<tr><td><input type="text"></td></tr>
<tr><td><input type="checkbox"></td></tr>
</table>
$('input:checkbox').change(function() {
var input = $(this).closest('table').find('input[type="text"]');
if ($(this).prop('checked')) {
input.data('text', input.val());
input.val('');
} else {
input.val(input.data('text'));
}
});
A demo which works if there were multiple pairs, so long as they exist in separate <table> parents. You could change the finder to get the previous sibling if that were not the case. This uses no global variables which are not really best practice - How to avoid global variables in JavaScript?.
Edit: Updated demo based on your other question Keydown event is not working properly but this will only for key events and not if someone pastes text into the <input>.
I'd suggest something a little less reliant on the mark-up remaining the same (though it does require that the checkbox follows the text input):
var prevData, textInputIndex;
$('input:checkbox').change(
function(){
thisIndex = ($(this).index('table input') - 1);
textInput = $('table input').eq(thisIndex);
if ($(this).is(':checked')) {
prevData = $(textInput).eq(thisIndex).val();
$(textInput).eq(thisIndex).val('');
}
else {
$(textInput).eq(thisIndex).val(prevData);
}
});
JS Fiddle demo.
Edited to remove the problem of having only one variable to store the text-input value:
var $textInputs = $('table input:text');
var prevData, textInputIndex, affectedTextInputIndex, textInputValues = [];
$('input:checkbox').change(
function(){
affectedTextInputIndex = $(this).index('table input') - 1;
textInputIndex = $('table input').eq(affectedTextInputIndex).index('table input:text');
if ($(this).is(':checked')) {
textInputValues[textInputIndex] = $textInputs.eq(textInputIndex).val();
$textInputs.eq(textInputIndex).val('');
}
else {
$textInputs.eq(textInputIndex).val(textInputValues[textInputIndex]);
}
});
JS Fiddle demo.
Edited to remove the explicit requirement that the input elements be contained in a table:
var $textInputs = $('input:text');
var prevData, textInputIndex, affectedTextInputIndex, textInputValues = [];
$('input:checkbox').change(
function(){
affectedTextInputIndex = $(this).index('input') - 1;
textInputIndex = $('ul input').eq(affectedTextInputIndex).index('input:text');
if ($(this).is(':checked')) {
textInputValues[textInputIndex] = $textInputs.eq(textInputIndex).val();
$textInputs.eq(textInputIndex).val('');
}
else {
$textInputs.eq(textInputIndex).val(textInputValues[textInputIndex]);
}
});
JS Fiddle demo.
References:
:checkbox selector.
change().
is().
:checked selector.
index().
val().
I am trying to disable a order button when the page loads and enable it when one checks the Terms and condition checkbox. I have it working where the order button is disabled when the page loads but on the click of checkbox the button doesnt get enabled. Here is my code. Can anyone help me identify the problem
<input type="checkbox" id="checkbox1" name="checkbox1" class="required" />Please read the Terms and Conditions
Jquery Code
var j$ = jQuery.noConflict();
j$(document).ready(function(){
alert("Hi");
if(j$('input[name="checkbox1"]').not(":checked"))
{
j$('input[name="Order"]').attr('disabled', 'disabled');
}
else
{
j$('input[name="Order"]').removeAttr('disabled');
}
j$('#checkbox1').change(function(){
if(j$('input[name="checkbox1"]').is(":checked")
{
j$('input[name="Order"]').attr('disabled', 'disabled');
}
else
{
j$('input[name="Order"]').removeAttr('disabled');
}
}
});
Thanks
Prady
The code you provided had some missing ( and {, here is an updated version with some changes to handle the checkbox state properly:
var j$ = jQuery.noConflict();
j$(document).ready(function() {
var checkbox1 = j$('#checkbox1');
var order = j$('input[name="Order"]');
var verifyChecked = function() {
if (checkbox1.is(":checked") === false) {
order.attr('disabled', 'disabled');
} else {
order.removeAttr('disabled');
}
};
verifyChecked();
checkbox1.change(verifyChecked);
});
Here is a jsfiddle with it working:
http://jsfiddle.net/7uRf6/4/
You have missed a closing parenthesis
if(j$('input[name="checkbox1"]').is(":checked")
should be
if(j$('input[name="checkbox1"]').is(":checked"))
Also you can use an id selector instead of this attribue selector.
And if you want to enable the button when the checkbox is checked you have to
if(!j$('input[name="checkbox1"]').is(":checked"))
in your change event,
if(j$('input[name="checkbox1"]').is(":checked")
it should be
if(j$('input[name="checkbox1"]').not(":checked")
I suggest you to create a function to check it.
var j$ = jQuery.noConflict();
j$(document).ready(function(){
ToggleButton();
j$('#checkbox1').change(ToggleButton);
});
function ToggleButton()
{
if(j$('input[name="checkbox1"]').not(":checked"))
{
j$('input[name="Order"]').attr('disabled', 'disabled');
}
else
{
j$('input[name="Order"]').removeAttr('disabled');
}
}
<script src="jquery.js"></script>
<script>
$(document).ready(function (){
$('#ch').click(
function (){
if($(this).is(':checked')){
$('#bt').attr('disabled','disabled');
}
else {
// remove
$('#bt').removeAttr('disabled');
}
}
)
})
</script>
<input type="button" value="button" id="bt"/>
<input type="checkbox" id="ch"/>