JQuery .on("click", function() ) doesn't work - javascript

I am trying to fire JQuery when I checkbox is checked. At first I realized my JQuery only works for static elements. I read through a couple posts and found out that I need .on("click, function()) in order to fire that same piece of javascript for dynamically added elements.
However, this method still doesn't work for me. Can anyone help? Thank you.
$(document).ready(function(){
$("input[name='todo']").on('click', function(){
var isChecked = this.checked
if (isChecked == true){
$(this).next().remove();
$(this).remove();
}
if (isChecked == false)
{
alert("checkbox is NOT checked");
}
});
});
My example app: http://jsfiddle.net/JSFoo/7sK7T/8/

You need delegation:
$('#ToDoList').on('click', "input[name='todo']", function() { ... });
http://jsfiddle.net/7sK7T/9/
Documentation: http://api.jquery.com/on/#direct-and-delegated-events
PS: the important note - you need to specify the element you're binding your handler to as close to the target elements as possible. In your case it's #ToDoList, not body or document as other answers advice.

For dynamic elements you would want to do something like this
$(document).ready(function () {
$(document).on('click', "input[name='todo']", function () {
var isChecked = this.checked
if (isChecked == true) {
$(this).next().remove();
$(this).remove();
}
if (isChecked == false) {
alert("checkbox is NOT checked");
}
});
});
if you use it like you were before on('click') is basically the same as click(); because you are still selecting the elements required and applying the event to those elements, the way the above example works is it is only applies the event to the document then checking the selector when the event is fired.
You can also change document to a close container of the elements to be clicked if you wish.
This is called Event Delegation
jQuery Learn Event Delegation

The below is what you needed. It is slightly different syntax
$(document).on('click', "input[name='todo']", function(){

You bind the elements on document ready, it's before they're created.
You have to bind AFTER their creation.
Alternatively you can bind their container on document.ready:
$("#containerDiv").on('click', "input[name='todo']", function(){
// .... your code
});
"containerDiv" should be the parent element of those checkboxes, it should be in the page on document ready!

Related

How to convert jQuery to JavaScript name attribute

I'm trying to find a way to create 'on click' events for dynamically generated buttons in JS. I know that in jQuery it can be done like this:
$(document).on('click', 'name=[buttonName]', function() {});
I know the e.target method in JS, but I'm wanting to find a way to do it with a name attribute instead.
Thanks
Firstly that line of jQuery isn't quite right as the square brackets are in the wrong place:
$(document).on('click', '[name="buttonName"]', func);
To achieve the same in plain JS you would need to attach a click event handler to a static parent element, then check the name property of the clicked element:
document.addEventListener('click', function(e) {
if (e.target.name == 'buttonName') {
// do something...
}
});
document.addEventListener('click', function(e) {
if (e.target.name == 'buttonName') {
alert('Hello!');
}
});
<button>I do nothing!</button>
<button name="buttonName">I say hello!</button>
You can use querySelector in a similar way than you would in jQuery, and attach the event listener whenever a new element is added to the DOM.
document.querySelector("button[name='buttonName']").addEventListener("click", function(){
alert("Hello, World");
});
<button name="buttonName">Click me</button>
The difference to the original jQuery code is that in that example it listens to events on the document whereas this does not.
You can use getElementByName to add click event to your button which is dynamically render
document.getElementByName("ButtonName").addEventListener("click", function(e) {
});

What is the proper way of binding REMOVE event listener to dynamically created elements in JQuery

My goal is to perform a certain operation each time an element with a certain id or class is deleted from DOM. Prior to this, I've been successfully using a standard syntax for binding click events on dynamically created elements like this:
$(document).on('click', '.someClass', function(e) {
alert("Div was clicked");
});
Inspired by this post, I tried to do the same thing for REMOVE event listener, and failed.
Here is my jsFiddle.
Any hints on how to make this work? And maybe what I am trying to do is fundamentally wrong, and I should come up with some entirely different logic ?
http://jsfiddle.net/wphtjw1o/
This is the functionality of Jquery UI script, so you have to include two scripts Jquery and Jquery UI to make it work.
$(function() {
$('<div id="DivToBeRemoved">DIV TO BE REMOVED</div>').prependTo('body');
$("#DivToBeRemoved").on("remove", function () {
alert("Element was removed");
});
$(document).on('click', '#DivToBeRemoved', function(e) {
alert("Div was clicked");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<button onclick="RemoveDiv();">Click here to remove div above</button>
<script type="text/javascript">
function RemoveDiv() {
var d = $("#DivToBeRemoved");
d.remove();
}
</script>
If I got you correctly, you trying to write custom event (remove event in your case).
For calling custom event you don't need any library, you need to trigger that event, like so:
function RemoveDiv() {
var d = $("#DivToBeRemoved");
// d.remove();
d.trigger('remove'); // <--
}
Read more about trigger: .trigger()
Also check this question here on SO: Custom events in jQuery?
jsfiddle

jquery change css on radio button and page load

I have the following jquery snippet which is showing or hiding items by css depending on which radio button is selected...
<script>
jQuery('input:radio[name="type"]').change(
function(){
if (jQuery(this).val() == 'value1') {
jQuery('.one').css({'display':'none'});
jQuery('.two').css({'display':'block'});
jQuery('.three').css({'display':'none'});
}
else if (jQuery(this).val() == 'value2') {
jQuery('.one').css({'display':'block'});
jQuery('.two').css({'display':'none'});
jQuery('.three').css({'display':'none'});
}
else if (jQuery(this).val() == 'value3') {
jQuery('.one').css({'display':'none'});
jQuery('.two').css({'display':'none'});
jQuery('.three').css({'display':'none'});
}
});
</script>
It is working great but what I want to do now is have this happen on page load as well instead of just when the radio button is changed.
Whats the simplest way to achieve this?
You could chain the .change() method after attaching the event listener.
In doing so, a change event is fired after the event listeners are attached (which will presumably happen when the page loads).
Example Here
$('input:radio[name="type"]').change(function () {
// ...
}).change(); // <---
You could also use .trigger('change') in place of .change() too:
Example Here
$('input:radio[name="type"]').change(function () {
// ...
}).trigger('change'); // <---
Depending on where the script is placed in your HTML document, you may need to make sure it is wrapped within a DOM ready handler too!
$(document).ready(function () {
$('input:radio[name="type"]').change(function () {
// ...
}).change();
});

if clicked arround element with jQuery

i just wanna ask if there's something like "if clicked arround" in jQuery, i mean, if clicked any element in the page except for one element, or if there a way to make that easily.
You can try this:
$(document).on("click", function(event) {
if($(event.target).parents().index(yourElement) == -1) {
// your code here
}
});
Yes you can use .not()
event.stoppropagation
Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
$('#divID').not('#ElID').click(function(){
//* code here */
});
Or
:not()
$('#divID:not("#ElID")').click(function(){
//* code here */
});
Start Reading jQuery API Documentation and Learning
Updated After OP's comment.
Fiddle Demo
event.target and .is()
$('#divID').click(function (event) {
if (!$(event.target).is('#ElID')) {
alert('Work');
}
});
Fiddle Demo
Works on click anywhere except element with id ElID
$('html').click(function (event) {
if (!$(event.target).is('#ElID')) {
alert('Work');
}
});

jQuery .on('change', function() {} not triggering for dynamically created inputs

The problem is that I have some dynamically created sets of input tags and I also have a function that is meant to trigger any time an input value is changed.
$('input').on('change', function() {
// Does some stuff and logs the event to the console
});
However the .on('change') is not triggering for any dynamically created inputs, only for items that were present when the page was loaded. Unfortunately this leaves me in a bit of a bind as .on is meant to be the replacement for .live() and .delegate() all of which are wrappers for .bind() :/
Has anyone else had this problem or know of a solution?
You should provide a selector to the on function:
$(document).on('change', 'input', function() {
// Does some stuff and logs the event to the console
});
In that case, it will work as you expected. Also, it is better to specify some element instead of document.
Read this article for better understanding: http://elijahmanor.com/differences-between-jquery-bind-vs-live-vs-delegate-vs-on/
You can use any one of several approaches:
$("#Input_Id").change(function(){ // 1st way
// do your code here
// Use this when your element is already rendered
});
$("#Input_Id").on('change', function(){ // 2nd way
// do your code here
// This will specifically call onChange of your element
});
$("body").on('change', '#Input_Id', function(){ // 3rd way
// do your code here
// It will filter the element "Input_Id" from the "body" and apply "onChange effect" on it
});
Use this
$('body').on('change', '#id', function() {
// Action goes here.
});
Just to clarify some potential confusion.
This only works when an element is present on DOM load:
$("#target").change(function(){
//does some stuff;
});
When an element is dynamically loaded in later you can use:
$(".parent-element").on('change', '#target', function(){
//does some stuff;
});
$("#id").change(function(){
//does some stuff;
});
you can use:
$('body').ready(function(){
$(document).on('change', '#elemID', function(){
// do something
});
});
It works with me.
You can use 'input' event, that occurs when an element gets user input.
$(document).on('input', '#input_id', function() {
// this will fire all possible change actions
});
documentation from w3
$(document).on('change', '#id', aFunc);
function aFunc() {
// code here...
}

Categories

Resources