I'm adding some content through form to the database and then reload this part of page to update the content. And then I want to add the next content and again reload but the .submit method I use, sends undefined instead of the written content. Here's the HTML code:
<form id="addForm" method="post" action="/addContent">
<input type="text" id="content" name="name" value="" placeholder="New content" required/><br/><br/>
<input name="submitted" id="submitted" value="Add content" class="submit" type="submit" />
</form>
And here's JS:
<script>
$('#addForm').submit(function() {
$.post('/addContent', {
data: $('#addForm').serializeArray(),
}, function(response) {
$('#contentPart').html(response);
});
return false;
});
</script>
Can anyone help me? I'll be gratefull.
You need to assign your event on any addForm form that may appear in DOM in the future:
$(document).on('submit', '#addForm', function() {
...
});
Related
I am trying to post the form from modal. To keep the current page, I target post to the iFrame.
Which trigger is triggered after posting the form? Or any other solution to close modal after post?
OnSubmit, as seen in the code, do not work.
<div class="modal-body">
<form method="post" id="modalForm" action="/Test/TestForm" target="myframe">
<input type="text" name="id" required />
<input type="text" name="name" required />
<input type="submit" value="Post" onsubmit="alert('after post - close modal!');" />
</form>
</div>
You can post form via Ajax and get the begin and end request by using the following approach:
<script>
$(document).ajaxStart(function () {
//display loading, etc.
});
$(document).ajaxComplete(function () {
//hide loading, etc.
});
</script>
My JS is not that great so I have been fiddling with this for a while now.
I have a form which is being POST to another file when the submit button is clicked. When it is clicked I also want to show an alert then redirect the user back to a URL.
The redirecting code works just fine on a button where I call the function "onclick" like so:
<button onclick="test()">Return</button>
But I don't want to have an extra button for this...I want the form to POST then show an alert box then go to URL specified but I get not a function error from console, thanks.
<iframe name="noreloadhack" style="display:none;"></iframe>
<form action="http://www.example.com/test.php" onsubmit="return test();" method="post" target="noreloadhack">
JS:
<script>
function test() {
alert('Hello World');
var return_url = document.getElementById('return_url').value;
window.location.href= return_url;
}
</script>
If it makes a difference I have the form target set to a hidden iframe as a hack to not reload page on submit (I know, not the best method). I'm pretty much using 4 form attributes here.
I have some old code that I used to solve a similar situation. Where I wanted to submit a form but not reload the page, here it is. Since there were only 4 input fields I just grabbed the values using jquery.
Javascript:
function processForm() {
var teamMembers=new Array();
console.log($("#"));
var schoolName=$("#schoolname").val();
var teamMembers=new Array();
teamMembers.push($("#contestant1").val());
teamMembers.push($("#contestant2").val());
teamMembers.push($("#contestant3").val());
$.ajax({
method: "POST",
url: "php/register.php",
data: { schoolname: schoolName, teammembers:teamMembers.toString()}
})
.done(function( msg ) {
alert( "Your team is now registered " + msg );
$('#register').hide();
location.reload();
});
// You must return false to prevent the default form behavior
// default being reloading the page
return false;
}
HTML:
<form id="registration_form" onsubmit="return processForm()" method="POST">
<p style="margin:0px;">School Name:</p>
<input type="text" id="schoolname" name="schoolname" autocomplete="off" class="input" required>
<hr>
<p style="margin:0px;">Contestants</p>
<div id="teammembers">
<input type="text" id="contestant1" name="contestant1" autocomplete="off" class="input" required>
<p></p>
<input type="text" id="contestant2" name="contestant2" autocomplete="off" class="input" required>
<p></p>
<input type="text" id="contestant3" name="contestant3" autocomplete="off" class="input" required>
</div>
<input type="submit" id="registered">
I am doing a web application using javascript and html that has a form containing a text field, button. When I enter a number in that text field and submit by clicking on that button, text areas are generated dynamically. Once my form is submitted some text areas are created but if I am not satisfied with existing text areas then again I enter some value with out refreshing page. But the text field value entered previously prevails showing the new text areas below the existing text areas on the page.
So, how do I clear the value with out refreshing the page.
<div>
<html>
<input type="text" name = "numquest" id ="numquest" value="" size="5" style="" disabled>
<input type="button" value="submit" onclick="getFields();">
</div>
</html>
<javascript>
var num_q=document.getElementById('numquest').value;
//code for dynamic creation
</javascript>
try this:
Using jQuery:
You can reset the entire form with:
$("#myform")[0].reset();
Or just the specific field with:
$('#form-id').children('input').val('')
Using JavaScript Without jQuery
<input type="button" value="Submit" id="btnsubmit" onclick="submitForm()">
function submitForm() {
// Get the first form with the name
// Hopefully there is only one, but there are more, select the correct index
var frm = document.getElementsByName('contact-form')[0];
frm.submit(); // Submit
frm.reset(); // Reset
return false; // Prevent page refresh
}
You can set the value of the element to blank
document.getElementById('elementId').value='';
Assign empty value:
document.getElementById('numquest').value=null;
or, if want to clear all form fields. Just call form reset method as:
document.forms['form_name'].reset()
you can just do as you get that elements value
document.getElementById('numquest').value='';
<form>
<input type="text" placeholder="user-name" /><br>
<input type=submit value="submit" id="submit" /> <br>
</form>
<script>
$(window).load(function() {
$('form').children('input:not(#submit)').val('')
}
</script>
You can use this script where every you want.
It will clear all the fields.
let inputs = document.querySelectorAll("input");
inputs.forEach((input) => (input.value = ""));
HTML
<form id="some_form">
<!-- some form elements -->
</form>
and jquery
$("#some_form").reset();
I believe it's better to use
$('#form-id').find('input').val('');
instead of
$('#form-id').children('input').val('');
incase you have checkboxes in your form use this to rest it:
$('#form-id').find('input:checkbox').removeAttr('checked');
.val() or .value is IMHO the best solution because it's useful with Ajax. And .reset() only works after page reload and APIs using Ajax never refresh pages unless it's triggered by a different script.
I had that issue and I solved by doing this:
.done(function() {
$(this).find("input").val("");
$("#feedback").trigger("reset");
});
I added this code after my script as I used jQuery. Try same)
<script type="text/JavaScript">
$(document).ready(function() {
$("#feedback").submit(function(event) {
event.preventDefault();
$.ajax({
url: "feedback_lib.php",
type: "post",
data: $("#feedback").serialize()
}).done(function() {
$(this).find("input").val("");
$("#feedback").trigger("reset");
});
});
});
</script>
<form id="feedback" action="" name="feedback" method="post">
<input id="name" name="name" placeholder="name" />
<br />
<input id="surname" name="surname" placeholder="surname" />
<br />
<input id="enquiry" name="enquiry" placeholder="enquiry" />
<br />
<input id="organisation" name="organisation" placeholder="organisation" />
<br />
<input id="email" name="email" placeholder="email" />
<br />
<textarea id="message" name="message" rows="7" cols="40" placeholder="сообщение"></textarea>
<br />
<button id="send" name="send">send</button>
</form>
You can assign to the onsubmit property:
document.querySelector('form').onsubmit = e => {
e.target.submit();
e.target.reset();
return false;
};
https://developer.mozilla.org/docs/Web/API/GlobalEventHandlers/onsubmit
I am trying to validate a form, but I can't get any code to execute when my button is clicked. Here's my code:
<div id="vehicle_form">
<form method="post" name="emailForm" action="">
<input class="dField" id="dfEmail" type="email" name="email" value="Email" onfocus="clearInput(this);" onblur="restoreInput(this)"><br/>
<input class="dField" id="dfName" type="text" name="firstname" value="First Name" onfocus="clearInput(this);" onblur="restoreInput(this)"><br/>
<input class="dField" id="dfLast" type="text" name="lastname" value="Last Name" onfocus="clearInput(this);" onblur="restoreInput(this)"><br/>
<button type="button" id="dSubmit">Submit</button>
</form>
</div>
$('#dSubmit').click(function(){
console.log('click');
});
You need to ensure that your jQuery is wrapped in a <script> tag, and ensure that the function is being loaded, perhaps by a $(document).ready() function, as shown below:
<script type='text/javascript'>
$(document).ready(function(){
//Your Click event
$('#dSubmit').click(function(){
console.log('click');
});
});
</script>
Working Demo
Actually the code stays wrong. A form can be often submitted by hitting enter inside of a textfield. If you want to make it right you should use the submit event.
<script>
$(function(){
$('#vehicle_form > form').submit(function(){
console.log('submit');
});
});
</script>
Well im new to jquery and ajax and the code below doesnt work after 2nd attemp of submit form... heres the javascript code:
$(document).ready(function() {
var options = {
target: '#output2', // target element(s) to be updated with server response
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
};
$('#myForm2').submit(function() {
$(this).ajaxSubmit(options);
return false;
});
$('#me').submit(function() {
$("#div2").load("main.php");
return false;
});
});
function showRequest(formData, jqForm, options) {
return true;
}
function showResponse(responseText, statusText, xhr, $form) {}
by the way im using jquery form plugin.....
and for the index.php
<form id="me" action="" method="post">
Message: <input type="text" name="mess">
<input type="submit" value="submit">
lastly for the main.php
<form id="myForm2" action="index.php" method="post"><div>
Name:</td><td><input name="Name" type="text" />
<input type="reset" name="resetButton " value="Reset" />
<input type="submit" name="submitButton" value="Submit1" />
</div></form>
<h1>Output Div (#output2):</h1>
<div id="output2">AJAX response will replace this content.</div>
</div>
You downloading your form after page load ( *$("#div2").load("main.php")) and your events are already binded. So when your second form loaded, it's Submit button click event doesn't triger nothing. You have to read about .live() in jQuery here
Here is my solution (that is just simpl example):
$('#myForm2').live("click",function() {
$(this).ajaxSubmit(options);
return false;
});
Maybe this will work for you.
UPD
Also you can try this:
1) replace
$('#myForm2').live("click",function() {
$(this).ajaxSubmit(options);
return false;
});
with
function MyFormSubmit(form) {
$(form).ajaxSubmit(options);
return false;
})
2) Add JS code to you myForm2 Submit button onClick event
<form id="myForm2" action="index.php" method="post"><div>
Name:</td><td><input name="Name" type="text" />
<input type="reset" name="resetButton " value="Reset" />
<input type="submit" name="submitButton" value="Submit1"
onClick="javascript:MyFormSubmit(this);return false;"/>
</div></form>
<h1>Output Div (#output2):</h1>
<div id="output2">AJAX response will replace this content.</div>
</div>
You have to remove action="index.php" method="post" from your form. Then should it work.
because now it is still making the php post to index.php