How can I hide a form after submission with JavaScript? - javascript

So I have these forms:
django template:
{% for F in forms %}
<input type="text" name="name/>
<input type="number" name="number/>
<input type="submit" class="button" [onclick="this.disabled=true,this.form.submit(); ??]> #how can I make this work?
{%endfor%}
What the template code does is render out multiple forms based on the value of forms> I want the user to submit the form and then have the form either disappear(preferable) or at least disabled so that they can resubmit. How can I do this?

If you have multiple forms on the page and want to handle them with JavaScript, I would suggest you to use jQuery. You could make something like:
$('input[type="submit"]').click(function() {
// here comes your logic
// and the next line removes the corresponding form
$(this).parents('form').remove();
});
But as Marc B pointed out, you should submit the form via Ajax. I don't know what do you intend to do with the user input, but if you want to use Ajax then you could make something like:
$('form').submit(function() {
$.ajax({
// your logic
});
});
Check the official documentation of jQuery for more details and adapt the examples to your needs.
EDIT:
if you want to prevent the form from submitting and refreshing the page, please change it slightly to:
$('form').submit(function(event) {
$.ajax({
// your logic
});
event.preventDefault();
});

Related

Update form fields without refresh (prevent duplicated form)

I need to update (submit) form without refresh. I know it should be done using Ajax, so I found many examples on this website, but none of them was useful in my case. Here's the catch - I don't need to display any "success" or similar messages when form was submitted, I need to display exactly the same form, but with new values.
Examining examples on this site, I got it working, but when form is submitted via ajax (this part works fine), I see two forms displayed. Here's the example - http://www.lipskas.com/form/ (the whole source is available to view)
What should I change here?
P.S. If I change "$('#msg').html(html);" to "$('#myForm').html(html);" duplicated form doesn't appear, except one "little" problem - the form can be submitted only for the 1st time. Then no more values are properly submitted.
In case you are interested why I need to display exactly the same form (but with updated fields) again, it's because I built some type of calculator which has many fields, and when user updates ANY field, re-calculations are made ( http://lipskas.com/bandymas/ )
Get rid of the "onclick" in the submit button and add this in the header above the chk function
<body>
<form id="myForm">
<input type="text" name="username" value="submitted - "><br/>
<input type="text" name="password" value="submitted - "><br/>
<select name="some_array[1]"><option value="1">1</option><option value="2">2</option></select>
<select name="some_stuff[2]"><option value="3">3</option><option value="4">4</option></select>
<input type="submit" name="submit_ok" value="test me">
</form>
</body>
function chk(this)
{
$.ajax({
type:"post",
url:"index.php",
data: this.serialize(),
cache:false,
success: function (html){
$('body').html(html);
}
});
}
$(function(){
$("body").on("submit","#myForm",function(){
chk($(this));
return false;
});
});

Enable field function triggers after second function is called

I need some help with sequencing (not sure if this is the right term) two jQuery functions so that both can co-exist together.
What I am trying to do is to add a new functionality that makes a field uneditable to the users, like disabled="disabled". Catch is that if I only apply disabled="disabled" to the filed the form will not send its value with the form submit.
Therefore, I have written some JS code, which enables the fields prior submitting and permits that their values are sent when form is submitted.
All works fine once the page is loaded.
Problem is when the user leaves one of the mandatory fields blank and tries to submit the form. Then there is another jQuery that fires - to validate the field contents.
This second validation function triggers the enable field function and all fields become editable again.
Need some help on how to prevent the second function to override the enable one.
Here is the code - the enable function is placed right before the form like this:
<script>
jQuery(function($) {
$('form').bind('submit', function() {
$(this).find(':input').removeAttr('disabled');
});
});
</script>
<form name="RegFrm" id="RegFrm" action="" method="post">
<select class="validate[required] text-input" disabled="disabled">
<option value="">Please Select</option>
</select>
<input name="sbtFrm" type="submit" value="Submit" />
</form>
And here is the second field validation function that is placed on a separate file. It is being invoked from files_include.php every time the page loads:
var genVar = jQuery.noConflict();
genVar(document).ready(function(){
genVar("#RegFrm").validationEngine();
});
How can I prevent the second function triggers the first one?
Thank you?
Thank you all for the comments. Although, no solution proposed you guys gave me an idea how to fix it.
I basically decided to check on form submit if form validates and only if true, then the enable function triggers.
This is the code:
jQuery(function($) {
$('form').bind('submit', function() {
if($("#RegFrm").validationEngine('validate')){
$(this).find(':input').removeAttr('disabled');
};
});
});

Using Array submission syntax in HTML?

Well, I have a lot of input fields in a form, some of them are like this:
<input name="agents[]" type="file" />
Moreover suppose there is a plus button besides this field like this:
<img src="plus.jpg" id="some_id" />
A user can add more agents field in addition to the one field present already.
So I was wondering how would I handle these kind of input fields when submitting form data through Ajax? Using JavaScript objects perhaps?
What's the main problem?
For Ajax uploading i'm using https://github.com/blueimp/jQuery-File-Upload
For handling dinamic form contents i use jquery .serialize()
Like this
var info = $("#additem").serialize();
$.post('/url.php', info, function(data) {
// response
}, 'json');
"additem" is the id of the form
<form id="additem">

Jquery .load and POST data

This is really frustrating I would appreciate some help with this. I have a div, called comments and a form inside of that div. What I want to do is post a form to the current page and have it load inside of the div without reloading the entire thing. Here is my current code:
<div id="comments">
<form action="#" method="post" onsubmit="return false;" >
<input type="hidden" name="txtname" value="test">
<textarea id="wysiwyg" name="wysiwyg" rows="5" cols="50"></textarea>
<input type="submit" name="post" id="post" value="Submit">
</form>
<script type="text/javascript">
EDIT: Read edit below for current code
</script>
</div>
When I submit, the alert fires, but the page does not load. It works fine if I make the event as follows:
$("#comments").load("comments.asp");
It's not liking the posting of data. I have used .load before but never to post data. I got the above code from these very same forums.
I'm honestly not sure of the purpose of 'name' and 'tel' - do I refer to those variables or the form variable names when processing the code? This is in ASP classic.
What's wrong with the above code, how can I get it to send data from the forum via POST? Thanks!
EDIT:
I am now using the following code:
$("#post").submit(function(event){
var $form = $(this),
$inputs = $form.find("input, select, button, textarea"),
serializedData = $form.serialize();
$inputs.attr("disabled", "disabled");
$.ajax({
url: "/comments.asp",
type: "post",
data: serializedData,
success: function(response, textStatus, jqXHR){
console.log("comment posted");
},
error: function(jqXHR, textStatus, errorThrown){
console.log(
textStatus, errorThrown
);
},
complete: function(){
// enable the inputs
$inputs.removeAttr("disabled");
}
});
event.preventDefault();
});
And now it's using properly getting the form handled...however it goes to comments.asp. How can I make all the action happen in a certain div (comments div?)
It seems to me you are blending a bunch of different techniques in a way that is not entirely coherent.
$.post is a shortened version of $.ajax (see here).
$.load takes a url and sticks it into a <div> or other DOM Element (see here).
If I understand it correctly (and I may not!), you're not really wanting to load the form, but put values into the form fields. $.load is an odd way to do this. (It may work, but I do it another way.)
If you're using $(#...).submit, you can also leave out a whole bunch of stuff in your form. The following should work fine.
<form id="form_id">
...
<input type="submit" value="Submit">
</form>
My method is: (1) have a hardcoded HTML form (or build it by AJAX), (2) get the values from the DB (or wherever) using $.post (or $.ajax), (3) stick the values into the form using .val() (or equivalent - whatever is right for the input type) and the DOM id of that input, and then (4) use .submit (in a manner similar to yours). You will need to add preventDefault as the others have suggested.
You're also muddying the waters using #post as the DOM id. You really want to give the form itself the ID, and then use $(#form_id).submit(... I can't test it now, but having the submit on the input field may cause some grief. The official example attaches the .submit to the form id.
I'm also not sure the <div> with id 'comments' really does much. I have a container id like your 'comments', but that's because I build forms by AJAX and stick them into the container. If you don't need to do that, the id 'comments' is unnecessary to the whole procedure.
Your text box element dont have an id with value txtname. But in your script you are trying to access using # (which is supposed be with an id context). So add an id element to your input box.
<input type="hidden" name="txtname" id="txtname" value="test">
And as expascarello said, You need to stop the default behaviour of the submit button . Other wise it will do the normal form posting so you wont be able to feel the ajax effect.
Use preventDefault
$(function(){
$("#post").click(function(e) {
e.preventDefault()
alert("clicked");
$("#comments").load("comments.asp", {
'name': $("#wysiwyg").val(),
'tel': $("#txtname").val()
});
});
});
You are not cancelling the clicking of the button so the form is submitting and resetting the page.
$("#post").click(function(evt) {
evt.preventDefault();
...
jQuery event.preventDefault()
The load() method does a get and not a post.

jQuery - reset form after submit w/ form plugin

let me start by saying it may look simple but im finding it extremely difficult.
ive made a search script that uses PHP and to fetch a result would look like this
search.php?term=alice&submit=Submit
Standard stuff.. problem is, i use an SPI with AJAX and PHP so my results would have to load dynamically into a div, whilst still keeping the hash value, as not to lose the page the user had visited previous to searching.
jQuery.history.js is the plugin i use for back button support, which requires links to be like such:
Home Page
this would load 'home.html' into a div named pageContent. as far as i know theres no way to call php files unless you develop a little hack, which i have,
here is my JavaScript/jQuery for my search form:
<script language="JavaScript">
$(document).ready(function() {
// bind form using ajaxForm
$('#search1').ajaxForm({
// target identifies the element(s) to update with the server response
target: '#pageContent',
// success identifies the function to invoke when the server response
success: function() {
$('#pageContent');
var hash = '#search.php?term='+($('#query').val()+'&submit=Submit').replace(/ /g, '+');
var stripped = hash.replace(/(<([^>]+)>)/ig,"");
update(window.location.hash = stripped);
}
});
});
</script>
Heres the form:
<form id="search1" action="search.php" method="post">
<input id="query" type="text" name="term" />
<input type="submit" name="submit" value="Submit" />
</form>
My problem is this:
ive tried this.form.reset(); this: Resetting a multi-stage form with jQuery , yet none of this works. please help me if you know a way of doing this..
$('#query').val(DefaultValue);
with this u can set your value to whatever you want, like blank: '';

Categories

Resources