jQuery show not working after added a new element in document - javascript

I am loading elements into a div container using Ajax / Request. By default I'm hiding an input box. If a user clicks an edit icon on that div, I want to show the input box. Here is my code:
HTML CODE
<div class='container'>
<input type = 'text' onkeydown='saveFn(event,this)' name = 'editemail' class = 'editemail' style='display:none; height:20px;' />
</div>
JS CODE
$(".container").click(function(){
console.log($(this).find(".editemail").show()); //Note it works fine If i didn't load any new elements into the div.
});
Console Log Output before loading new element into the container.
<input type="text" onkeydown="saveFn(event,this)" name="editemail" class="editemail" style="height: 20px; " value="hyther#zohocorp.com" title="press enter to save">
Console Log Output after loading an element into the container.
<input type="text" onkeydown="saveFn(event,this)" name="editemail" class="editemail" style="height: 20px; display: none; " value="saravanan#zohocorp.com" title="press enter to save">
Even though I am also tried to remove the "style" attribute from this element and adding a new style element, it still doesn't work.

First you should read the jQuery Docs FAQ section: Why_do_my_events_stop_working_after_an_AJAX_request
Use on() to delegate the handler for future elements
$(document).on('click', ".container", function(){
/* your code*/
})

Try this instead:
$(document).on('click','.container',function(){
http://api.jquery.com/on/

Try this one instead:
$('.container').live('click', function(){
/* Your Code Here */
});

The problem is that the click() bound is getting lost after an ajax request. In JQuery you can use .live() function to get this working however this function is now deprecated and they encourage you to use .on() or .delegate(). Personally i've have tons of headecks using .on() and .delegate() and rather use the plugin livequery. With livequery plugin is as simple as:
$(function(){
$('#elementId').livequery('click',function(){
//do something on click
})
});
For more information go to:
.livequery()
.on()
.delegate()

Related

.click() not working on a specific index

I'm creating a dynamic menu where I can add and remove a new form.
<input type="button" value="generate form" id="test"/>
<div id="form1"></div>
<script>
$(document).ready(function() {
$("#test").click(function() {
$("#form1").append("<select id='score-attempt'><option value='penalty'>penalty</option></select><input type='button' value='remove' id='remove'/><br>");
});
$("#form1 #remove").click(function() {
alert($(this).index());
});
});
The problem is that clicking on remove never triggers the alert box.
Thanks
The problem is that the element is added later and doesn't exist when the dom is loaded. Therefore the click event has to be delegated from an already existing element, e.g. like this:
$(document).on("click", "#remove", function(){
alert($(this).index() );
});
Instead of $(document) every other static parent element can be used for event delegation, just as example.
Update for the comments: as mentioned, $(document) only as example. I'd also prefer to use $("#form1") here like mithunsatheesh suggested.
And for reference: https://api.jquery.com/on/#on-events-selector-data-handler, section "Direct and delegated events":
"Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()."
Update for the correct index: you'll get the correct index using e.g.
$("#form1").on("click", ".remove", function(){
alert($(".remove").index($(this)));
});
with the adjustment to use remove as class instead of id for the remove-button. IDs have to be unique, so classes are a better solution. index() starts counting with 0, so you'll get 0 for the first one.
As working example: Fiddle
You need to add an event handler on your #form1 input with #remove.
Look here, here and here.
Here is the working jsfiddle for you.

.click() not working when using jQuery

I have a normal js script which has been working since the start of my project. But now for some reason when I click on buttons nothing works at all, no response from the clicking event(note this used to work) and nothing displays in the console log stating if there is an error of some sort... the script just doesn't respond...
Here is the HTML:
<script type="text/javascript" src="js/myscript.js"></script>
<form>
<input type="text" name="signinemail" id="signinemail" placeholder="Enter Email">
<input type="password" name="signinpassword" id="signinpassword" placeholder="Enter Password">
<input type="submit" id ="siginsubmit" name="siginsubmit" value="Sign In">
</form>
Here is my javascript:
$(document).on('pageinit',"#sellbookpage",
function()
{
$("#siginsubmit").click
(
function()
{
alert("hello");
}
);
}
);
Note I am making use of jQuery Mobile
The pageinit event is only available if you use jQuery Mobile. Are you still using that? Otherwise you should use $(document).ready( ... ).
The winning answer to my problem was nothing to do with any of the above posts mentioned above! What was causing the problem was I was using the jQuery mobile, jQuery and Twitter Bootstrap. As soon as I commented out the link to the bootstrap css everything started to work as it used to. Thus there must be a conflict between Twitters Bootstrap and either jQuery or jQuery Mobile.
have u tried using live()
$("#sellbookpage").live('pageinit', function() {
$("#siginsubmit").click(function(){
alert("hello");
});
});
From http://api.jquery.com/on/#on-events-selector-data-handlereventObject:
When a selector is provided, the event handler is referred to as
delegated. The handler is not called when the event occurs directly on
the bound element, but only for descendants (inner elements) that
match the selector. jQuery bubbles the event from the event target up
to the element where the handler is attached (i.e., innermost to
outermost element) and runs the handler for any elements along that
path matching the selector.
siginsubmit is an input (which cannot contain descendant elements let alone descendant elements with id="sellbookpage") so the selector string is not matching anything and the click event is never reaching the siginsubmit input.
Change it to this:
$(document).on('pageinit', function () {
$('#siginsubmit').click(function (e) {
alert('hello');
e.preventDefault();
return false;
});
});
Working fiddle: http://jsfiddle.net/VG3Eg/

Jquery unable to find form inputs to given form id

I'm attempting to run a function on sumbit of a reply form on my website.
These forms are created by Javascript after the page load, so the Jquery is using a live function to react to the click of the ".replyformsubmit" class of button.
I need the script to record the input values of the form, but it seems unable to do so.
Currently the ID of the form which houses the button is found, but using it to try and find the input values seems fruitless, it's probably a school boy error but I can't seem to suss it.
Any help would be great.
The Jquery:
$(".replyformsubmit").live("click", function(){
var curform = $(this).closest('form').attr('id');//what form is the current one?
var comment = $('#' + curform + ' > input[name=comment]"').val(); //comes out as undefined
var replyingSerial = $('#' + curform + ' > input[name=replyingSerial]"').val(); //comes out as undefined
...
The script seems unable to find what comment and the replyingSerial are.
The HTML for a standard example form is:
<form action="com.php" method="post" id="replyform_quickreply_1345291318.6107" class="replyform">
<textarea name="comment" type="text" id="commenttextquickreply_1345291318.6107">
</textarea>
<br>
<input type="submit" value="send!" class="replyformsubmit">
<input type="hidden" style="visibilty: hidden;" name="replyingSerial" value="1345291318.6107"></form>
A couple of things. Comment is a textarea, not an input, so if you want to find it you need to use textarea[name=comment].
Second, you can use parent() and find to make your code a little cleaner:
$(".replyformsubmit").on("click", function(){
var parent = $(this).parent();
var comment= parent.find("textarea[name=comment]");
alert(comment.val());
});​
That's because the button is a submit, it prevents the rest of the code to be executed.
Use type='button' instead.
Or use:
$('#formname').submit(function() {
alert('Handler for .submit() called.');
return false;
});
change input type="submit" to input type="button" as it wont allow other code to get executed afer the submit, and instead of .live() use .on()
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
This method provides a means to attach delegated event handlers to the document element of a page, which simplifies the use of event handlers when content is dynamically added to a page. See the discussion of direct versus delegated events in the .on() method for more information.

alert not being fired when I append a new div

On this fiddle http://jsfiddle.net/adrianjsfiddlenetuser/zyUkd/46/ the divs 'Hello 01' & 'Hello 02' fire an alert when they are clicked. When i click 'Add New' a new div is added but when I click on this div the alert is not fired even though it is styled with same css .
How can I amend this so that the alert is fired when a new div is appended ?
Code from jsFiddle for posterity
JS
$(function() {
$(".myDivs").click(function() {
alert('Clicked');
});
$("#button").click(get);
function get() {
$(".connected").append("<div class=\"myDivs\">hello</div>");
}
});
HTML
<div class="connected">
<div class="myDivs">Hello 01</div>
<div class="myDivs">Hello 02</div>
</div>
<input name="Button3" type="button" value="Add New" id="button">
​
​
You need delegate event handler, because your way on bind event only bind event to existing DOM .myDivs, but not for upcoming.
$(".connected").on('click', '.myDivs', function() {
alert('Clicked');
});
DEMO
For more detail go here
That's because your jQuery is using the document.ready to make the assignment. Because this element was not present at the load, it does not have this assignment. You need to make this assignment separately.
the answer thecodeparadox gave is valid. But I went ahead and updated your fiddle to fully match the latest jQuery convention.
DEMO
Here's a link to the jQuery documentation for more information:
jQuery .on()

Javascript doesn't work on elements added by jquery's load(), prepend(), or append() functions

I have a comment system where a user submits a comment, the comment is processed, then the HTML for the comment is returned. jquery then adds that retrieved HTML to the comment system. that whole system works, but the comment buttons that requir javascript do not work unless I refresh the page. How do make my javascript work on elements added through load, prepend, or append?
Not sure if my question is clear, but here's the javascript I have:
$(function () {
$(".replyform").submit( function (event) {
event.preventDefault();
id = $(this).attr("id").split('_')[1];
text = $('textarea#text_'+id).val();
$.post( "/api/add/comment/", {_csrf: _csrf, id: id, text: text, a: a},
function (data) {
$('#commentreplies_'+id).prepend(data);
$('#replyform_' + id).hide();
});
});
});
I then have elements such as "reply" for each comment that have functions in an external javascript that do not work unless I refresh the page. Hopefully that made sense.
Use jQuery live() (it is deprecated, see on()) function
jQuery has a live method to allow elements that are added on the page after loading to be able to have events already bound by jQuery. You can bind your events using live method as described here.
A second solution, and probably a more efficient one, would be using delegate method to handle events by existing containers and delegating them to the elements inside that container. You can read more about delegate here.
An example solution using live method is as follows assuming you have buttons with class 'reply' in your response data:
$(".reply").live('click', function(event) {
event.preventDefault();
id = $(this).attr("id").split('_')[1];
text = $('textarea#text_'+id).val();
// post won't work since url is missing, but that code remains the same.
// Assuming you get a response like this
// <div><input type="textarea" id="text2" /><input type="submit" id="reply_2" value="submitReply" class="reply" /></div>
// And if you append this to your document
var data = $('<div></div>').html('<input type="textarea" id="text2" /><input type="submit" id="reply_2" value="submitReply" class="reply" />');
$('#commentreplies_'+id).prepend();
$('#reply_' + id).hide();
});
There are few different approaches to this
1) Explicitly init the button inside returned HTML on AJAX success
2) Setup global handler for your button type using jQuery live() function (replaced by on() in 1.7)
3) define button handler right in the markup
Which one do you pick is really up to your specific task.

Categories

Resources