jQuery: Trigger even when checkbox gets checked - javascript

I am making a web app. In one part, I have a checklist dynamically generated with javascript.
I want to have a jQuery function executed when the checklist is checked.
Here is the code that dynamically generated the checklist:
var checkbox = document.createElement("input");
checkbox.setAttribute("type","checkbox");
checkbox.setAttribute("class", "tickbox");
document.getElementById("sortable").appendChild(checkbox);
Here is the output HTML file on execution, that shows that the checkbox was actually created:
<input type="checkbox" class="tickbox">
I want to have a function executed when the box is checked. I have tried:
1.
$('.tickbox').change(function () {
alert("Here");
if ($(this).attr("checked")) {
alert("Yeah");
}
2.
if($(.tickbox).is(':checked')){
alert("Yeah!!!");
3.
$('.tickbox').each(function(){
if($(this).is(':checked')){
alert("Yeah!!!");
}
})
But nothing worked. What's wrong? What should I do?
Note: A lot of other javaScript and jQuery, including many other function calls are working completely fine.

You said you have dynamically added checkbox so in order to add event handler to that DOM you has to use .on().
Example.
$(document).on('change','.tickbox',function(){
if($(this).is(':checked')){
alert("Yeah!!!");
}
})

Try this....
var checkbox = document.createElement("input");
checkbox.setAttribute("type","checkbox");
checkbox.setAttribute("class", "tickbox");
document.getElementById("sortable").appendChild(checkbox);
$(".tickbox").click(function(){
if ($(this).is(':checked')) {
alert("checked");
}
});
Example: http://jsfiddle.net/7xY8Y/

for dynamically generated element you need to use on():
$(document).on("change",'.tickbox',function () {
if ($(this).attr("checked")) {
alert("Yeah");
}
});
because your tickbox created dynamically then you need to bind event on document for class name tickbox for change event.

Related

Checkbox and click event handling

I'm trying to set a textbox to 'readonly', add a class, and put a text into the textbox at that moment when I check the checkbox. Moreover, I'm also trying to remove 'readonly' attribute from the textbox, add a class, and delete text in the textbox.
I have
$('#CheckBoxSectionCode').click(function () {
if ($(this).is(':checked')) {
$('#TextBoxSectionCode').attr('readonly', 'readonly');
$('#TextBoxSectionCode').addClass('disabled');
$('#TextBoxSectionCode').text(document.getElementById('TextBoxSectionName').val);
}
else {
$('#TextBoxSectionCode').attr('readonly', false);
$('#TextBoxSectionCode').addClass('abled');
$('#TextBoxSectionCode').text('');
}
});
This code doesn't work for me.
Thanks,
Phillip
Thanks everyone for answers.
According to your comments and answers, I've changed my code but it's still not working.
$('#CheckBoxSectionCode').click(function () {
if ($(this).is(':checked')) {
$('#TextBoxSectionCode').prop('readonly', true);
$('#TextBoxSectionCode').addClass('disabled');
$('#TextBoxSectionCode').text('disabled');
}
else {
$('#TextBoxSectionCode').prop('readonly', false);
$('#TextBoxSectionCode').removeClass('disabled').addClass('enabled');
$('#TextBoxSectionCode').text('');
}
});
I'm using chrome browser to run this code, and using developer tools in chrome and put a break point at the code above to see what's happening in the jquery. However, when I click the check box to check/uncheck, nothing happens there.
document.getElementById('TextBoxSectionName').val this is wrong. You really should cache your jQuery object so it's not navigating the DOM over and over. Then you mix in native JS and .val is not a DOM property or method, nor is it a jQuery property, it should be .value for a DOM object or .val() for a jQuery object.
Obligatory explanation by #Archy Wilhes:
"Just to clarify; when #SterlingArcher says caching the jQuery object,
she/he means doing something like var obj = $('#TextBoxSectionCode')
then calling the functions using the variable like this:
obj.attr(...); obj.addClass(...). Every time you do a $(something) you
are calling a function in jQuery that looks for the DOM."
since everytime you are adding the class the element is going to end up having both the two classes. Consider removing the other class before adding one. For example,
$(selector).removeClass('disabled').addClass('enabled')
Try with change event instead of click:
$('#CheckBoxSectionCode').change(function () {
if ($(this).is(':checked')) {
$('#TextBoxSectionCode').attr('readonly', 'readonly');
$('#TextBoxSectionCode').addClass('disabled');
$('#TextBoxSectionCode').text(document.getElementById('TextBoxSectionName').val);
}
else {
$('#TextBoxSectionCode').attr('readonly', false);
$('#TextBoxSectionCode').addClass('abled');
$('#TextBoxSectionCode').text('');
}
});
You could do the following way.
//Cache reference to DOM as DOM scan is expensive!
var textBox = $('#TextBoxSectionCode');
$('#CheckBoxSectionCode').click(function () {
//Use prop as opposed to attr
textBox.prop("readOnly", false).removeClass('disabled').addClass('abled').text("");
if ($(this).is(':checked')) {
textBox.prop("readOnly", true).removeClass('abled').addClass('disabled').text($("#TextBoxSectionName").val());
}
});

Click on dynamically generated radio button

i am trying to alert some text when a dynamically generated radio button is checked .. here is the link from fiddle ..
http://jsfiddle.net/z7cu3q0y/
function createRadioButtons(n)
{
$("#radioContainer").empty();
for(var i=0;i<n;i++)
{
radioButtons = "<p><input type='radio' class='"+n+"' name='"+n+"'>"+(i+1)+"</p>";
$("#radioContainer").append(radioButtons);
}
}
$("#dropDown").on("change",function()
{
createRadioButtons(parseInt($(this).val()));
});
$("#radioContainer input").on("change",function()
{
alert("checked");
});
when i click on radio button i am not getting alert .. can any one of you please help me in taking a look ?
Thanks in advance,
Ashwin
Your code $("#radioContainer input").on("change",function(){})
will directly attach the event handler to the matching elements that are currently present in DOM.
To work with dynamically generated elements added in the future, You need to delegate your event handler to a common parent element:
$("#radioContainer").on("change","input",function(){
alert("checked");
});
The above will attach the handler to #radioContainer, Whenever the corresponding event (change in this case)is triggered (Usually propagated from the children), it checks whether the event target matches the specified selector (input in this case) and invokes the handler accordingly.
Updated Fiddle
You need to use .on() for dynamically generated elements like below. Here .on() will bind change event to all radio buttons which are inside radioContainer
$("#radioContainer").on("change","input[type=radio]",function()
{
alert("checked");
});
Demo
Try using the below code
$(document).on("change","#radioContainer input",function(){
alert("checked");
});
Updated fiddle
You need to put the input defined as click area and radiocontainer as working area.
DEMO: http://jsfiddle.net/don/z7cu3q0y/3/
Just remove input before .on and put inside of the function.
jQuery:
function createRadioButtons(n)
{
$("#radioContainer").empty();
for(var i=0;i<n;i++)
{
radioButtons = "<p><input type='radio' class='"+n+"' name='"+n+"'>"+(i+1)+"</p>";
$("#radioContainer").append(radioButtons);
}
}
$("#dropDown").on("change",function()
{
createRadioButtons(parseInt($(this).val()));
});
$("#radioContainer").on("change", 'input', function()
{
alert("checked");
});

jquery/ajax - .load keeping the same JQuery

Basically,
What I'm trying to do is have a button which when you click, loads up another .html form
which has a button to the next .html page and so on and so on..
The first part works, and, for the form to be loaded, however, when the next form is loaded the jquery does not work for the button.. For example:
index1.html:
<button id="LoadForm" value="form1.html">Load the form</button>
$(document).ready(function() {
function foo(x) {
$('.content').load(x);
}
$('#LoadForm').click(function() {
var ele = $(this).attr("value");
$(this).hide();
form(ele);
});
});
In form1.html:
<button id="LoadForm" value="index.html">Go to form2..</button>
Where am I going wrong here?
1) You can't have duplicate ids on the same page, so .content must contain the original #LoadForm button (I assume it does) and
2) you need to use a delegated event handler for dynamically added elements:
$(document).ready(function() {
function foo(x) {
$('.content').load(x);
}
$(document).on('click', '#LoadForm', function() {
var ele = $(this).attr("value");
$(this).hide();
form(ele); // This should be foo in your example :)
});
});
This works by listening for click events bubbling up to a non-changing ancestor (document is the best default of there is nothing closer. Never use 'body' as it has problems related to styling). It then applies the jQuery filter. It then applies the supplied function for any selected elements that generated the event.
and 3) you have foo and form in your example. Please correct the code :)

