On document ready I run this code:
jQuery(document).ready(function(){
jQuery('#button').click(function() {
jQuery('#contact_form').load("/Users/mge/Downloads/jquery-ajax-1/readme.txt");
return false;
});
});
Then if I create a form like
<div id="contact_form">
<form name="contact" method="post" action="">
<fieldset>
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label for="email" id="email_label">Return Email</label>
<input type="text" name="email" id="email" size="30" value="" class="text-input" />
<label for="phone" id="phone_label">Return Phone</label>
<input type="text" name="phone" id="phone" size="30" value="" class="text-input" />
<br />
<input type="submit" name="submit" class="button" id="button" value="Send" />
</fieldset>
</form>
</div>
Everything works fine. However, if I mimic the behavior I want in the actual app (the form is loaded dynamically after document.ready has already been executed. The jquery #button action does not get called and the form acts as if there is no javascript and just runs a post.
jQuery('#contact_form').load("/dynamicform.php");
Is there something that has to be done to .load() in order for the ready function to be applied to it?
Use .live() like this:
jQuery(document).ready(function(){
jQuery('#button').live('click', function() {
jQuery('#contact_form').load("/Users/mge/Downloads/jquery-ajax-1/readme.txt");
return false;
});
});
Your element isn't there when you're adding the handler. You need to listen for the click in all cases...this is what .live() is for, is listens up at the DOM root for the click, whereas .click() isn't getting attached to anything because there are no elements that match the selector when you're calling it. live() listens for clicks on matching elements later.
The .ready event is called when the DOM is ready to be used, and therefore it won't be called when you dynamically load and insert something into an already existing DOM.
Also I believe that it is common practice to have a custom form submit work by attaching an event handler to the form, not the submit button. As it will also handle cases where the user submits the form in another way than clicking on the submit button. Example:
jQuery("#contact_form form").submit(function (event) {
event.preventDefault();
// Do your stuff...
})
(event.preventDefault(): http://docs.jquery.com/Events/jQuery.Event#event.preventDefault.28.29)
ready() is not applied after load(). Look in the doc for load(), you can probably specify a callback to be executed when the loading is done, in which you'll be able to reassign the click handler.
Related
<form action="">
<input type="text" id="id" name="id" value="">
<input type="password" id="pw" name="pw" value="">
</form>
<script>
$('#id').val('darth-vader');
$('#pw').val('i-am-your-father');
$('form').submit();
</script>
I know it would be very ridiculous question, anyway, what I am trying to do is save id and password to local storage or javaScript values, and then automatically log on. (without Server languages, I'm just making prototype on client side)
Of course, the avobe page reload infinitely, How can I do this correctly?
Add event.preventDefault(); to the submit function. Check details here: https://api.jquery.com/submit/
It stops the default event from triggering, which in case of a submit is reloading the page.
You can:
A) handle the submit event and make sure to return false
B) use an ID'd button and bind a 'pseudo-submission' function to the button's click event.
My personal preference is B for simple cases, but using the native submit event allows the browser to handle native validation (such as required, max/mid-length, etc). If you're going to use A, you may return false or use event.preventDefault() to stop the page from reloading. Nothing further is required if you use B.
Self answer
problem :
<form action="">
<input type="text" id="id" name="id" value="">
<input type="password" id="pw" name="pw" value="">
</form>
<script>
$('#id').val('darth-vader');
$('#pw').val('i-am-your-father');
$('form').submit();
$('form').submit(function(e){
e.prenventDefault();
});
</script>
solved :
<form action="">
<input type="text" id="id" name="id" value="">
<input type="password" id="pw" name="pw" value="">
</form>
<script>
$('#id').val('darth-vader');
$('#pw').val('i-am-your-father');
$('form').submit(function(e){
e.prenventDefault();
});
$('form').submit();
</script>
I have 2 forms. I want when button is clicked to show another form on first form position. So just to replace that form.
Form 1
<div id="right">
<form id="contact" class="visible" action="" method="post">
<fieldset>
<input name="fname" placeholder="Ime" type="text" tabindex="1" required>
</fieldset>
<fieldset>
<input name="lname" placeholder="Prezime" type="text" tabindex="2" required>
</fieldset>
<fieldset>
<input name="tel" placeholder="Telefon" type="text" tabindex="2" required>
</fieldset>
<fieldset>
<input name="email" placeholder="Email" type="email" tabindex="2" required>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Pošalji</button>
</fieldset>
</form>
</div>
Form 2
<div id="form2">
<form id="contact2" action="" method="post">
<fieldset>
<input name="fname" placeholder="Ime" type="text" tabindex="1" required>
</fieldset>
<fieldset>
<input name="lname" placeholder="Prezime" type="text" tabindex="2" required>
</fieldset>
<fieldset>
<input name="tel" placeholder="Telefon" type="text" tabindex="2" required>
</fieldset>
<fieldset>
<input name="email" placeholder="Email" type="email" tabindex="2" required>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Pošalji</button>
</fieldset>
</div>
jQuery
$("#contact-submit").on("click", function() {
$("#contact").removeClass("visible");
$("#form2").addClass("visible");
});
So for some reason this is not working. Please help me to solve this. I tried to set opacity:0; of first form but it doesn't work. And please let me know which libary is should use.
Here is my example: http://codepen.io/anon/pen/PzKaPa
EDIT: So I looked at your pen and fixed it so it works: http://codepen.io/anon/pen/OXjEQd
It looks like you'll need to do a couple of things, one of which you might have already: first, place your jquery in a ready function (and make sure you've linked a jquery version in your head tag)--
$(function(){
// your code
});
Then, in your click handler, add a preventDefault():
$('#contact-submit').on('click',function(e){
e.preventDefault();
// rest of code
});
e.preventDefault() keeps your submit button from doing it's default action--submitting the form. This lets you perform other actions with the button. If you don't include this, the very first thing that will happen when your button is clicked is form submission, and you'll not get to any of the other code inside your click event.
This also assumes you have a .visible class defined in your css. If not, you'll need to add that as well, or instead of using addClass and removeClass, you'll need to change the display property on the form directly:
$('#contact').css('display','none');
$('#form2').css('display','block');
Unless you have defined the class visible somewhere else (and have set the CSS defaults for your forms to be hiddne, adding or removing it will have no effect.
Instead, I'd recommend you directly change the display property of the two:
$("#form2").css("display", "none"); // so it's initially invisible
$("#contact-submit").on("click", function() {
$("#contact").css("display", "none");
$("#form2").css("display", "");
});
This will directly alter the style attribute on each element, causing them to hide or show. Using css("display", "") will remove the setting.
You might also look into the hide and show methods in jQuery as they can do the same thing, only with a nice animation.
Unless you have specific CSS that applies to elements with or without the class 'visible', removing and adding that class to the elements will do nothing.
You may want to try
$("#contact-submit").on("click", function() {
$("#contact").toggle();
$("#form2").toggle();
});
to toggle form visibility, and you can initially apply visibility on the forms using CSS or built-in jQuery classes.
I'm not sure why, but when I call $(form).serialize() it returns object within dynamically created elements.
I have this html syntax:
<form id="form1"></form>
<input type="text" name="formItem[0][value]" value="XX" />
<input type="text" name="formItem[INDEX][value]" value="XX" />
I call method to clone input[name="formItem[0][value]"] and replace INDEX with 1, so then I have form like this:
<form id="form1"></form>
<input type="text" name="formItem[0][value]" value="XX" />
<input type="text" name="formItem[1][value]" value="XX" />
<input type="text" name="formItem[INDEX][value]" value="XX" />
But then, when I call method to serialize form, there are still same count of elements -> two - but for this example:
When I submit form for first time, with no cloned input, there was formItem[0][value] and formItem[INDEX][value], but when I call clone and then submit form, serializeArray method return formItem[0][value] and formItem[1][value].
Do you have any idea, how to solve my problem?
https://jsfiddle.net/8u83h22j/2/
Solved - use Chrome instead of Safari browser.
In my website, I am retrieving multiple previously saved addresses from the database and showing them on my website. Now, the user can select any one of them and the data of the address selected will be send to the next page to be inserted into the database.
http://tinypic.com/r/2lj70i9/5
My jsp code to fetch address:
<a href="javascript:next()">
<div class="address1">
<form name="form2" method="post">
<input name="name" type="text" readonly="readonly" value="<% out.print(x1); %>" style="font-weight: bold;" />
<input name="address" type="text" readonly="readonly" value="<% out.print(x2);%>"/>
<input name="city" type="text" readonly="readonly" value="<% out.print(rs1.getString("city"));%>"/>
<input name="state" type="text" readonly="readonly" value="<% out.print(rs1.getString("state"));%>"/>
<input name="pin" type="text" readonly="readonly" value="<% out.print(rs1.getString("pin"));%>"/>
<input name="phone" type="text" readonly="readonly" value="<% out.print(rs1.getString("mob"));%>"/>
</form>
<div class="selectLine">Click to Select</div>
</div>
</a>
and my Javascript is:
function next()
{
var f=document.forms["form2"];
f.method="post";
f.action='checkout3.jsp';
f.submit();
}
but the problem is whatever I'm selecting only the top address is being fetched to the next page.
Currently your anchor elements all call your next() function without passing any information about which item was selected. You could change that by using onclick='next(this)' so that your function gets a reference to the clicked anchor, but it's generally best not to include JS directly inside your html - especially if you're using a library like jQuery which makes it really easy to set up event handlers. (I assume you are either using jQuery already or are open to it given you added the jQuery tag to your question.)
I'd suggesting changing your anchor from:
<a href="javascript:next()">
...to something like:
<a class="selectAddress">
And then instead of your next() function you can use a jQuery-based click handler as follows:
$(document).ready(function() {
$("a.selectAddress").click(function() {
$(this).find("form")
.prop("action", "checkout3.jsp")
.submit();
});
});
That is, bind a click handler to all anchors with that class. Within the handler, this will be the particular anchor clicked, so you can use the .find() method to select the form that is a descendant of the anchor, then set its action property, then submit it. Note that your form has method="post" in its html, so there's no need to set this again like you do in your next() function.
I have a simple form like below that I have added the jQuery validations plugin onto (http://docs.jquery.com/Plugins/Validation). I have this form in a modal popup window so if there are errors and the user closes the window when they open it again the form still has the errors. In my popup close callback I tried calling resetForm() but it says the method doesn't exist.
Form HTML:
<form class="validations" id="commentForm" method="get" action="">
<p>
<label for="name">Name</label>
<em>*</em><input id="name" name="name" size="25" class="required" minlength="2" />
</p>
<p>
<label for="email">E-Mail</label>
<em>*</em><input id="email" name="email" size="25" class="required email" />
</p>
</form>
Popup Close Callback:
function(){
$(this).find('form.validations').resetForm();
}
Thanks in advance for the help.
resetForm is part of the object returned by the validate method, not the form. Example:
var validate = $('#commentForm').validate({ ... });
// Later...
validate.resetForm();
// Or if variable scope is in the way...
$('#commentForm').data('validator').resetForm();
The validation plugin stores a reference to the validation object in the form's data store.
If it really is a short form with just a few elements, you could simply reset them by hand when the close button on the modal window is clicked, like so:
$("input[name='formelementName']").val("");