How to handle two unrelated events with jquery - javascript

I'm wondering if I can fire off both of these events together :
$("input[type=checkbox]").click(function(){
if($(this).is(":checked"))
{
//Value of checkbox
alert(this.value);
}
});
and
$("input[type= 'text']").keyup(function(){
alert(this.value);
});
I looked into .bind, but that seems to only work for one selected elements (i.e. $(p).bind("mouseout mouseenter).doSomething()).
The situation I am running into is that I have a function that needs to fire anytime either one of these things occur.

Try
$("input[type=checkbox],input[type='text']").on('click keyup', function(){
// code
});

Two ways you can achieve this as shown below:
using "on" method:
$(document).on('keyup click',"input[type=checkbox],input[type='text']", function(){
// Do stuff here..
})
Call function after the event.
$("input[type=checkbox]").click(doSomething);
$("input[type= 'text']").keyup(doSomething);
function doSomething() {
}

If you still need the additional if, you can use:
$("input[type=checkbox]").click(function(){
if($(this).is(":checked"))
{
//Value of checkbox
alert(this.value);
somethingHappened();
}
});
$("input[type= 'text']").keyup(function(){
alert(this.value);
somethingHappened();
});
function somethingHappened() {
// Do stuff
}

Perhaps all you need is a common function?
$("input[type=checkbox]").click(function(){
if($(this).is(":checked")) {
special(this.value);
}
});
$("input[type= 'text']").keyup(function(){
special(this.value);
});
function special(val) {
alert(val);
}

If your intent really is to invoke a function when any checkboxes/text fields across the whole page changes, you probably want something like this:
$('body').on('change', ':checkbox,:text', function () {
});
Note that the :checkbox and :text selectors are much nicer than input[type=checkbox] etc.

Related

Generalize a specialized JQuery function

This is a question about Multiple Checkbox Select/Deselect Using JQuery:
http://viralpatel.net/blogs/multiple-checkbox-select-deselect-jquery-tutorial-example/
which has the functionality of selecting multiple items from a list to process them. The Online Demo is at:
http://viralpatel.net/blogs/demo/jquery/multiple-checkbox-select-deselect/jquery-select-multiple-checkbox.html
I've extended the demo to include several groups, and have made the sample JQuery JavaScript function to work for one case, the BlackBerry one. The working code is at http://jsfiddle.net/jLx5z99q/3/.
In it, this is the specialized function that I want to generalize:
$(function () {
$("#BlackBerry").click(function () {
$('.case_blackberry').attr('checked', this.checked);
});
$(".case_blackberry").click(function () {
if ($(".case_blackberry").length == $(".case_blackberry:checked").length) {
$("#BlackBerry").attr("checked", "checked");
} else {
$("#BlackBerry").removeAttr("checked");
}
});
});
I want to generalize it so that the "#BlackBerry" and ".case_blackberry" are two parameters to the function, so that I can call it several times to cover other groups as well.
I'm not a JavaScript developer. Please help.
UPDATE:
I've posted the full working html source code at http://pastie.org/10278464.
Also, FYI, this full working html source code is generated automatically by easygen with this template. This html test code is the reason that I wrote easygen, to make it easy to write whatever test case whatever the way I like. Hope it will help someone else too.
Thanks
You need define some specific attributes.
Try this fiddle.
Example Fiddle:: http://jsfiddle.net/iboylmz/2acnLzzw/3/
This could work:
function bindMulti( parent, children ) {
parent.click(function () {
children.attr('checked', this.checked);
});
children.click(function () {
if (children.length == children.filter(':checked').length) {
parent.attr("checked", "checked");
} else {
parent.removeAttr("checked");
}
});
};
Use like this:
bindMulti($('#select_all'),$('.children'));
bindMulti($('#BlackBerry'),$('.case_blackberry'));
Maintaining your current's code logic and flow and element identification, you can do:
$(function () {
$(".case_subgroup_all").click(function () {
$('.case_'+$(this).attr('id').toLowerCase()).attr('checked', this.checked);
});
$(".case_blackberry").click(function () {
if ($(".case_blackberry").length == $(".case_blackberry:checked").length) {
$("#BlackBerry").attr("checked", "checked");
} else {
$("#BlackBerry").removeAttr("checked");
}
});
});
I've also added case_subgroup_all to your 'check all' checkboxes, in order to call your event handler.
jsfiddle: http://jsfiddle.net/jLx5z99q/5/

How can I combine all event handlers at once?

Suppose handler of event listener can be added multiple times like below:
firstPar.addEventListener("click", myFirstEventHandler, false);
firstPar.addEventListener("click", mySecondEventHandler, false);
etc...
So, how can I combine the code so that I could use by shortening:
function allHandler(){
myFirstEventHandler();
mySecondEventHandler();
}
or,
function allHandler(){
return function(){
myFirstEventHandler();
mySecondEventHandler();
}
}
So that I could use:
firstPar.addEventListener("click",allHandler,false);
Or, the other way?
The first way is fine but I would include the event:
function myFirstEventHnadler (event) {
event.stopPropagation(); // To answer your question in the comments.
}
function mySecondEventHandler (event) {
}
function allHandler(event){
myFirstEventHandler(event);
mySecondEventHandler(event);
}
Demo: http://jsfiddle.net/aUE2L/
This may introduce scoping complexities, but why not use an anonymous function.
firstPar.addEventListener("click", function(){
myFirstEventHandler();
mySecondEventHandler();
}, false);

possible clear jquery `one` method

Its possible to clear jquery one property? for example given html
<div id="button">button</div>
<div id="clearOneProperty">clear one property</div>
and js
$("#button").one("click", function () {
alert("blah");
});
$("#clearOneProperty").on("click", function () {
// clear "one" property, that is after this event, I want "#button" to work again
});
Demo http://jsfiddle.net/RzzCu/2/
So, if click #button div, alert happened only one times right?
And I want that, at click on #clearOneProperty, reset one property. Its possible?
P.S. I am not asking how to make this with other ways, I am interest exact: "possible clear jquery one method?". Thanks.
Try this:
function bindButton() {
$("#button").unbind('click').one("click", function() {
alert("blah");
});
}
bindButton();
$("#clearOneProperty").on("click", function() {
bindButton();
});
Updated fiddle
The one unbinds its self on first invocation as stated "The first form of this method is identical to .bind(), except that the handler is unbound after its first invocation", jQuery Documentation *So you need to bind it again*.
Live Demo
$("#button").one("click", onefunction);
function onefunction() {
alert("blah");
}
$("#clearOneProperty").one("click", function() {
$("#button").one("click", onefunction);
});​
Just rebind it inside the function.
$("#button").one("click", function () {
alert("blah");
});
$("#clearOneProperty").one("click", function () {
$('#button').one("click", function () {
alert("blah");
});
});
here a fiddle
Use unbind() method
$("#button").unbind();
Try
$('#button').unbind('click');

jQuery .click() perform the default action before the custom function

Here is my code, I have two checkboxes and want to keep one disabled until the other one is enabled:
$(function(){
$('#remember').live('click', function(event){
if($('#remember').is(':checked')){
$('#keepIn').removeAttr('disabled');
}
else
$('#keepIn').attr('disabled', 'disabled');
});
});
The problem is that this function executes before the default action and when I click in the first one $('#remember').is(':checked') returns false (the old value) instead of true.
You can use change event instead:
$('#remember').live('change', function(event) {
if (this.checked) {
$('#keepIn').removeAttr('disabled');
} else {
$('#keepIn').attr('disabled', 'disabled');
}
});
DEMO: http://jsfiddle.net/jP3NY/
NB: live method is deprecated. You should better use on or delegate.
For the newer version of jQuery the solution could be as follows:
$('body').on('change', '#remember', function(event) {
$('#keepIn').prop('disabled', !this.checked);
});
Instead of body you can use any parent element of #remember.

run function at ready and keyup event

Is there another in jquery to run a function at page load and at a keyup event instead of the way I'm doing it?
$(function() {
totalQty();
$("#main input").keyup(function() {
totalQty();
});
});
Disregarding live or delegate optimizations, you can trigger an event like this:
$(function() {
$("#main input").keyup(function() {
totalQty();
}).filter(":first").keyup(); //Run it once
});
No need for the filter if it's not on multiple elements, just leave it out in that case.
You can use $(document).ready event to run functions on load:
$(document).ready(function(){
/* your code here */
});
Here's what I would do (jQuery 1.4+ )
$(document).ready(function() {
totalQty();
$("#main").delegate("input","keyup",function() {
totalQty();
});
});
You could use $.live(), which does event delegation, which is MUCH more efficient than created an event listener for every single input tag...and then missing any dynamically created ones. Try the following:
$(document).ready(function() {
totalQty();
$('#main input').live('keyup', function() {
totalQty();
});
});

Categories