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");
});
Related
I have a checkbox and I marked it as checked, however it doesnt fire the on change function. The note doesn't appear.
My code:
$('#checkbox1').prop("checked", true);
$('#checkbox1').change(function(){
if ($(this).is(':checked'))
$('#s-note').show();
else
$('#s-note').hide();
});
Do you expect the onchange to fire without user interaction?
Your issue is you set the checked state before you set the handler so if this would have trigged change, you would have not caught it. Your real issue here is setting the property with JavaScript does not fire the change event. So you need to trigger the change event manually.
$('#checkbox1')
.prop("checked", true) // set it to checked
.on("change", function() { // bind change event
$('#s-note').toggle($(this).is(':checked')); // toggle visibility
}).trigger("change"); //trigger that you need the change to run
If you are setting the note to be hidden by default and doing it with an id based selector, like this:
#s-note { display:none; }
Then your code won't be able to show it because it also uses an id based selector and that won't be more specific than the selector already in effect.
Instead, you'll have to default the note to hidden using a selector that is less specific than the id selector you will use to show/hide it later. That would be a class.
Also, it's critical that you set up the event handler before you trigger the event, so that when the event happens, there is already an event handler registered.
Now, for your needs, you don't really need the change event, click will do just fine. And, lastly, to ensure that you properly trigger the event, use JQuery's .trigger() method to set things in motion.
// Make sure you set up the callback first
$('#checkbox1').on("click", function(){
if ($(this).is(":checked"))
$('#s-note').show();
else
$('#s-note').hide();
});
// Then just trigger the event
$('#checkbox1').trigger("click");
.hide { display:none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="checkbox1">Test
<div id="s-note" class="hide">Special</div>
I hope this code snippet will help you
Approach 1
$('#idcheckbox').on('change', function() {
if($(this).is(':checked')) {
alert('checked');
} else {
alert('default ');
}
});
Approach 2
$('input[type=checkbox]').on('change', function() {
if($(this).is(':checked')) {
alert('checked');
} else {
alert('default ');
}
});
I ran your code in .net mvc and it runs fine.
This is the checkbox same id it hide or shows div element.
<input type="checkbox" id="checkbox1" value=" " />
<div id="s-note" style="display: none">
<label>Showing</label>
</div>
What are you trying to display?
I followed this example to capture an onChange() jQuery event for a radio button group:
JQuery $(#radioButton).change(...) not firing during de-selection
But in my case, the solution given in that example is not working. I have the following generated from my JSP:
<input id="object.reportEntity.reportEntityIsPrime1" name="object.reportEntity.reportEntityIsPrime" type="radio" value="Y_YES" checked="checked"/>Prime
<input id="object.reportEntity.reportEntityIsPrime2" name="object.reportEntity.reportEntityIsPrime" type="radio" value="N_NO"/>Not Prime
JS:
$(document).ready(function() {
// Display Alert on Radio Change
$('input[name=object.reportEntity.reportEntityIsPrime]:radio').change(function () {
alert('Radio Button clicked');
});
}
The alert is not being diplayed. Also, there's this error:
Syntax error, unrecognized expression "input"
You should delegate the events.
Event delegation allows us to attach a single event listener, to a
parent element, that will fire for all descendants matching a
selector, whether those descendants exist now or are added in the
future.
Also, you need to add " in your selector e.g. [name=""] Observe the following...
$('body').on('change', 'input[name="object.reportEntity.reportEntityIsPrime"]:radio', function() {
alert('Radio Button clicked');
});
side note: you are missing ); on the end of your ready function
JSFiddle Link - working demo
Also, be sure to check out the jQuery Understanding Event Delegation docs for more info
Use quote marks for your name like this:
$('input[name="object.reportEntity.reportEntityIsPrime"]:radio')
Quote the name attribute in your selector string.
$(document).ready(function() {
// Display Alert on Radio Change
$('input[name="object.reportEntity.reportEntityIsPrime"]:radio').change(function () {
alert('Radio Button clicked');
});
}
I have a button and when it is clicked it should add a class to the HTML element, but then when the .class is clicked, it isn't detected.
This is the use case:
Click button - "testerclass" will be added to HTML element
Click "testerclass" - removes that class from that element
The detection for when "testerclass" is clicked only seems to work when the class exists before the page load, not when I add the class manually after load. Is this something to do with the problem?
I have tried to recreate the problem on jsfiddle, but I can't recreate the use case where the class is already added to the HTML element, as I can't edit that on jsfiddle.
But here is jsfiddle one, In this one you can see that the buttonone adds a class to HTML, but the detection for clicks on .testerclass never come through.
And here is jsfiddle two. In this one, I have changed the .testerclass selector to html, and this shows that HTML clicks are bubbling through (which I was unsure of when I first hit this problem).
And offline I created a third testcase where the HTML element already had the testerclass, and it detected the clicks sent through to it.
$(document).ready(function() {
$('button.1').click(function() {
$('html').addClass('testerclass');
$('.test').append('"testerclass" added to html<br />');
});
$('.testerclass').click(function() {
$('.test').append('testerclass clicked and removed<br />');
$('html').removeClass('testerclass');
});
});
Edit: I also tried doing this with a slightly different method of:
$('html').click(function() {
if(this).hasClass('testerclass') {
//do stuff
}
});
but that didn’t work either.
Since the testerclass is dynamic, you need to use event delegation to handle events based on that. Which will require us to register the event handler to the document object that causes another problem because the click event from the button will get propagated to the document object which will trigger the testerclass click handler as well. To prevent this from happening you can stop the event propagation from the button.
$(document).ready(function () {
$('button.1').click(function (e) {
e.stopPropagation();
$('html').addClass('testerclass');
$('.test').append('"testerclass" added to html<br />');
});
$(document).on('click', '.testerclass', function () {
$('.test').append('testerclass clicked and removed<br />');
$('html').removeClass('testerclass');
});
});
Demo: Fiddle
You need to stop the propagation to the html so the other click handler does not pick it up.
$('button.1').on("click", function(evt) {
$('html').addClass('testerclass');
$('.test').append('"testerclass" added to html<br />');
evt.stopPropagation();
});
$(document).on("click", function() {
$('.test').append('testerclass clicked and removed<br />');
$('html').removeClass('testerclass');
});
Other option would be to add one event handler and use the event target to see if it is the button or not and change the content that way.
$(document).on("click", function (evt) {
var isButton = $(evt.target).is(".btn");
var message = isButton ? '<p>"testerclass" added to html</p>' : '<p>"testerclass" clicked and removed</p>'
$('html').toggleClass('testerclass', isButton);
$(".test").append(message);
});
JSFiddle: http://jsfiddle.net/69scv/
here's a neat way to do it
$('html').on('click', function(e) {
var state = !!$(e.target).closest('button.1').length;
var msg = state ? 'class added' : 'class removed';
$(this).toggleClass('testerclass', state);
$('.test').append(msg + '<br>');
});
FIDDLE
You add a class to html element, so when this class is clicked, it means the html element is click. Now the problem is when you click any where in page, it will remove this class away from html! Let try add this class to body element instead.
$(document).ready(function() {
$('button.1').click(function() {
$('body').addClass('testerclass');
$('.test').append('"testerclass" added to html<br />');
});
$('.testerclass').click(function() {
$('.test').append('testerclass clicked and removed<br />');
$('body').removeClass('testerclass');
});
});
And now you can check it:
$('html').click(function() {
if(this).hasClass('testerclass') {
//do stuff
}
});
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.
I have a checkbox inside a div that has an onclick javascript event attached to it.
When I click on the checkbox, the onclick event is fired, instead of the checkbox being checked.
Any ideas on how to fix this behaviour?
Thanks
You can try to change your code (in the jsfiddle.net example) to something like this:
$(function() {
$('#click').click(function(event) {
var $target = $(event.target);
if (!$target.is(':input')) {
// div and contents, except inputs
alert('click');
} else {
// div's content inputs
}
});
});