Jquery unable to find form inputs to given form id - javascript

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.

Related

.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/

Event at value changed using jquery.val()

I have an <input type="text"> that have you value updated for many other scripts jQuerys, using the method .val("value here"). I need a new script to be run when the value of input has been updated. How to associate an event that'd make it for me?
Here is my code:
$('#PedidoTotalDescontoPadrao').change(function()
{
console.log('test');
});
but it doesn't work
I think you're using the wrong event handler for what you need.
Try this one.
http://api.jquery.com/keyup/
The change() method does not applies to <input type="text"> html tags. you may wan't to do it with keyup().
$('#PedidoTotalDescontoPadrao').keyup(function() {
console.log('test');
// and this is how you'd trigger the other events you want
$('.something').trigger('click');
});

jquery for regexp doesnt work

i use a jquery for a input box to validate content of that
i person who has worked before me make a file that name is comoon.js and that file support all another files.but when i write this code on (document).ready(function() like this
$(document).ready(function()
{
$('#validate').keyup(function(){
var i = $('input');
(/http:\/\//).test(i.val()) && i.val(i.val().replace('http://',''));
});
});
and i have input box like this
<input type="text" id="validate" class="right" name="linkurl" maxlength="150" size="130"/>
but it doesnt work on this button what should i do and what is the problem and i know that js file loaded of all pages ...
Assuming you have more than one input on your page the problem is this line:
var i = $('input');
...which sets i to a jQuery object containing all inputs on the page. Try instead:
var i = $(this);
...which will set i to a jQuery object containing just the element the event occurred on.
(Your code works when there is only one input.)
If the input in question is created dynamically after page load you'll have a second issue: you can't bind an event handler to an element that doesn't exist yet, but you can use a delegated event handler:
$(document).ready(function()
{
$(document).on("keyup", '#validate', function(){
var i = $(this);
(/http:\/\//).test(i.val()) && i.val(i.val().replace('http://',''));
});
});
Where ideally you'd replace document in $(document).on("keyup", '#validate', ... with the closest ancestor of "#validate" that exists on page load. If you're using a version of jQuery less than 1.7 use .delegate() instead of .on() (see the jQuery API doco for more info).

jQuery show not working after added a new element in document

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

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