how to capture change event in input with jquery? - javascript

$('input').change(function(){
alert($(this).val());
});
$('input').val(1);
This dont work. I need capture the change input with JavaScript :-s
Thanks.

Programmatic changes to <input> elements don't cause events. Only user interaction does.
You can do this however:
$('input').val(1).trigger('change');

You have to put those functions inside the "Ready" function. see the fiddle: http://jsfiddle.net/SfjJQ/1/
$(function() {
$('input').change(function() {
alert($(this).val());
});
$('input').val(1);
$('input').trigger('change');
});​
keep in mind that your:
$('input').val(1);
initializes the input to have a value of 1.
Of course you could also do this:
$(function() {
$('input')
.change(function() {
alert($(this).val());
})
.val(1)
.trigger('change');
});​

As others have mentioned, .val() does not trigger any events; however, you could add a wrapper function to jQuery that will change the value and trigger the event if wanted:
$( function () {
//-- new jQuery function
$.fn.changeVal = function () {
$.fn.val.apply( this, arguments );
$( this ).trigger( 'change' );
};
//-- your updated code
$('input').change(function(){
alert($(this).val());
});
$('input').changeVal(1);
} );​
http://jsfiddle.net/bA3V2/

Related

I'm trying to attach events using on() based on changing selectors

I have a button that can be in 2 different states (lets say Lock and Unlock). When I click on the button, I update the class on the button to reflect the binary opposite state. Each class has a different event attachment function using on(string, callback). For some reason the event being triggered remains the first callback assigned based on the original class.
HTML:
<button class="lock">Lock</button>
<button class="unlock">Unlock</button>
JavaScript:
$(document).ready(function() {
$('.lock').on('click', function() {
// Perform some magic here
console.log('Lock!');
$(this).removeClass('lock')
.addClass('unlock')
.html('Unlock');
});
$('.unlock').on('click', function() {
// Perform some magic here
console.log('Unlock!');
$(this).removeClass('unlock')
.addClass('lock')
.html('Lock');
});
});
https://jsfiddle.net/c283uaog/ for testing.
Expected console output when clicking on the same button repeatedly:
Lock!
Unlock!
Lock!
Actual console output:
Lock!
Lock!
Lock!
Any assistance would be greatly desired
use event Delegation
$(document).on('click','.lock', function() {
$(document).on('click','.unlock', function() {
updated Demo
Or use in single function with toggleClass
$(document).on('click', '.lock,.unlock', function () {
$('#output').html($(this).attr('class'));
$(this).toggleClass('lock unlock').text($(this).attr('class'));
});
ToggleClass demo
I'd do it this way, attaching only one event: http://jsfiddle.net/jozu47tv/
$(".lock").on('click', function(e) {
e.preventDefault();
if($(this).hasClass("lock")) {
$(this).removeClass("lock").addClass("unlock");
console.log("lock -> unlock");
} else {
$(this).removeClass("unlock").addClass("lock");
console.log("unlock -> lock");
}
})
Use Event Delegation method, Try this updated fiddle,
$(document).ready(function() {
$(document).on('click', '.lock', function() {
$('#output').html('Lock!');
$(this).removeClass('lock')
.addClass('unlock')
.html('Unlock');
});
$(document).on('click', '.unlock', function() {
$('#output').html('Unlock!');
$(this).removeClass('unlock')
.addClass('lock')
.html('Lock');
});
});
Probably, this question could answer you in a better way:
jQuery .on function for future elements, as .live is deprecated
$(document).on(event, selector, handler)
Change your html to this:
<button class="locker lock" >Lock</button>
<button class="locker unlock"">Unlock</button>
<div id="output">Output</div>
and your Js to this:
$(document).ready(function() {
$('.locker').on('click', function() {
if($(this).hasClass("lock")){
$(this).removeClass("lock");
$(this).addClass("unlock");
$(this).html("unlock");
}
else if($(this).hasClass("unlock")){
$(this).removeClass("unlock");
$(this).addClass("lock");
$(this).html("lock");
}
});
});

click event not working when changing id or class

I'm starting with jquery, and have an issue here:
http://jsfiddle.net/8guzD/
$('#test.off').click(function(){
$(this).removeClass('off').addClass('on');
});
$('#test.on').click(function(){
$(this).removeClass('on').addClass('off');
alert('ok');
});
the first part of the code goes well, the class is apply, but when I attach an event in this element with its new class it won't work.
Can someone explain me what is the problem exactly?
I tried with javascript,
http://jsfiddle.net/R5NRz/
var element = document.getElementById('test');
element.addEventListener('click', function() {
this.id ='test2';
alert("ok");
}, false);
var element2 = document.getElementById('test2');
element2.addEventListener('click', function() {
alert("ok2");
}, false);
and it didn't really help me, having the same issue
try
$(document).on("click",'#test.on',function(){
$(this).removeClass('off').addClass('on');
alert('ok');
});
$(document).on("click",'#test.off',function(){
$(this).removeClass('off').addClass('on');
alert('ok passs');
});
Demo
In your jQuery example you are binding to DOM elements that exist at that time. That is why you see the first fire but not the second. It is not a match for your '#test.on' selector when the code is run. What you want to do instead is use delegation:
$('#test').on('click',function() {
var ele = $(this);
if (ele.hasClass('on')) {
ele.removeClass('on').addClass('off');
} else {
ele.removeClass('off').addClass('on');
}
});
This assumes that you are doing more than just toggling classes. If you want simply toggle classes then an easier solution is to pick one as the default and use the other as a flag. For example, .on is on but without .on it's off. Then you can just use toggle:
$('#test').on('click', function() {
$(this).toggleClass('on');
});
$("#test.on")
Doesn't bind to anything. Try this:
$('#test').click(function() {
if($(this)).hasClass('off') $(this).removeClass('off').addClass('on');
else $(this).removeClass('on').addClass('off');
});
You might consider using an 'active' class instead and just toggling that, instead of have two separate on/off classes. Then you can write:
$("#test").click(function() {
$(this).toggleClass('active');
});

Trigger a function on key up on any input

I want a javascript function to be triggered on key up on any input box. I tried using getElementsByTagName.onkeyup but it didn't work. Along with the solution please send a working jsfiddle. I don't want document.getElementById or onkeyup="function()" as there are many input boxes. It wont look tidy. I even tried
$(document).ready(function(){
$('input').onkeyup(function(){
calculate();
})
})
I also want a function that will add 0 to the value of each input on window.onload.
Thank You
DEMO There is no onkeyup event in jQuery tru to change to keyup
$(document).ready(function(){
$('input').keyup(function(){
calculate();
})
})
.keyup()
try
document.onkeyup = function () {
if (document.activeElement.tagName.toUpperCase() !== 'input') return;
// do sth. here
}
This should do the keyup part:
http://jsfiddle.net/pwqx7/
$(function() {
$('input').bind('keyup', function() {
alert($(this).attr('id'));
});
});
Try
$(document).ready(function() {
$(document).on('keyup', 'input', function() {
calculate();
})
})
Demo: Fiddle

Jquery append input element and send data from that input element

I have this simple HTML code:
<div id="new_gallery">
<p id="add_gallery">Add new gallery</p>
</div>
and jQuery code:
<script>
$("#add_gallery").click(function() {
$("#new_gallery").append('<input name"new_gallery" />Add');
$(this).remove();
});
$("#create_new_gallery").on('click', function(){
alert('1');
});
</script>
First function is working, but second one is not. I need to create new input element, send data via ajax, and then delete the input element and append a p element once again. How can I do this?
When the second statement runs, the element #create_new_gallery does not exist yet so it does nothing.
You can do the binding to the click event after you created the element for instance, this ensures the element exists in the DOM:
$("#add_gallery").click(function() {
$("#new_gallery").append('<input name="new_gallery" />Add');
$(this).remove();
$("#create_new_gallery").on('click', function() {
alert('1');
});
});​
DEMO
Here is a little bit more optimized version. It's a bit non-sense to append an element and have to re-query for it (event though querying by id is the fastest method. Besides, it's best to use the chaining capabilities of jQuery afterall:
$("#add_gallery").click(function() {
var $gallery = $("#new_gallery");
$('<input name="new_gallery" />').appendTo($gallery);
$('Add')
.on('click', function() {
alert('1');
})
.appendTo($gallery);
$(this).remove();
});​
DEMO
#create_new_gallery doesn't exist when you bind its click event.
Here is what your code should look like:
$("#add_gallery").click(function() {
var newG = $("#new_gallery");
$('<input name"new_gallery" />').appendTo(newG);
$('Add').appendTo(newG).on('click',
function() {
alert('1');
});
$(this).remove();
});
Notice that getting $("#new_gallery") into a variable avoid to look for it twice.
$(document).ready(function () {
$("#add_gallery").click(function() {
$("#new_gallery").append('<input name"new_gallery" />Add');
$(this).remove();
$("#create_new_gallery").on('click', function(){
alert('1');
});
});
});
DEMO: http://jsfiddle.net/39E4s/2/
​
Try live to handle the events fired for elements added after the page has loaded.
$("#create_new_gallery").live('click', function(){
alert('1');
});
http://api.jquery.com/live/

How do I bind to the click event from within the click event when I need to do it repeatedly?

I've got code so that when you click on a word, it is replaced by another word.
<script>
$(document).ready(function() {
$('.note_text').click(function(){
$(this).remove();
$('#note_div').append('<span class="note_text">new</span>');
// re-applying behaviour code here
});
});
</script>
<div id="note_div">
<span class="note_text">preparing</span>
</div>
I need the appended word to have the same click behaviour. What is the best way to do this?
change
$('.note_text').click(function(){
to
$('.note_text').live('click',function(){
This will cause anything on your page that ever gets the class 'note_text' to have the behaviour set by .live
You should use a .live()help or .delegate()help binding for that purpose.
$(function() {
$('#note_div').delegate('.note_text', 'click', function(e) {
$(e.target).parent().append("<span class='note_text'>new</span>").end().remove();
});
});
Demo: http://www.jsfiddle.net/PkngP/2/
You could rebind the handler:
function handler(){
$(this).remove();
$('#note_div').append("<span class="note_text">new</span>");
$(".note_text").unbind("click");
$('.note_text').click(handler);
}
$(document).ready(function() {
$('.note_text').click(handler);
});

Categories

Resources