how to know which checkbox was clicked on? - javascript

I have a list of checkboxes. I need to know which was was clicked.
I can't do a loop with
if(form1.news[i].checked)
Because there can be others that are already checked.
I've tried using
this.form.id
this.from.checkboxname.id
but it didn't work.

The event object will contain a reference to the element that was clicked.
For example (using YUI to abstract the browser differences for event binding, other libraries do similar things and you can use raw DOM if you don't mind abandoning old-Internet Explorer):
YUI().use('node', 'event', function (Y) {
Y.one('#container').delegate('click', function (e) {
alert(e.target.get('value'));
e.stopPropagation();
}, 'input[type=checkbox]');
});
​

UPDATED DEMO:
$(function() {
$('#myButton').click(function() {
$('input:checkbox:checked').each(function(i) {
alert(this.value);
});
});
});​

If your onclick() function is on the checkbox, this.id should work just fine.

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());
}
});

Disable select elements using jquery

I have a function which simply disables all select elements using following line of code
$('select').prop('disabled', true);
It works fine for all those select elements which already exist in DOM, however. There are several places where select elements are added using javascript/jquery. And above line of code does not disable those elements. One way to work around is that call that particular plugin everytime those select elements are added to the DOM but this would be a lot of work and needs.
Is there a better way to disable all these select elements?
<a id="myBtn" href="#">Insert select</a>
<script src="/Scripts/jquery-1.8.2.min.js"></script>
<script src="/Scripts/jquery.validate.min.js"></script>
<script>
$(function() {
$("#myBtn").click(function() {
$("body").prepend("<select></select>");
});
$(document).on('DOMNodeInserted', function(e) {
if (e.target.tagName === "SELECT") {
console.log("doing stuff!");
}
});
});
</script>
You need this
$(document).on('DOMSubtreeModified', 'select', function () {
$(this).prop('disabled', true);
});
you can try somoething like this:
$('body').on('DOMNodeInserted', 'select', function () {
$(this).prop('disabled', true);
});
EDIT: it seems that DOMNodeInserted is deprecated. So you should use MutationObserver.
If you need IE9/10 support you can take a look at Polyfill.

How to toggle an element with on()?

I am using the Hammer.js library for mobile touch events and in their example for use with jQuery, they have the following:
$('#test_el').hammer().on("tap", ".nested_el", function(event) {
console.log(this, event);
});
This is straightforward; however, I would like to incorporate a toggle behavior to #test_el. In other words, if the above example was replaced with something like this:
$('button').hammer().on("tap", function() {
$('div').addClass('open');
}, function {
$('div').addClass('close');
});
How would I get this "toggle" behavior to work?
Initially, you could add a starting class to all buttons. Then on event, you can check if the class exists. This lets you know what state the element was in when you tapped it.
$('button').addClass('close');
$('button').hammer().on('tap', function() {
if ($(this).hasClass('close')) {
$(this).removeClass('close').addClass('open');
// Event code
}
else {
$(this).removeClass('open').addClass('close');
// Event code
}
});
jQuery also provides a toggleClass method.
There is already a toggleClass function available in JQuery, it seems that it does what you want.
Try:
$('#test_el').hammer().on("tap", ".nested_el", function(event) {
$(this).toggleClass("classnamehere");
});
Where classnamehere would be your class name.

jQuery on(click) doesn't work but on(hover) does

After initialize js I create new <div> element with close class and on("click") function doesn't work.
$(document).on('click', '.post-close', function () {
alert("hello");
});
but on('hover') work perfectly.
$(document).on('hover', '.post-close', function () {
alert("hello");
});
but I need to make it work on click.
It's because you're not preventing the default behaviour of the browser. Pass e into your handler and then use e.preventDefault()
$(document).on('click', '.post-close', function (e) {
e.preventDefault();
alert("hello");
});
Edit
Also, bind the handler before creating the new <div>
why not use something like
$('.post-close').click(function(){
//do something
});
If the element was added dynamically use:
$(document).on('click', '.post-close', function(){
//do something
});
edit:
like danWellman said, you can add the preventDefault IF you want to make sure no other code is executed. otherwise use the code above.
edit2:
changed the .live to .on
It's an old post but I've had a exactly same problem (element created dynamically, hover works, but click doesn't) and found solution.
I hope this post helps someone.
In my case, I found ui-selectable is used for parent element and that was preventing from click event propagate to the document.
So I added a selector of the button element to ui-selectable's 'cancel' option and problem solved.
If you have a similar probrem, check this
Try turn of libraries for parent element
You're not using stopPropagation() in parent element ?

How to check if there is already a click/event associated to an element

lets say I have
function trigger(){
$('a.pep').each(function(){
$('a.pep').click(function(){
console.log($(this).val());
});
});
}
function push(){
$('body').append('<a class="pep">hey mate i have no trigger yet</a>');
trigger(); //now i do but the others have duplicated trigger
}
$(document).ready(function(){
$('a.push').click(function(){
push();
});
});
So it seems that the click event is being applied twice/+ because the console.log is lauched more than once by click
How can i prevent this?
The problem is that you call $('a.pep').click() lots of times. (In fact, you bind as many click handlers as there are matching elements to each element. And then you do it again every time one of them is clicked.)
You should lever the DOM event bubbling model to handle this. jQuery helps you with the on method:
$(document.body).on('click', 'a.pep', function() {
console.log('element clicked');
$(document.body).append('<a class="pep">Click handlers handled automatically</a>');
});
See a working jsFiddle.
Note that I have removed the val call, because a elements can't have a value... Note also that the on method is introduced in jQuery 1.7; before that, use delegate:
$(document.body).delegate('a.pep', 'click', function() {
Small change to your trigger function is all you need. Just unbind the click event before binding to ensure that it is never added more than once. Also, you don't need to use each when binding events, it will add the event to each item automatically.
function trigger(){
$('a.pep').unbind('click').click(function() {
console.log($(this).val());
});
}
You can check using data('events') on any element if the required event is attached or not. For example to check if click event is attached or not try this.
if(!$('a.pep').data('events').click){
$('a.pep').click(function(){
console.log($(this).val());
});
}
you should use jQuery live here because you add DOM elements dynamicly and you want them to have the same click behaviour
function push(){
$('body').append('<a class="pep">hey mate i have no trigger yet</a>');
}
$(document).ready(function(){
$('a.push').click(function(){
push();
});
$('a.pep').live('click', function(){
console.log($(this).val());
});
});
Try:
if($('a.pep').data('events').click) {
//do something
}
i think if you use live() event you dont need to make function
$('a.pep').live('click', function(){
console.log($(this).val());
});

Categories