alert box not stopping execution/submission of the form - javascript

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>

Related

Unable to submit form even when input is not empty

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;
});

Fire button click via JavaScript

I need to 'click' one button using JavaScript, when the user clicks another button.
In Chrome on Mac, the following works fine. However, in Safari on Mac, clicking the button simply reloads the current page, rather than triggering the expected behaviour.
JS
$( 'document' ).ready( function() {
var $myForm = $('#my-form');
$('#button-fake').on('click', function(){
console.log("FAKE CLICKED");
if ($myForm[0].checkValidity()){
console.log("FORM VALID");
$('#button-real').click();
console.log("FORM SUBMITTED");
}
});
});
HTML
<input type="submit" id="button-fake" value="Fake button" />
<input type="submit" id="button-real" value="Real button" />
PS: Not my idea, I just need to get it working.
You may need to add e.preventDefault();
var $myForm = $('#my-form');
$('#button-fake').on('click', function(e) {
e.preventDefault();
console.log("FAKE CLICKED");
if ($myForm[0].checkValidity()) {
console.log("FORM VALID");
$('#button-real').click();
console.log("FORM SUBMITTED");
}
});
$('#button-real').on('click', function(e) {
console.log('button-real clicked')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id='my-form'>
<input type='text' required>
<button type='submit' id='button-fake'>Submit</button>
<button type='button' id='button-real'>Real</button>
</form>
The button will trigger a form submit. The form submit will reload the page. To prevent this, call preventDefault().
$( 'document' ).ready( function() {
var $myForm = $('#my-form');
$('#button-fake').on('click', function(e){
e.preventDefault(); // <- This
console.log("FAKE CLICKED");
if ($myForm[0].checkValidity()){
console.log("FORM VALID");
$('#button-real').click();
console.log("FORM SUBMITTED");
}
});
});

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();
}
}
});
});

JQuery - Click Submit Button Get Form Value

I have the following function and all i am trying to do is get the value out of the form field.
$( ".searchbutton" ).click(function() {
var tc = $(this).closest("form input[name='searchbox']").val();
alert(tc);
return false;
});
The alert keeps telling me "Undefined". I have treid closest, parent, parents, find, etc. I don't know what im doing wrong. Im clicking the submit button and all i want in return is the value in the search box. Please help.
html
<form action="/index.php" method="get" class="qsearch" >
<input type="text" id="fsearch" name="searchbox" >
<input class="searchbutton" type="submit" value="Submit">
</form>
Try this:
$( ".searchbutton" ).click(function() {
var tc = $(this).closest("form").find("input[name='searchbox']").val();
alert(tc);
return false;
});
Update
Yep, it work with your HTML - see here http://jsfiddle.net/qa6z3n1b/
As alternative - you must use
$( ".searchbutton" ).click(function() {
var tc = $(this).siblings("input[name='searchbox']").val();
alert(tc);
return false;
});
in your case. http://jsfiddle.net/qa6z3n1b/1/
Try easiest way:
<script>
$( ".searchbutton" ).click(function() {
var tc = $('#fsearch').val();
alert(tc);
return false;
});
</script>
How about just using $('input[name="searchbox"]') selector:
$( ".searchbutton" ).click(function() {
var tc = $('input[name="searchbox"]').val();
alert(tc);
return false;
});

How to create a javascript function that responds to a click or enter pressed?

I need the if bottom if statement to run if #nextQ is clicked (like it is currently) or if enter is pressed.
$('input[type=text]').on('keyup', function(e) {
if (e.which == 13) {
alert("enter is pressed");
return true;
}
});
$('#nextQ').click(function() {
//me.html validations
if (actual == 0 && document.URL.indexOf("me.html") >= 0){
loadNew();
}
});
If your input is wrapped in a form and that form has a submit button, it is submitted when you press enter inside the input.
Knowing this you should listen to the submit event:
The form:
<form class="myForm">
<input name="answer" type="text">
<button id="nextQ" type="submit">next Question</button>
</form>
JS:
jQuery( '.myForm' ).on( 'submit', function( event ) {
//me.html validations
if (actual == 0 && document.URL.indexOf("me.html") >= 0){
loadNew();
}
} );

Categories