I want to auto-sumbit my form once user clicks out side the div of the form.
I tried the following but it submits within clicking within the div.
<div id="formDiv">
<form id="search">
<input id="target" type="text" value="Field 1" />
<input type="text" value="Field 2" />
</form>
</div>
// auto submit
jQuery('#formDiv').live('blur',function() {
$(this).children('form').submit();
});
Off-hand, the only thing I can suggest it so attach to the click event of the body, then also attach to the div's click event and e.preventDefault() to halt it. Alternatively, you could bind to each form element's focus/blur event with a .delay. If they lose focus from one element and aren't in another, submit the form.
EDIT
See if this is what you're looking for:
Javascript:
var queueSubmit;
$('#sample input').each(function(i,e){
$(this).bind('focus',function(){
clearTimeout(queueSubmit);
});
$(this).bind('blur',function(){
queueSubmit = setTimeout(function(){ $('#sample').submit(); }, 1000);
});
});
$('#sample').bind('submit',function(){
clearTimeout(queueSubmit);
alert('Pseudo-Submitted!');
return false;
});
Sample HTML
<div id="main">
<p> </p>
<div id="main-form">
<form id="sample" method="POST" target="">
<fieldset>
<legend>My Sample Form</legend>
First Name: <input type="text" id="first_name" /><br />
Last Name: <input type="text" id="last_name" /><br />
Telephone: <input type="text" id="telephone" /><br />
<input type="submit" value="Submit" />
</fieldset>
</form>
</div>
<p> </p>
</div>
Working Example Here
I would do this by putting a click handler on the body and seeing if the event target (event.target) is a descendent element of #formDiv:
$('#search').one('focus', function() { // the first time that a field in #search receives focus
var $formDiv = $('#formDiv');
$(document.body).click(function(e) { // bind a click handler to the document body
if (!$formDiv.has(e.target).length) { // if the target element is not within formDiv
$('#search').submit(); // submit the form
}
});
});
Related
I want to create a dynamic questionnaire, loading the next question dynamically, but when I load the second question, the event of the button next2 doesn't respond as if there were no event.
I think it's because I load the input with a JavaScript function. What do I have to do to make it work?
$(document).ready(function() {
var question2 = `
<form>
<input type="number" id="age" placeholder="age">
<input type="submit" id="next2">
</form>
`;
var question3 = `
<form>
<input type = "email" id="email" placeholder="email">
<input type="submit" id="next3">
</form>
`;
$('#next').click(function(e) {
e.preventDefault();
console.log(1);
$(".questions").html(question2);
});
$("#next2").click(function(e) {
e.preventDefault();
$(".questions").html(question3);
});
$("#next3").click(function() {
alert('Cool');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<div class="questions">
<form>
<input type="text" id="name" placeholder="Name">
<button type="submit" value="Next" id="next">Next</button>
</form>
</div>
</html>
You should use $(document). It is a function trigger for any click event in the document. Then inside you can use the jquery on("click","#idname",somefunction), where the second argument specifies which specific element to target. In this case every element inside the body.
$(document).on('click', '#next', function(e) {
e.preventDefault();
$(".questions").html(question2);
});
You only need one event handler for all this, not multiple.
You are inserting the HTML into the element with the class questions with $(".questions").html. Given that you should hook the event handlers to that element with the questions class to be as close to the element as possible (not make it traverse the entire DOM looking for things in the events.
Here I took the CURRENT html and saved it to myApp which I created to hold stuff and not pollute the global namespace; Then I cycle back to it on the last. Odd that you have both button and input type submit but I also handle that. Since these are submit buttons in a form, I added the submit event in case that is how it gets triggered.
$(function() {
let myApp = {};
myApp.question2 = ` <form>I am 2
<input type="number" id="age" placeholder="age">
<input type="submit" id="next2" data-nextthing="question3">
</form>
`;
myApp.question3 = ` <form>I am 3
<input type = "email" id="email" placeholder="email">
<input type="submit" id="next3" data-nextthing="question1">
</form>
`;
myApp.question1 = $(".questions").html(); // just to store it
$(".questions")
.on('click submit', 'form, button[type="submit"], input[type="submit"]', function(event) {
event.preventDefault()
let d = $(this).data('nextthing');
$(event.delegateTarget).html(myApp[d]);
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="questions">
<form>
<input type="text" id="name" placeholder="Name">
<button type="submit" value="Next" id="next" data-nextthing="question2">Next</button>
</form>
</div>
How can I change immediately the submit button text if any form input change?
//This applies to whole form
$('#test').change(function() {
$("#send").prop("value","Change");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="test">
<input id="Input1" value="Input1" />
<input id="Input2" value="Input2" />
<input type="submit" id="send" value="Send" />
</form>
Here, the button text change after the cursor leave the input.
Live example : http://jsfiddle.net/rgg3A/56/
Use input event
Use :input Selector, Selects all input, textarea, select and button elements
$('#test').find(':input').on('input', function() {
document.getElementById('send').value = this.value;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form id="test">
<input id="Input1" value="Input1">
<input id="Input2" value="Input2">
<input type="submit" id="send" value="Send">
</form>
You need to put the listener on the inputs themselves, in this case attach it to the onKeyDown event:
$('input').on("keydown", function() {
send.value = "Change";
});
Updated Fiddle
A solution requiring minimal change would be to use the keyup event. I.e.
$('#test').keyup(function() {
send.value = "Change";
});
This way, typing in any of the input fields within the #test parent will trigger the event.
You can do it by using jquery input event and selector.
$('input').on("keydown", function() {
$('#send').val(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="test">
<input id="Input1" value="Input1">
<input id="Input2" value="Input2">
<input type="submit" id="send" value="Send">
</form>
As your original question did not mention JQuery directly except by it's use as a selector, this one left me hanging for a proper JavaScript answer.
So this answer is the same as the other examples, but using just plain ol' JavaScript. Uses the input event, just as the other answers do.
document.getElementById('test').addEventListener('input', function(e) {
document.getElementById('send').value = e.target.value;
});
<form id="test">
<input id="Input1" value="Input1">
<input id="Input2" value="Input2">
<input type="submit" id="send" value="Send">
</form>
The difference here is that it is listening for bubbled events on the form element proper, registers an event listener only once (instead of applying the same event listener to multiple elements), and using the Event.target property to figure out which element was modified.
I am trying to open another form to get inputs after submitting one. In my code, I want to edit a node in my array and by getting the first input I make the program find my node to edit. If the input is valid -the input is one of the nodes in my array-, I want it to open another on the same place as the first one. How can I do that?
<p>
EDIT AN EXISTING NODE
</p>
<form action="#" style="display: none;" id="editNodeForm">ID or Name:
<input type="text" id="toEdit" size="20" style="width: 50%; height: 2em;">
<br />
<br />
<button type="button" class="myButton" form="editNodeForm" style="width: 50%;" onclick="editExistingNode();">Submit</button>
<br />
<br />
</form>
What I would do is put all the fields inside a form, and separate the steps with divs.
On page load, you hide all the steps (except the first one). After clicking the button, the next step gets displayed.
The last step won't have a button, but a submit button, making it fire the form.
$(function() {
$('form>div:not(:first)').hide(); /* hide all but first step */
$('form').on('click', 'button', function(e) {
e.preventDefault();
var currDiv = $(this).parent() ,
nextDiv = parent.next('div');
$(currDiv).hide();
$(nextDiv).show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div>
Step 1 / 3
Add some value: <input type="text" /><br />
<button>Next step</button>
</div>
<div>
Step 2 / 3
Add some value: <input type="text" /><br />
<button>Next step</button>
</div>
<div>
Step 3 / 3
Add some value: <input type="text" /><br />
<input type="submit" value="Save form" />
</div>
</form>
Try to replace the the line
nextDiv = parent.next('div');
with:
nextDiv = $(this).parent().next('div');
in the code of the comment above, if it's not working
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've been at this for two days and can't seem to get it. Basically, I'm using the JQuery Cookbook modal from scratch. My problem is the form html page loads fine but the code will not recognize my submit button. Here's the relevant parts of the code:
Separate HTML:
<div id="contact">
<form action="" id="register_form" method="post">
<p>First Name <br />
<input type="text" id="firstname" name="firstname" /></p>
<p>Last Name <br />
<input type="text" id="lastname" name="lastname" /></p>
<p>Username: <span class="micro">Must be a valid email address</span></span><br />
<input type="text" id="username" name="username" /></p>
<p><input type="submit" value="Register" id="register" /></p>
</form>
</div>
Here's the relevant parts of the modal code:
// Insert modal at end of </body>.
$('body').append('<div id="modal_wrapper"><!--[if IE 6]><iframe id="modal_iframe" frameborder="0"></iframe><![endif]--><div id="modal_overlay"></div><div id="modal_window"><div id="modal_bar"><strong>Modal window</strong>Close</div><div id="modal_content"><div id="contact"><form><p><input id="firstname" /></p><p><input id="register" /></p></form></div></div></div>');
$('#modal_content').load('mediaKitF.html#contact'.replace('#', ' #'), '', showModal);
$("input[type=text]").focus(function(){
// Select field contents
this.select();
});
$('input #firstname').focus();
$('#register').click(function () {
alert("hello there");
});
$('#modal_content').load() is an asynchronous method, which means that you are trying to attach your click event to the $('#register') element before receiving the new content. You need to either use $('#register').live('click', function() {}) or move the code attaching the click handler into your showModal function.