jquery change handler of object that is replaced - javascript

Is there a way to keep checking an object if it's checked after it is replaced
this illustrates the problem I'm having
http://jsfiddle.net/nr6eA/
once the element is replaced the change function is not triggered again, while I have a pretty good idea why this is happening, I'm not sure how to solve this.
I've got a lot of checkboxes, and adding a script to each when they are replaced doesn't seem to be the best idea.
Is there a way of re-initializing the jquery function ofter an ajax update?

You need event delegation. For that purpose you can use on() with jQuery 1.7+ like below:
For .on():
$(document).ready(function() {
$('#f').on('change', ' input:checkbox', function() {
$('#textbox1').val($(this).attr('id') + " " + $(this).is(':checked'));
$(this).replaceWith('<input type="checkbox" id="checkbox1" class="ichange"/>')
});
});​
But, your fiddle shows jQuery 1.6.2. In that case you can use live() or delegate().
For live():
$(document).ready(function() {
$('#f input:checkbox').live('change', function() {
$('#textbox1').val($(this).attr('id') + " " + $(this).is(':checked'));
$(this).replaceWith('<input type="checkbox" id="checkbox1" class="ichange"/>')
});
});​
And for delegate():
$(document).ready(function() {
$('#f').delegate('input:checkbox', 'change', function() {
$('#textbox1').val($(this).attr('id') + " " + $(this).is(':checked'));
$(this).replaceWith('<input type="checkbox" id="checkbox1" class="ichange"/>')
});
});​
But it would be better if you can use .on() with jQuery 1.7+.

Related

jQuery change value of input and display it as text

