I want to perform validation before any other onsubmit actions. Unfortunately, I have no control over the value of the onsubmit attribute on the form. So for example:
<form id="myForm" onsubmit="return stuffICantChange()"></form>
I've tried the following code, and several other methods, with no luck:
$("#myForm").onsubmit = function() {
console.log("hi");
}
Any help is appreciated, thanks.
If this is a duplicate, please let me know before marking it as such so that I can refute the claim if necessary.
EDIT:
My code as requested:
<form id="form_ContactUs1" name="form" method="post" action="index.php" onsubmit="return Validator1(this) && ajaxFormSubmit(this); return false">
<div class="form">
<div class="form-staticText">
<p>We look forward to hearing from you! Please fill out the form below and we will get back with you as soon as possible.</p>
</div>
<div class="form-group">
<input class="form-control" placeholder="Name" id="IDFormField1_Name_0" name="formField_Name" value="" size="25" required="" type="text">
<span class="form-control-feedback"></span>
</div>
<div class="form-group">
<input class="form-control" placeholder="Email" id="IDFormField1_Email_0" name="formField_Email" value="" size="25" required="" type="email">
<span class="form-control-feedback"></span>
</div>
<div class="form-group">
<input class="form-control bfh-phone" data-format="ddd ddd-dddd" placeholder="Phone" id="IDFormField1_Phone_0" name="formField_Phone" value="" size="25" type="tel">
<span class="form-control-feedback"></span>
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Comments" name="formField_Comments" id="IDFormField1_Comments_0" cols="60" rows="5" required=""></textarea>
<span class="form-control-feedback"></span>
</div>
<div class="row submit-section">
<input name="submit" class="btn btn-success submit-button" value="Submit" type="submit">
</div>
</div>
$( "form" ).each(function() {
console.log( $(this)[0] );
sCurrentOnSubmit = $(this)[0].onsubmit;
$(this)[0].onsubmit = null;
console.log( $(this)[0] );
$( this )[0].onsubmit( function() {
console.log( 'test' );
});
});
You should be able to add unobtrusively another onsubmit function to #myForm, in addition to the function which already executes:
function myFunction() {
...
}
var myForm = document.getElementById('myForm');
myForm.addEventListener('submit',myFunction,false);
Try
$("#myForm").submit(function(){
.. Your stuff..
console.log("submit");
return false;
});
This will trigger everytime the form is submitted then the end return false stops the forms default actions from continuing.
Try this, it is plain Javascript:
function overrideFunction(){
console.log('Overrided!');
}
var form;
form = document.querySelector('#myForm');
form.setAttribute('onsubmit','overrideFunction()');
Regards.
You should trigger a change event on every field in the form to check on validation.
$('input').on('change', function(e) {
if($(this).val() == '') {
console.log('empty');
}
});
This wil help the user mutch faster then waiting for the submit.
You could also try a click event before the submit.
$('#formsubmitbutton').on('click', function(e) {
//your before submit logic
$('#form').trigger('customSubmit');
});
$('#form').on('customSubmit', function(e) {
//your normal submit
});
Try this code:
$("#myForm").on('submit',function() {
console.log("hi");
});
Stumbling across this post and putting together other javascript ways to modify html, I thought I would add this to the pile as what I consider a simpler solution that's more straight forward.
document.getElementById("yourFormID").setAttribute("onsubmit", "yourFunction('text','" + Variable + "');");
<form id="yourFormID" onsubmit="">
....
</form>
Related
I'd like to display a message above the name field if the user submits a name with a length greater than 20. This means the form will not get submitted - in other words, the form's action won't be triggered.
I've tried almost every suggestion I could find to prevent the form action from being triggered upon form validation but nothing seems to be working.
I've hit a wall with this and can't figure out what I'm doing wrong. How can rectify this?
html:
<form method="POST" id="form" action="/post.php">
<span class="nameError"></span>
<input type="text" class="name" name="name" placeholder="Name" required/>
<input class="button" type="submit" value="Submit"/>
</form>
Here's my jquery:
let name = $('.name');
let nameError= $('.nameError');
$(document).ready(function() {
$('input[type=submit]').on('click', function(e) {
if (name.length > 20) {
e.preventDefault();
nameError.val("Too many characters!");
return false;
}
});
});
I have modified the logic for validation. Basically we need to capture the submit event for the form and use the correct jquery methods to retreive data based upon the selectors.
$(document).ready(function() {
$("#form").submit(function( event ) {
let name = $('.name').val();
let nameError= $('.nameError');
if (name.length > 20) {
nameError.text("Too many characters!");
event.preventDefault();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<form method="POST" id="form" action="/post.php">
<input type="text" class="name" name="name" placeholder="Name" required/>
<label class="nameError"></label> <br/>
<input class="button" type="submit" value="Submit"/>
</form>
Trying to verify form input via a jQuery get request, but function does not get called.
Tried using just the jQuery (without function), the $.get works and returns proper values. I need the function approach to return false if (and stop form from submitting) if condition is not met.
<form onSubmit="return checkName();" action="/register" method="post">
<div class="form-group">
<input id="1" autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password">
</div>
<div class="form-group">
<input class="form-control" name="passconf" placeholder="Confirm password" type="password">
</div>
<button id="2" class="btn btn-primary" type="submit" value="submit">Register</button>
</form>
<script>
function checkName() {
$(document).ready(function () {
$("button").click(function () {
$.get("/check?username=" + document.getElementById('1').value, function (data, status) {
alert(data);
return false;
});
});
});
}
</script>
I expect the function to be called, return true if input verified (and go on with form submission) and false (stop form from submitting) if verification fails.
It isn't common practice to put events within the html anymore, as there is addEventListener. You can add it directly from the javascript:
document.querySelector('form').addEventListener('submit', checkName)
This allows for easier code to navigate, and makes it easier to read.
We can then prevent the form form doing it's default action by passing the first parameter to the function, and calling .preventDefault() as you can see from the modified function below. We no longer need to have return false because of it.
document.querySelector('form').addEventListener('submit', checkName)
function checkName(e) {
e.preventDefault()
$.get("/check?username=" + document.getElementById('1').value, function(data, status) {
alert(data);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="/register" method="post">
<div class="form-group">
<input id="1" autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password">
</div>
<div class="form-group">
<input class="form-control" name="passconf" placeholder="Confirm password" type="password">
</div>
<button id="2" class="btn btn-primary" type="submit" value="submit">Register</button>
</form>
You're returning false from the async handler function. As such, that's not going to stop the form from being sent.
A better solution would be to always prevent the form from being submit then, based on the result of your AJAX request, submit it manually.
Also note that it's much better practice to assign unobtrusive event handlers. As you're using jQuery this is a trivial task. This also gets you access to the Event object which was raised by the form submission in order to cancel it. Try this:
<form action="/register" method="post" id="yourForm">
<div class="form-group">
<input id="1" autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password">
</div>
<div class="form-group">
<input class="form-control" name="passconf" placeholder="Confirm password" type="password">
</div>
<button id="2" class="btn btn-primary" type="submit" value="submit">Register</button>
</form>
$(document).ready(function() {
$("#yourForm").on('submit', function(e) {
e.preventDefault();
var _form = this;
$.get('/check', { username: $('#1').val() }, function(data, status) {
// interrogate result here and allow the form submission or show an error as required:
if (data.isValid) { // just an example property, change as needed
_form.submit();
} else {
alert("Invalid username");
}
});
});
});
You need to return from function not from inside the callback, and you do one if you assign to onsubmit you don't need click handler. And also click handler will not work if you have action on a form.
You need this:
function checkName() {
$.get("/check?username=" + document.getElementById('1').value, function(data, status){
alert(data);
});
return false;
}
this is base code, if you want to submit the form if data is false, no user in db then you need something like this (there is probably better way of doing this:
var valid = false;
function checkName() {
if (valid) { // if valid is true it mean that we submited second time
return;
}
$.get("/check?username=" + document.getElementById('1').value, function(data, status){
if (data) { // we check value (it need to be json/boolean, if it's
// string it will be true, even string "false")
valid = true;
$('form').submit(); // resubmit the form
}
});
return valid;
}
You can mark all your fields as required if they cannot be left blank.
For your function you may use the below format which works for me.
function checkName() {
var name = $("#1").val();
if ('check condition for name which should return true') {} else {
return false;
}
return true;
}
Just write the name of the function followed by (). no need to write return on onsubmit function call
function checkName()
{
$(document).ready(function(){
$("button").click(function(){
$.get("/check?username=" + document.getElementById('1').value, function(data, status){
alert(data);
return false;
});
});
});
}
<form onSubmit="checkName();" action="/register" method="post">
<div class="form-group">
<input id="1" autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password">
</div>
<div class="form-group">
<input class="form-control" name="passconf" placeholder="Confirm password" type="password">
</div>
<button id="2" class="btn btn-primary" type="submit" value="submit">Register</button>
</form>
I think if you replace button type from submit to button and then on button click event, inside get request, if your condition gets true, submit the form explicitly, would help you too achieve what you require.
You should remove the document.ready and the button event click.
EDITED
Adding an event parameter to checkName :
<form onSubmit="return checkName(event);" action="/register" method="post" id="myForm">
<div class="form-group">
<input id="1" autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password">
</div>
<div class="form-group">
<input class="form-control" name="passconf" placeholder="Confirm password" type="password">
</div>
<button id="2" class="btn btn-primary" type="submit" value="submit">Register</button>
</form>
<script>
function checkName(e){
e.preventDefault();
e.returnValue = false;
$.get("/check?username=" + document.getElementById('1').value,
function(data, status){
if(data) // here you check if the data is ok
document.getElementById('myForm').submit();
else
return false;
});}
</script>
I have the following piece of code, that is being executed on submit of a form. Yet the following logic is incorrect as the intent was to develop a universal function that would work for all the forms in my DOM. After failing over and over I ended up creating this function, specific to a this form, that verifies if the values of input fields in my form are the same as their custom defVal attribute, if so the form will stop submitting and an error message will pop up.
My question consists on the following: how can i check if any child elements of my form meet specific parameters, like for example being an input field and have their .val() == .attr('defVal')?
I've already tried using .find(), .children() and .childNode functionalities. Could somebody please suggest me a good solution and if possible explain your code
HTML:
<div class="login" align="center">
<div class="formWrapper">
<form action="index.php?r=backoffice" method="post">
<input type="text" name="USERNAME" required value="username" defval="username" maxlength="16">
<input type="password" name="PASSWORD" required value="password" defval="password" maxlength="16">
<input type="reset" value="reset">
<input type="submit" value="submit">
<hr/>
Can't log in?
</form>
</div>
<div class="infoWrapper">
<div class="info">
</div>
</div>
jQuery:
$('div.login').ready(function(){
$('div.login form').submit(function(e){
if( $('div.login form input').val()==$('div.login form input').attr('defVal') ){
var numMsgs=$('div.login form').children();
if( numMsgs.length<=6 ){
var formHtml=$('div.login form').html();
$('div.login form').html('<a class="sysMsg" href="#">error::invalid username/password</a>'+formHtml);
$('div.login form a.sysMsg').addClass('errFatal').fadeIn(300).delay(5000).fadeOut(300);
}
e.preventDefault();
}
});
});
Try (this pattern)
$(function () {
var elems = $(".login input[defval]");
console.log(elems.length);
$.each(elems, function (i, el) {
if ($(el).val() === $(el).attr("defval")) {
// do stuff
console.log(i, $(el).val() === $(el).attr("defval"), $(el));
};
});
});
jsfiddle http://jsfiddle.net/guest271314/9578v/
After sleeping over the subject I ended up managing to do the task. I've changed the html a bit. Anyway thank you for your suggestion as it was quite useful and actualy toaught me something.
HTML:
<div class="login" align="center">
<div class="formWrapper">
<form action="index.php?r=backoffice" method="post">
<p class="jQueryErr">
<?php
if( !empty($_POST['USERNAME']) && !empty($_POST['PASSWORD']) ){
phpClass::USER_login($_POST['USERNAME'],'username',$_POST['PASSWORD'],'password');
}
?>
</p>
<input type="text" name="USERNAME" value="username" defval="username" maxlength="16">
<input type="password" name="PASSWORD" value="password" defval="password" maxlength="16">
<input type="reset" value="reset">
<input type="submit" value="submit">
<hr/>
Can't log in?
</form>
</div>
jQuery:
$('form').submit(function(e){
var elems=$(this).find('input[defval]');
var errWrapper=$(this).find('p.jQueryErr');
for( var i=0; i<elems.length; i++ ){
if( $(elems[i]).val()==$(elems[i]).attr('defVal') ){
$(errWrapper[0]).html('<a class="sysMsg errWarning" href="#">error:: invalid username/password</a>');
var formSysMsg=$('p.jQueryErr a.sysMsg');
$(formSysMsg[0]).fadeIn(300).delay(5000).fadeOut(300);
e.preventDefault();
break;
}else if( $(elems[i]).val().length<8 ){
$(errWrapper[0]).html('<a class="sysMsg errWarning" href="#">error::'+ $(elems[i]).attr('defVal') +'::is too short!</a>');
var formSysMsg=$('p.jQueryErr a.sysMsg');
$(formSysMsg[0]).fadeIn(300).delay(5000).fadeOut(300);
e.preventDefault();
break;
}
}
});
I am catching event of form submit and adding divs to the DOM, code http://jsfiddle.net/testtracker/7rkX4/7/
now i want to pass some arguments to the function like name of the commenter, time comment was added etc. I want it to be something like this.
html
<form onsubmit="addComment('john deo','post_id')">
<input ......>
<input ......>
</form>
javascript
function addComment(commenter_name,post_id){
perform operation....
}
The code you posted works fine. The reason it would not work in jsfiddle is because your functions are declared in a document.ready type of block by default (see the onLoad in the drop down on the left?)
The proper way to bind event handlers would be to bind them in javascript. This would avoid the scope problem.
If you need to get an inline event handler working, you can explicitly define your function as global:
window.addComment = function (commenter_name,post_id){
perform operation....
};
You can store the name of the commenter in html for example.
Try this (see demo: http://jsfiddle.net/7rkX4/8/).
HTML
<div class="post">
<ul class="comments"></ul>
<div class="comment_entry">
<form method="post" action="#">
<input type="hidden" name="name" value="Neha" />
<input type="text" name="comment" placeholder="Leave comment" />
<input type="submit" value="submit" />
</form>
</div>
</div>
<div class="post">
<ul class="comments"></ul>
<div class="comment_entry">
<form method="post" action="#">
<input type="hidden" name="name" value="Danil" />
<input type="text" name="comment" placeholder="Leave comment" />
<input type="submit" value="submit" />
</form>
</div>
</div>
JavaScript
$(document).ready(function () {
$('.comment_entry form').submit(function (e) {
e.preventDefault();
var name = $('input[name="name"]', this).val();
var comment = $('input[name="comment"]', this).val();
$(this).parent().prev().append('<li><a class="commenter_name" href="/">' + name + '</a><br />' + comment + '</li>');
});
});
If I understand correctly you want to add some variable-value pairs to the form on submit. Why not add some input fields to your form with type="hidden", then you can modify their values in your javascript code as you like.
I want to interrupt and prevent a form from submitting using jQuery. Here's my form markup:
<div id="register-box">
<div id="register-box-inner">
<h2>Register</h2>
<form action="/register" method="post" id="register-form">
<p><label for="username">Username:</label><input type="text" name="username"></p>
<p><label for="password">Password:</label><input type="password" name="password"></p>
<p><label for="email">E-mail:</label><input type="text" name="email"></p>
<p><input type="submit" value="Register" class="register"></p>
</form>
</div>
</div>
and my Javascript code thus far:
$('#register-form').submit(function(e){
e.preventDefault();
alert("hi");
});
Problem is, the form still goes through. I wanted to submit the form using AJAX but with a fallback for users who don't have Javascript enabled. No errors pop up in the Javascript console, either.
Try
$("form").live("submit", function() {
alert("hi");
return false;
});
Try returning false from the handler.
$('#register-form').submit(function(e){
e.preventDefault();
alert("hi");
return false;
});
Try:
<p><input type="submit" value="Register" class="register" onclick="submit(); return false;"></p>