Check if input is empty on submit - javascript

I am trying to check whether or not the password field on a form has been filled in on submission on a form but it always returns as "undefined" so the code I'm trying to run when the form is submitted never runs.
The username field seems to work fine though.
Here's my code...
$("#form1").find("input[type=submit]").click( function() {
if($(".username").val() != "" && $(".password").val() != "") {
console.log("Success")
} else {
console.log("fail");
}
});

Something must be wrong with your html since it seems to work:
<form id="form1" method="post">
<input type="text" class="username">
<input type="text" class="password">
<input type="submit" value="Submit">
</form>
See live example here.
I have a feeling that you might be confusing classes that are selected with a "." with id's that are selected with a "#", but if I don't see your html, I'm just guessing.

Related

Problems with outputting error after submit empty fields

i have a problem with my script, the only problem is outputting error.
the error just bricks after submit_button. so that means when the fields are empty it has to output error and it works but the problem the output just bricks
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form method="post">
<input type="text" id="text_field1" />
<input type="text" id="text_field2">
<button type="submit" id="submit_button">Submit</button>
<button type="submit">Submit</button>
<p id="error_resp"></p>
</form>
<script>
$("#submit_button").click(function() {
if ($("#text_field1").val() == "")
$('#error_resp').text('please fill the required field');
else if ($("#text_field2").val() == "")
$('#error_resp').text('please fill the required field');
else
return true;
});
</script>
There are few issues in your form HTML.
You are not using preventDefault() method which will prevent the default behavior of a form so the inout can be validated.
Also, you do not need check empty input like == "" You can just ! to say if my input is empty then show error message
You are displaying errors in error_resp ideally use .html to clear the previous message and replace with new message
You can read more about .html here
Run snippet to below to see it working.
$("#submit_button").click(function(e) {
e.preventDefault();
if (!$("#text_field1").val()) {
$('#error_resp').html('please fill the first required field');
} else if (!$("#text_field2").val()) {
$('#error_resp').html('please fill the second required field');
} else {
$('#myForm').submit();
console.log('All looking good. Form will submit now')
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="myForm" action="filename.php">
<input type="text" id="text_field1" />
<input type="text" id="text_field2">
<button type="submit" id="submit_button">Submit</button>
<p id="error_resp"></p>
</form>

Check Required Fields With preventDefault

I ran into a situation where I have a HTML form and it has required on many of the fields. The issue is I have to use preventDefault which ignores 'required' inputs and submits the form even without the required fields. Because the work is not entirely up to me I must use preventDefault and work around it.
I am working with jQuery and I am trying to find a way to target the fields that have required and prevent the form from submitting on click.It is important that the required fields are filled out on the form before a user can submit the form as I do not want required information missing when it is being submitted. Help is appreciated!
HTML
<form id="myForm">
<input type="text" name="sentence1" id="st1" placeholder="Text here" required>
<input type="text" name="sentence1" id="st2" placeholder="Text here" required>
<input type="text" name="sentence1" id="st3" placeholder="Text here" required>
<input type="text" name="sentence1" id="st4" placeholder="Text here" required>
<input type="text" name="sentence1" id="st5" placeholder="This field is not required">
<button type="submit" id="submit-form">Submit</button>
</form>
Came across the same problem and here is the solution that works for me.
Form elements have a function called checkValidity and reportValidity. We can use these and override the click event for the submit button.
$('#submit-form').click((event) => {
let isFormValid = $('#myForm').checkValidity();
if(!isFormValid) {
$('#myForm').reportValidity();
} else {
event.preventDefault();
... do something ...
}
});
In your event handler, where you are using preventDefault(), add the checkValidity() method on the form element:
document.getElementById('myForm').checkValidity();
This will "statically" check your form for all HTML5 constraint violations (including required),
Just a quick solution for your problem. I hope this is what you need. Check below:
$('#submit-form').click(function(){
event.preventDefault();
if(validateForm()){
alert('sending');
}
});
function validateForm() {
var isValid = true;
$('input[type=text]').each(function() {
if ( $(this).val() === '' ) {
alert('validation failed');
isValid = false;
}
});
return isValid;
}
Or visit JSFiddle: enter link description here
You can use preventDefault() in forms submit method. Then 'required' will work.
document.querySelector('form').addEventListener('submit', submitHandler);
function submitHandler(e){
e.preventDefault();
//your code here
}

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();" />

Javascript form validation - PHP variable as VALUE - Invalid Input

I have an issue where I am validating form submission with javascript. The form is prefilled with results from the database as PHP values like this:
<form name="profiledit" action="profile_edited.php" method="POST" >
<h3>Name:</h3>
<input type="text" id="teamname" name="teamname"
value="<?php echo $result['teamname'];?>">
</form>
This is the javascript:
<script type="text/javascript">
function empty() {
tn = document.getElementById("teamname").value;
if (! /^[a-zA-Z0-9]+$/.test(tn)) {
alert("Please enter a valid Team Name");
return false;
}
}
</script>
The submit button is :
onClick="return empty();"
The problem is that is always tells me top "Please enter a valid Team Name" unless I retype the text in the box (that was supplied by the PHP value).
I cannot see any weird spaces or things in "view source".
What could the problem be?
Thanks.
EDIT1 : Sorry I forgot to paste closing brace. It was there in the code and this does work for BLANK forms OK. Just not when it has a prefilled value from PHP.
Try this
Check this link
Html
<form name="profiledit" action="" method="POST" id="profiledit">
<h3>Name:</h3>
<input type="text" id="teamname" name="teamname" value=""/>
<input type="button" id="submit" value="submit" name="submit" />
<input type="submit" id="submitform" value="submitform" name="submit" style="display:none;" />
</form>
Jquery
$('#submit').click(function(){
var pattern=/^[a-zA-Z0-9]*$/;
var tn = $("#teamname").val();
if(tn == "" && pattern.test(tn)){
alert('1');
}else {
//alert('2');
$('#submitform').trigger('click');
}
});
Hope its helps
Well, there was nothing wrong with the responses after all. My code was good and you guys code was good as well.
The problem?
Well I just happened to be testing with a teamname that had a SPACE in it!!!!!!!!!!
So having finally worked out that was the problem all along I would like to thank you all for your inputs.
I have used the regex instead : /^\w+( \w+)*$/
Allows words, numbers and a space.

cancel in confirm function submitting form in javascript

Got a form that requires users to input an amount to donate. On clicking submit, a function is called and the function is meant to display the amount specified and prompt the user to confirm if the amount typed is the actual amount or not.
The Cancel option in the Confirm() keeps submitting the form instead of returning false.
function donationFormSend(){
get_donation_amount = document.getElementById("get_donation_amt").value;
if(get_donation_amount != ''){
return confirm("You have specified "+get_donation_amount+" as the amount you wish to donate. \n\n Are you sure you want to proceed with the donation?");
}
else{
alert("Amount must be specified to process your donation.");
return false;
}
}
<form method="post" action="">
<div>
<div>Donation Amount:</div>
<input name="amount" type="text" id="get_donation_amt" required="required" />
</div>
<input name="donation_submit" type="submit" id="Submit" value="Proceed" onclick="return donationFormSend();" />
</form>
Jsfiddle link
Would be pleased getting help with this.
I updated your jsfiddle so it's in the expected format (loading the js in the head) and returning the confirm result
return confirm('blah blah')
works perfectly well for me in FF! Just make sure you clear your cache and reload your page.
A way to do do it might be:
form :
<form id='test' method="post" action="">
<div>
<div>Donation Amount:</div>
<input name="amount" type="text" id="get_donation_amt" required="required" />
</div>
<input type="submit" value="submit" onClick="form_submit(this.value)">
<input type="submit" value="cancel" onClick="form_submit(this.value)">
</form>
javascript:
document.getElementById('test').addEventListener('submit',function (event) {
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
})
form_submit= function (submited_by) {
if(submited_by == 'submit'){
alert('Submited')
}else if (submited_by == 'cancel'){
alert('cancelled')
}
}
I'd rather use a switch statement to make it expandable in the future but this should work.
Also I'm using jquery mostly because I'm not sure how to stop default action without it.
here's a JSFiddle with the code running.
EDIT: Updated to not use Jquery.
EDIT: well, I feel stupid now, realised it wasn't cancel button in a submit form but in a confirmation form.
In your HTML use : onclick="return donationFormSend();"
In Your Javascript: return confirm("Are you sure ....blah blah blah")

Categories