I'm struggling with the following problem. I have input text element. I want a user to enter something there and then his value appears as a normal text (the input should disappear).
I searched for a few solutions but nothing worked for me. What I tried (whatever function I provide, I get no results, what should I provide to get the effect I described above and how to make it happen?):
$('input.modified').on('input', function(){
(this).append('<p>some</p>');
});
OR
$("input.modified").bind("propertychange change keyup paste input", function(){
$(this).append("<p>dgdgd</p>");
});
OR
$("input.modified").change(function(){
$(this).css("visibility","hidden");
}); //end change function
How to make functions like .on() or .change() work with my code?
thanks for all the answer, but I can't move your examples to my code :(
Please verify this fiddle what I'm missing:
[http://jsfiddle.net/w6242/][1]
Check this DEMO
HTML:
<input class="modified" type="text"/>
<p></p>
JS:
$("input.modified").change(function(){
$('p').html($(this).val());
$(this).css("visibility","hidden");
});
check this
Fiddle
$("#in").focusout(function(e){
$("span").html(($("#in").val()));
$(this).hide();
});
Here a fiddle http://jsfiddle.net/keypaul/NsWC5/5/
HTML
<div id="wrapper">
<input type="text" id="writer" />
send
</div>
JQuery
$("#submit").click(function(e){
var txt = $("#writer").val();
$("#writer").fadeOut(400);
$("#submit").fadeOut(400, function(){
$("#wrapper").append('<div id="text">' + txt + '</div>').hide().fadeIn(600);
});
e.preventDefault();
});
If you need to do that with onther event (instead of a click submit) you can use onchange or focusout applied to your input element
At its simplest, assuming you really want to replace the input:
$('#demo').on('keyup', function(e){
if (e.which === 13) {
var p = $('<p />', {
text : this.value
});
$(this).replaceWith(p);
}
});
JS Fiddle demo.
Or, to insert an adjacent element and simply hide the input:
$('#demo').on('keyup', function(e){
if (e.which === 13) {
var span = $('<span />', {
text : this.value
});
$(this).hide().after(span);
}
});
JS Fiddle demo.
The above jQuery works with the following demonstrative HTML:
<input id="demo" type="text" />
References:
after().
hide().
on().
replaceWith().

mouseover function of jquery not working on dynamically created div

I am trying to add a mouseover function to dynamically created elements using jquery
$('#schools').append(
'<div class="mediumListIconTextItem" onclick="javascript:showSchoolReport(\'' + $.trim(this.id) + '\',\'' + $.trim(this.companyID) + '\',\'' + $.trim(this.companyCode) + '\',\'' + $.trim(this.companyName) + '\');" style="padding-left: 30px;margin: 5px;">' + '<div class="icon-newspaper mediumListIconTextItem-Image"></div>' + '<div class="mediumListIconTextItem-Detail">' + '<h6 id="header" style="max-width:100px; overflow:hidden;">' + this.name + ' - ' + this.companyName + '</h6></div></div>');
code for mouseover effect
$(document).ready(function (e) {
$(".mediumListIconTextItem").mouseover(function () {
alert($(this.name));
});
});
$(".mediumListIconTextItem").on("mouseover", function () {
alert('mouseover works!!!!!!!!!');
});
});
none of the above function for mouseover works. whats wrong with my code. suggest a solution
This is the case called event delegation. In here you can't bind the direct event to a dynamically created elem. try this as below:
$(document).on("mouseover", ".mediumListIconTextItem", function() {
alert('mouseover works!!!!!!!!!');
});
You're almost there, you have to use on but in a different form. You're using direct event but you need to use delegated events
$('#schools').on("mouseover", ".mediumListIconTextItem", function() { .. }
For more details check section Direct and delegated events
Use on() for dynamically added elements like,
$(document).on("mouseover", ".mediumListIconTextItem", function() {
alert('mouseover works!!!!!!!!!');
});
Use .on()
As elements are added dynamically you can not bind events directly to them .So you have to use Event Delegation.
$(document).on("mouseover", ".mediumListIconTextItem", function() { .code here. }
better use
$("#schools").on("mouseover", ".mediumListIconTextItem", function() { .code here. }
Syntax
$( elements ).on( events, selector, data, handler );
Use event delegation :
$('#schools').on('mouseover', '.mediumListIconTextItem', function(){ ... })
For a clear and short explanation of how event delegation works, see this question :
Direct vs. Delegated - jQuery .on()

Setting checkbox as checked with jQuery

I have two input checkboxes, and I want to check/uncheck them with jQuery:
<input type="checkbox" name="user1" value="1" id="u1" onclick="loadUserCalendar(1)">
<input type="checkbox" name="user2" value="2" id="u2" onclick="loadUserCalendar(2)">
JavaScript code:
var list = new cookieList("calendar_users");
var users = list.items();
for (var i = 0; i < users.length; i++) {
$('input[name="user' + users[i].substr(1,1) + '"]').attr('checked', true);
console.log('substring: ' + users[i].substr(1,1));
console.log('enabling user ' + users[i]);
}
var users contains these values: u1,u2 . To only get the user ID, I perform a substring, which gets me the correct number as you can see below in the console output.
Console output:
substring: 1
enabling user u1
substring: 2
enabling user u2
I have no idea, why the checkboxes are not checked when the code ran. What am I doing wrong here?
Edit: I am using jQuery 1.4.4 due to compatibility reasons, that's why I am using .attr()
Inline event handlers (onclick="loadUserCalendar(1)") are not the jQuery way. You should not have any in your html. Get rid of them and add to your jquery:
$(function() {
$('form').on('click',':checkbox', function() {
loadUserCalendar($(this).val());
});
});
But maybe what you wanted was this:
$(function() {
$('form').on('click',':checkbox', function() {
$('form :checkbox').attr('checked','checked');
});
});
The jquery 1.ancient version:
$(function() {
$('input[type=checkbox]').live('click', function() {
// do things
});
});
What version of jQuery are you using?
You have to try something like :
$('input[name="user' + users[i].substr(1,1) + '"]').attr('checked', 'checked');
or
$('input[name="user' + users[i].substr(1,1) + '"]').prop('checked', 'checked');
The second one is jQuery 1.6+
When you want something to be checked you have to do the following:
$('.myCheckbox').attr('checked','checked');
If you have created the checkboxes dynamically use jQuery on method, because simple functions won't be able to access these elements.
Regarding the initialization of the checkboxes I would suggest something like this:
$('input[type=checkbox]').each(function(index, box) {
$(box).attr('checked', $.inArray($(box).attr("id"), users) != -1);
});

HTML <select> JQuery .change not working

Alright I don't see why this isnt working. It seems pretty simple.
Here is my drop-down menu:
<div>
<form>
<select id='yearDropdown'>
<c:forEach var="years" items="${parkYears}">
<option value=/events.html?display_year=${years}<c:if test="${currentYear == years}">selected="selected"</c:if>>${years}</option>
</c:forEach>
</select>
</form>
</div>
and here is the JavaScript
$("#yearDropdown").change(function () {
alert('The option with value ' + $(this).val());
});
Right now I just want to get it working so I can add functionality. Thanks!
That code is syntactically correct. Most likely running it at the wrong time.
You'll want to bind the event when the DOM is ready:
Native JS/DOM
window.addEventListener('DOMContentLoaded', () => {
const yearDropDown = document.getElementById('yearDropdown');
yearDropDown.addEventListener('change', () => {
alert(yearDropDown.value)
});
});
jQuery
$(function(){ /* DOM ready */
$("#yearDropdown").change(function() {
alert('The option with value ' + $(this).val());
});
});
Or, use live:
$("#yearDropdown").live('change', function() {
alert('The option with value ' + $(this).val());
});
Or, use delegate:
$(document.body).delegate('#yearDropdown', 'change', function() {
alert('The option with value ' + $(this).val());
});
Or, if you're using jQuery 1.7+:
$("#yearDropdown").on('change', function() {
alert('The option with value ' + $(this).val());
});
Nonetheless, it is usually best to execute script once the browser has finished rendering Markup.
I have tried your code in jsFiffle.
I manually added some years as options.
It works right.
Just bind the .change event in the $(document).ready:
$(document).ready(function(){
$("#yearDropdown").change(function () {
alert('The option with value ' + $(this).val());
});​
});
Your code is correct and is working for me, see here: http://jsfiddle.net/mobweb/2Skp9/
Are you sure jQuery has been loaded properly?
Not sure if this will help, but you could try this:
$("#yearDropdown").live("change", function () {
alert('The option with value ' + $(this).val());
});

.click() in a <div> in a <div> does not work

$('#A').click(function () {
$('#A1').prepend('<div class="AcL" id=' + i + '>Hello<span class="RmMe" id="' + i + '" style="margin-left:20px; cursor:pointer;">X</span></div>');
i++;
});
$('.RmMe').click(function () {
alert("OK");
});
<div id="A1"></div>
Any idea why the click is not working?
You need to use .delegate() or .live() because you are attempting to bind a handler to an element that does not yet exist.
$('#A').click(function() {
$('#A1').prepend('<div class="AcL" id='+i+'>Hello<span class="RmMe" id="'+i+'" style="margin-left:20px; cursor:pointer;">X</span></div>');
i++;
});
$('.RmMe').live('click', function() { alert( 'OK' ); });
Try that.
EDIT:
However, should you be using jQuery 1.7+, the .on method is the preferred approach: See post from xdazz
$('.RmMe').on('click', function () {
alert("OK");
});
Good luck!
Try use .onDoc.
$('.RmMe').on('click', function () {
alert("OK");
});
You have to use
$('.RmMe').on("click",function(){
alert("OK");
});
because this element does not exist when your DOM is created, it is inserted afterwards and you cannot bind click to the element which does not exist. .live adds an event listener for you, which makes it easy to achieve the task you want.

Categories

Resources