Unable to submit form even when input is not empty - javascript

So I'm working on a simple form where I'm checking if the input is empty. If it is then it should stop the form submission but if its not then it will go ahead and submit the form.
Right now, when the input field is empty and I press the submit button, the error message is displayed. But if I type something on the input field and try to submit, the code inside the if block triggers again and the form doesn't submit.
Why would the code inside the if block trigger again when the input is not empty? Wouldn't it just skip the if statement altogether and submit the form?
Here's the code:
HTML
<div class="name-search" >
<form action="/send" method="POST" >
<input class="search_input" name="name" type="text">
<button type="submit" class="search_icon"><i class="fas fa-search"></i></button>
<p class="error-msg"></p>
</form>
</div>
JS
const form = $( '.name-search form' );
const formInputVal = $( '.name-search form .search_input' ).val();
const formErrorMsg = $( '.name-search form .error-msg' );
$( form ).submit( ( e ) => {
if ( formInputVal === '' ) {
$( formErrorMsg ).text( 'Input field can\'t be empty.' );
return false;
}
return true;
});

When you put the value in a variable, that's it, you do it once, the variable doesn't change when the value does, so instead, you need to get the value everytime:
const form = $( '.name-search form' );
const formInput = $( '.name-search form .search_input' );
const formErrorMsg = $( '.name-search form .error-msg' );
$( form ).submit( ( e ) => {
if ( formInput.val() === '' ) {
$( formErrorMsg ).text( 'Input field can\'t be empty.' );
return false;
}
return true;
});

Related

jQuery: delay disable button onclick after the form submission?

So right now I have this:
HTML:
<input type="submit" class="usp-submit usp-submit-default" onclick="return change(this); " id="btnSubmit" />
jQuery:
function change( el )
{
if ( el.value === "Send" )
el.value = "Sending";
else
el.value = "Please wait...";
$("#btnSubmit").attr("disabled", true);
}
This does disable the input button and change the value to "Please wait", but the form is not submitted.
I assume this disables the button in the first place and doesn't perform the send action.
I have read somewhere that you can add a delay before .attr("disabled", true) for a few milliseconds so that the form would be submitted first.
Any help from jQuery experts would be appreciated.
Thanks.
If you want to delay, you can use the vanilla js way, setTimeout()
function change( el )
{
if ( el.value === "Send" )
el.value = "Sending";
else
el.value = "Please wait...";
setTimeout( () => $("#btnSubmit").prop("disabled", true) , 0);
}

How to automatically submit form if input field value exists?

