What is wrong whit this jQuery submit function? - javascript

This code runs smoothly except submit function. If I change the submit function with another function such as "show();" it works. Why doesn't it run this submit function?
$(document).ready(function() {
$('#submit').click(function() {
var email = $('#email').val();
email = $.trim(email);
var password = $('#password').val();
password = $.trim(password);
if (email == "" || password == "") {
$('.division').show();
} else {
$('#form').submit();
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form" method="post" action="run.php">
<input type="text" id="email" name="email">
<input type="password" id="password" name="password">
<input type="checkbox" checked="checked" id="keep" value="yes">
<label for="keep">Keep login</label>
<input type="submit" id="submit" value="Sign in" onClick="return false;">
</form>

The problem is that you've given your submit button the id "submit". Browsers add elements to the form object using the id, so the normal submit function of the form is being replaced with a reference to your submit button.
Change the name (and probably id) of the submit button to (say) submit-btn and it will work. Live Example
Separately from that, though, I wouldn't hook click on the submit button at all; I'd hook submit on the form element, since forms can be submitted in other ways (pressing Enter in certain form fields, for instance).
Example: Live Copy
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<script>
$(document).ready(function(){
$('#form').submit(function(e){
var email = $('#email').val();
email = $.trim(email);
var password = $('#password').val();
password = $.trim(password);
if( email == "" || password == "") {
$('.division').show();
e.preventDefault(); // Don't allow the form submission
}else{
$('#form').submit();
}
})
});
</script>
<!-- Using GET rather than POST, and no action
attribute, so that it posts back to the jsbin page -->
<form id="form" method="get">
<input type="text" id="email" name="email">
<input type="password" id="password" name="password">
<input type="checkbox" checked="checked" id="keep" value="yes">
<label for="keep">Keep login</label>
<input type="submit" value="Sign in">
</form>
<div class="division" style="display: none">Please fill in an email and password</div>
</body>
</html>

In your input element, you have onClick="return false;"This onClick function is being given priority over the click handler that you defined in jQuery. If you remove the onClick portion of your input element, your jQuery code will run.
Aside, there is a problem with your submit code in that it never actually prevents the POST to the server. See my edit below:
if( email == "" || password == "") {
$('.division').show();
return false;
}else{
('#form').submit();
}
You must explicitly return false to prevent the form from submitting to the server. Alternatively, you can just remove the else clause altogether, due to the fact that if the function doesn't explicitly return false, it will complete and continue with the form submission.
Also note that for form submissions, it is typically better to use the onSubmit event as opposed to the onClick event, since forms can technically be submitted by hitting the 'enter' key as well as clicking the submit button. When onClick is used, the submission is not triggered via hitting the enter key.

Related

Why's my form action still being triggered when validating the form despite using e.preventDefault()?

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>

validate simple html form with JavaScript

Simple html form with some JavaScript code to check if user name is empty and then display error message otherwise submit the form.
First part works fine when the user name is empty.
Second part does not work once I click the submit button when the user name is not empty.
What is wrong with the code and how can I submit the form correctly?
let userName = document.getElementById('uname');
let form =
document.querySelector('#myForm');
form.addEventListener('submit',function(e){
e.preventDefault();
if(userName.value === ''){
alert('user name is required');
}
});
<form method="get" id="myForm">
<div>
<input type="text" class="form-control" id="uname" name="uname">
</div>
<button type="submit" name="submit">send</button>
</form>
That is because of using preventDefault. You are calling e.preventDefault(); even there is no error while you just need to call the function when form is not valid.
So put e.preventDefault(); in if part
let userName = document.getElementById('uname');
let form =
document.querySelector('#myForm');
form.addEventListener('submit',function(e){
if(userName.value === ''){
alert('user name is required');
e.preventDefault();
}
});
<form method="get" id="myForm">
<div>
<input type="text" class="form-control" id="uname" name="uname">
</div>
<button type="submit" name="submit">send</button>
</form>
You need to conditionally call the e.preventDefault() so that it doesn't prevent the submit behaviour of the form.
You only need to prevent the form submit behaviour while showing the alert box.
preventDefault() will tell the browser to avoid the default action of the form (submit action)
Move preventDefault in the condition where the username is empty:
let userName = document.getElementById('uname');
let form =
document.querySelector('#myForm');
form.addEventListener('submit',function(e){
if(userName.value === ''){
alert('user name is required');
e.preventDefault();
}
});
<form method="get" id="myForm">
<div>
<input type="text" class="form-control" id="uname" name="uname">
</div>
<button type="submit" name="submit">send</button>
</form>

Form message validation using onsubmit function?

I'm making some message validation with javascript using setCustomValidity() method. So when I attach onsubmit in my form it won't display message in input field but when I use onclick it dispay message.I understand difference between onlclick and IonsubmitI function. But why message is not displayed when I use onsubmit function?
For example.
<form id="myForm" onsubmit="subForm">
<input type="email" name="email" id="email" required>
<input type="submit" name="subit" id="submit">
</form>
<script type="text/javascript">
var mail = document.getElementById("email");
function subForm() {
if (mail.value == "") {
mail.setCustomValidity("Your input field is empty!");
}
}
</script>

How to check if textbox is empty and display a popup message if it is using jquery?

I'm trying to check if the textbox is empty for my form. However, whenever I try to hit submit instead of an alert box message, telling me Firstname is empty I get "Please fill out filled".
('#submit').click(function() {
if ($('#firstname').val() == '') {
alert('Firstname is empty');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="elem" autocomplete="on">
First Name:
<br>
<input type="text" name="firstname" id="firstname" required placeholder="Enter the first name" pattern="[A-Za-z\-]+" maxlength="25"><br>
<input type="submit" id="submit" value="Submit" />
</form>
Firstly I'm assuming that the missing $ is just a typo in the question, as you state that you see the validation message appear.
The reason you're seeing the 'Please fill out this field' notification is because you've used the required attribute on the field. If you want to validate the form manually then remove that attribute. You will also need to hook to the submit event of the form, not the click of the button and prevent the form submission if the validation fails, something like this:
$('#elem').submit(function(e) {
if ($('#firstname').val().trim() == '') {
e.preventDefault();
alert('Firstname is empty');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="elem" autocomplete="on">
First Name:
<br>
<input type="text" name="firstname" id="firstname" placeholder="Enter the first name" pattern="[A-Za-z\-]+" maxlength="25"><br>
<input type="submit" id="submit" value="Submit" />
</form>
Personally I'd suggest you use the required attribute as it saves all of the above needless JS code - unless you need more complex logic than just checking all required fields have been given values.
Because you have the required property set.It is giving you Please fill out field validation as the error message.It is the validation that HTML5 is performing.
For this please make one function like :
function Checktext()
{
if ($('#firstname').val() == '') {
alert('Firstname is empty');
return false;
}
else
{
return true;
}
}
now call this function on submit button click like :
<input type="submit" id="submit" value="Submit" onclick="return check();" />

JS validation false, form still submitting

I've got a JS problem. My validation seems to be working, checking that the user inputs a valid number which isn't zero, but the form is still submitting. I have seen this question asked many times but I can't find a solution that works for me. Any ideas would be great.
My Javascript
function checkNotZero()
{
var theNumber = document.getElementById("theNumber").value;
var str = /^\+?[1-9]\d*$/.test(theNumber);
if ( str == false ) {
alert('You have not entered a valid number');
return false;
} else {
document.getElementById('numberCheck').submit();
}
}
My HTML
<form action="/next.php" method="post" id="numberCheck">
<input type="text" id="theNumber" value="0">
<button id="submitButton" OnClick="checkNotZero();">Add to Basket</button>
</form>
Use an <input type="submit"> for the submit button.
Validate on the form's submit event rather than some onclick. Forms can get submitted in other ways than just clicking a button (for instance, pressing "enter", or procedurally through code).
Prefer .addEventListener to attributes for attaching events to elements. Use preventDefault() to prevent form submission.
Hi for the above requirement of 'validating form' java script validation should be done
when the form gets submitted. follow the below approach, form will not get submitted
until and unless the validation is correct.
<html>
<head>
<script type="text/javascript">
function checkNotZero()
{
var theNumber = document.getElementById("theNumber").value;
var str = /^\+?[1-9]\d*$/.test(theNumber);
if ( str == false ) {
alert('in');
alert('You have not entered a valid number');
return false;
} else {
document.getElementById('numberCheck').submit();
}
}
</script>
</head>
<body>
<form action="/next.php" method="post" id="numberCheck" onsubmit="return
checkNotZero()">
<input type="text" id="theNumber" value="0">
<button id="submitButton">Add to Basket</button>
</form>
</body>
</html>
the only change is <form action="/next.php" method="post" id="numberCheck"
onsubmit="return checkNotZero()">
do not use onclick event in submit button.

Categories