Checkbox Styling with SelectAll Function

Was styling the checkboxes of my webpage with jquery using the tutorial here
But i realized that I could not do SelectAll checkbox that will select all the checkboxes in my list. It works in the backend (the checkboxes are selected) but it does not show in my page.
Added a demo to show my problem. May need to port to your system to test it out
Demo
what can I add to the jQuery Custom Radio-buttons and Checkbox javascript file in the to achieve the select all checkbox function
Thank you!
You can try this FIDDLE:
$(function () {
var $chbxs = $('.checkbox');
$('#sel_all_lbl').toggle(
function() {
$chbxs.css('background-position', '50% -50px');
$('#checkboxall .truefalse').prop('checked', true);
},
function() {
$chbxs.css('background-position', '50% 0px');
$('#checkboxall .truefalse').prop('checked', false);
}
);
});
What I've done? First, in your fiddle you need to correct some syntax errors, then add a plugin code to the DOM, and you scripts to the script panel, so they will fire when DOM is ready. (This is all about jsFiddle, so you to understand how it works)
About actually your code, you attached click-handlers (.toggle()) to the checkbox element. But click event does not fire on it. Script simply changed the property of the checkbox, but there is no click. So you need to attach these handler to the element wish user actually clicks, that is square icon. (I added an id="sel_all_lbl" to it)
Try to use event handling on the select all checkbox and manually check all the checkboxes from javascript.

checkbox jquery or javascript oncheck?

I do not know the correct terminology for this, but I want the same effect as onclick but for a check box with jquery or javascript.
onclick version:
Link
I want the same effect as above but for a checkbox. The end result will be that the page should reload with an updated php query, but that part I can do. I just don't know what the onclick is for checkboxes.
checkbox:
<input type="checkbox" name="change" value="one" />changes php query
You should listen to the change event, as the checkbox can be selected or deselect with the keyboard too:
$('input[type="checkbox"][name="change"]').change(function() {
if(this.checked) {
// do something when checked
}
});
Similarly with plain JavaScript:
// checkbox is a reference to the element
checkbox.onchange = function() {
if(this.checked) {
// do something when checked
}
};
And last, although you really should not use inline event handlers, but if you have to:
<input ... onchange="handler.call(this)" />
where handler is like the handlers shown above.
Further reading:
jQuery documentation
MDN JavaScript Guide
quriksmode.org Introduction to Events
$('#input_id').click(function() {
// do what you want here...
});
$('input:checked').click(function() {
//do something
});
See http://api.jquery.com/checked-selector/ and http://api.jquery.com/checkbox-selector/

Categories