I have the following form on my site. It's simple, one search input field and one submit button:
<form id="search-form" name="search-form" onsubmit="return search()">
<input type="search" id="query" class="search-field" value="<?php echo $searchQuery;?>">
<input type="submit" name="search-btn" id="search-btn" value="">
</form>
As you can see, in the search field (id=query) I have a php which sometimes inserts value into his field.
What I want to do is following:
If $searchQuery doesn't exist (or in other words, if value of search
field id=query is empty, allow user to click on the search button
manually.
If $searchQuery exist, auto submit the the form (simulate click on
the search button.
Any solution will help, JavaScript, jQuery or in PHP. I just need to figure out how to auto submit this form when PHP variable $searchQuery exists.
I believe you are asking specifically on initial page load. Use jQuery:
$(document).ready(function() {
if ($('#query').val() !== '') {
$('#search-form').submit();
}
});
You would need to just look to see if the value is populated and submit the form if it is.
jQuery Version:
$( function() {
if ( $( '#query' ).val() !== '' ) {
$( '#search-form' ).submit();
}
});
Fiddle: https://jsfiddle.net/fe9m8pk3/
Javascript Version:
function ready( fn ) {
if ( document.attachEvent ? document.readyState === 'complete' : document.readyState !== 'loading' ) {
fn();
} else {
document.addEventListener( 'DOMContentLoaded', fn );
}
}
ready( function() {
if ( document.getElementById( 'query' ).value != '' ) {
document.getElementById( 'search-form' ).submit();
}
});
Fiddle: https://jsfiddle.net/qeo25yu1/
<script type="javascript/text">
var query = document.getElementById('query');
if(query.value != ''){
//do your submit
}
function yoursubmitfunctionname(){
//do your submit
}
query.addEventListener('change',yoursubmitfunctionname);
</script>
This code will submit form if character length minimum fullfiled using Jquery:
$(document).ready(function ()
{
var minimum_character = 7;
$('#query').on('propertychange input', function (e)
{
var valueChanged = false;
if(e.type=='propertychange')
{
valueChanged = e.originalEvent.propertyName=='value';
}
else
{
valueChanged = true;
}
if(valueChanged)
{
str_length = $('#query').val().length;
if(str_length == minimum_character)
{
$("#search-form").submit();
}
}
});
});

How to customize validation message position in login validation?

<input type="text" class="form-control"
name="username" placeholder="Enter ID" required
oninvalid="this.setCustomValidity('Enter ID')"
oninput="setCustomValidity('')" />
How to customize the Validation message position to the right of the textbox? Now it's coming below the textbox.
Plunker link: http://plnkr.co/edit/vvfR5pelzeJAMM5LagC9?p=preview
Using of positions to the element for parent element use relative and use position absolute for tooltip. If possible show your demo code.
Here is an example with jQuery dependent script.
<div>
<label for="name">Name:</label>
<input id="name" type="text" required>
</div>
<div>
<label for="comments">Comments:</label>
<textarea id="comments" required></textarea>
</div>
<div class="buttons">
<button>Submit</button>
</div>
</form>​
<script>
var createAllErrors = function() {
var form = $( this ),
errorList = $( "ul.errorMessages", form );
var showAllErrorMessages = function() {
errorList.empty();
// Find all invalid fields within the form.
var invalidFields = form.find( ":invalid" ).each( function( index, node ) {
// Find the field's corresponding label
var label = $( "label[for=" + node.id + "] "),
// Opera incorrectly does not fill the validationMessage property.
message = node.validationMessage || 'Invalid value.';
errorList
.show()
.append( "<li><span>" + label.html() + "</span> " + message + "</li>" );
});
};
// Support Safari
form.on( "submit", function( event ) {
if ( this.checkValidity && !this.checkValidity() ) {
$( this ).find( ":invalid" ).first().focus();
event.preventDefault();
}
});
$( "input[type=submit], button:not([type=button])", form )
.on( "click", showAllErrorMessages);
$( "input", form ).on( "keypress", function( event ) {
var type = $( this ).attr( "type" );
if ( /date|email|month|number|search|tel|text|time|url|week/.test ( type )
&& event.keyCode == 13 ) {
showAllErrorMessages();
}
});
};
$( "form" ).each( createAllErrors );
</script>
You can customize the validation message position by adding this CSS code.
.form-control[required] {
margin-top: 40px !important;
margin-left: 100px !important;
}

alert box not stopping execution/submission of the form

This is a code snippet I'm using. Here as per my expectation, code execution doesn't stop and the form gets submitted. Though alert box appears but after pressing "ok" the form get submitted.
$('.qto').each(function(index) {
if (jQuery.inArray($("#quota-" + (index + 1)).val(), quoatas) != -1) {
alert("Please check the different values you have entered");
return false;
}
quoatas.push($("#quota-" + (index + 1)).val());
});
The issue is because your return false is relevant to the anonymous function it's contained in, not the submit handler of the form (which I'm presuming this code is contained within). As a workaround, you can use the preventDefault() method of the event which is passed to the submit handler. Try this:
$('#myForm').submit(function(e) {
$('.qto').each(function(index) {
if ($.inArray($("#quota-" + (index + 1)).val(), quoatas) != -1) {
e.preventDefault(); // stop the form submission
alert("Please check the different values you have entered");
}
quoatas.push($("#quota-" + (index + 1)).val());
});
});
you can use preventDefault() to stop form submission
You can simply use event handler which is bound to the form like this,
<!doctype html>
<html>
<head>
<title>Form Submit Handler</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Enter 'demo' as valid data: </p>
<form id="formId" action="javascript:alert( 'Value Valid. Form submitted.' );">
<div>
<input id="firstName" type="text">
<input type="submit" value="Check">
</div>
</form>
<p id="response" style="color:red;"></p>
<script>
$( "#formId" ).submit(function( event ) {
if ( $( "#firstName" ).val() === "demo" ) {
$( "#response" ).empty();
$( "#response" ).text( "Submitted." ).show();
return;
}
$( "#response" ).empty();
$( "#response" ).append( "Not submitted." );
event.preventDefault();
});
</script>
</body>
</html>

Why is this validation code not working?

I looked over my code and changed it and everything looks alright I just dont understand why it is not working! When I open it in my browser and enter a phone number and press the button nothing happens. It does not alert me like I want it to.
<html>
<head>
<title>Phone Number Validation</title>
</head>
<body>
<script language="javascript">
window.onload=function(){
document.getElementById("valButton".onclick=validateIt;
}
function validateIt(){
var phoneno = /^\d{10}$/;
if((inputtxt.value.match(phoneno))
{
alert("Yay it's a phone number!");
return true;
}
else
{
alert("Not a valid number");
return false;
}
}
</script>
<p>Phone Number Validation:</p>
<p>Enter a phone number here:<br>
<input type="text" size=30 id="phoneno" /><br>
<input type="button" value="Validate" id="valButton" />
</p>
</body>
</html
Add an "onblur=phonenumber()" to your input, to trigger calling the function when control leaves the input (click or tab away).
Issues:
1- The function is never called
2- The function has a syntax error
function phonenumber(inputtxt) {
var pattern = "/^\d{10}$/",
phoneno = new RegExp(pattern);
if (inputtxt) {
if(inputtxt.match(phoneno)) {
return true;
} else {
alert("message");
return false;
}
}
}
//Using jQuery for DOM manipulation you can execute the function on validate button click
$('#valButton').on('click', function () {
var phoneInputValue = $('#phoneno').val();
phonenumber(phoneInputValue);
});
Checkout fixed code here:
https://jsfiddle.net/au7aft0k/2/
The function you have written never gets executed. You need to add an event handler onto the button and/or the input itself. The easiest way to do so is after the DOMContentLoaded event fires (DOM has been parsed).
var btn = document.getElementById( 'valButton' );
btn.addEventListener( 'DOMContentLoaded', function(){
var txt = document.getElementById( 'phoneno' ).value;
if ( phonenumber( txt ) ) {
alert( 'Test passed. Do stuff here' );
} else {
alert( 'Test failed!!' );
}
}, false );
Similarly if you want to automatically check after the person leaves the input field you would use:
var input = document.getElementById( 'phoneno' );
input.addEventListener( 'blur', function(){
if ( phonenumber( input.value ) ) {
alert( 'Test passed. Do stuff here' );
} else {
alert( 'Test failed!!' );
}
}, false );

Categories