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();
}
}
});
});
Related
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;
});
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 );
I have a simple form with hidden inputs and I'm trying to check whether each hidden input has a value. If all hidden inputs have a value than disable or enable the submit button. The inputs are being filled once the user clicks on an image via jquery. Ive tried multiple ways and it seems like I'm missing something....
<form method="post" action="test.php">
<div class="selections" id="accordion">
<h3>title<div class='status'>Pending</div></h3>
<div class='select-form'>
<div class='images'>
<img src='images/vote.jpg' data-value='data-value'>
<br/><span>title</span><br/>description
</div>
<input type='hidden' class='image-value' name='1' value=''>
</div>
<div class='select-form'>
<div class='images'>
<img src='images/vote.jpg' data-value='data-value2'>
<br/><span>title</span><br/>description
</div>
<input type='hidden' class='image-value2' name='2' value=''>
</div>
</div>
<input id="submit_button" type="submit" class="submit" value="SUBMIT">
</form>
the javascript goes as follows:
$( document ).ready(function() {
var $submit = $("input[type=submit]"),
$inputs = $('input[type=hidden]');
function checkEmpty() {
// filter over the empty inputs
return $inputs.filter(function() {
return !$.trim(this.value);
}).length === 0;
}
$inputs.on('blur', function() {
$submit.prop("disabled", !checkEmpty());
}).blur(); // trigger an initial blur
});
any ideas?
You could just call the checkEmpty() on img.click(), and from that function handle the disabled state.
Try it out here: JSFiddle (click the images)
$( document ).ready(function() {
var $submit = $("input[type=submit]"),
$inputs = $('input[type=hidden]');
function checkEmpty() {
var res = true;
$inputs.each( function(i,v){
if(v.value == ""){
res = false;
return false;
}
});
$submit.prop("disabled", !res);
}
$("img").click( function(){
$(this).parent().parent().find("input[type=hidden]").val("sdf");
checkEmpty();
});
checkEmpty(); //set disabled onload
});
Your trim function isn't behaving as you accept, remove it like here :
function checkEmpty() {
// filter over the empty inputs
return inputs.filter(function() {
return !(this.value);
}).length === 0;
}
Put this inside of the blur function to find out if all hidden inputs have a non empty value.
var empty=false;
$('input[type=hidden]').each(function(){
if($(this).val()==""){
empty=true;
}
});
if(empty){
//DISABLE SUBMIT
}
You're using $ in your JavaScript variables when you shouldn't be. Working fiddle: http://jsfiddle.net/keliix06/2f3cv2pk/
$( document ).ready(function() {
var submit = $("input[type=submit]"),
inputs = $('input[type=hidden]');
function checkEmpty() {
// filter over the empty inputs
return inputs.filter(function() {
return !$.trim(this.value);
}).length === 0;
}
inputs.on('blur', function() {
submit.prop("disabled", !checkEmpty());
}).blur(); // trigger an initial blur
});
How do I make a script in javascript to output an error and prevent form submission with empty fields in the form? Say the form name is "form" and the input name is "name". I have been having some trouble with PHP not always handling the empty fields correctly, so I would like this as a backup. Any help is appreciated, thanks.
HTML Code :-
<form name='form'>
<input type="button" onclick="runMyFunction()" value="Submit form">
</form>
Javascript Code :-
function runMyFunction()
{
if (document.getElementsByName("name")[0].value == "")
{
alert("Please enter value");
}
else
{
var form= document.getElementsByName("form")[0];
form.submit();
}
}
Claudio's answer is great. Here's a plain js option for you. Just says to do nothing if field is empty - and to submit if not.
If you need to validate more than one, just add an && operator in the if statement and add the same syntax for OtherFieldName
function checkForm(form1)
{
if (form1.elements['FieldName'].value == "")
{
alert("You didn't fill out FieldName - please do so before submitting");
return false;
}
else
{
form1.submit();
return false;
}
}
This is untested code but it demonstrates my method.
It will check any text field in 'form' for empty values, and cancel the submit action if there are any.
Of course, you will still have to check for empty fields in PHP for security reasons, but this should reduce the overhead of querying your server with empty fields.
window.onload = function (event) {
var form = document.getElementsByName('form')[0];
form.addEventListener('submit', function (event) {
var inputs = form.getElementsByTagName('input'), input, i;
for (i = 0; i < inputs.length; i += 1) {
input = inputs[i];
if (input.type === 'text' && input.value.trim() === '') {
event.preventDefault();
alert('You have empty fields remaining.');
return false;
}
}
}, false);
};
Attach an event handler to the submit event, check if a value is set (DEMO).
var form = document.getElementById('test');
if (!form.addEventListener) {
form.attachEvent("onsubmit", checkForm); //IE8 and below
}
else {
form.addEventListener("submit", checkForm, false);
}
function checkForm(e) {
if(form.elements['name'].value == "") {
e.preventDefault();
alert("Invalid name!");
}
}
i am using this javascript to disable my form submit button until a user has typed in the textarea field. once the textarea is populated the submit button is no longer disabled.
however, whilst this is working for a single text area i now want to find a way to make this work so that if i had four text input fields then to keep the submit button disabled until all of them are NOT empty/populated with text.
heres what im using at the moment:
<form action=\"includes/welcomestats.php\" method=\"post\" id=\"form1\" onSubmit=\"if (this.display_name.value == '') {return false;}\">
<input type=\"text\" name=\"display_name\" id=\"display_name\" maxlength=\"30\" placeholder=\"Display Name\">
<input type=\"submit\" class=\"welcome-submit2\" name=\"submit\" value=\"Next ->\" id=\"submit\"/>
</form>
<script>
$(function(){
$("#submit").submit(function(e){
if($("#display_name").val()==""))
{
e.preventDefault();
}
});
});
</script>
but now i am adding more text input fields to my form, so i need the script to keep my submit button disabled until all the text fields are populated, can anyone help me please?
i want to add these text fields to my form:
<input type=\"text\" name=\"public_email\" id=\"public_email\" maxlength=\"50\" placeholder=\"Email Address\">
<input type=\"text\" name=\"phone\" id=\"phone\" maxlength=\"30\" placeholder=\"Phone Number\">
<input type=\"text\" name=\"age\" id=\"age\" maxlength=\"2\" placeholder=\"Display Age\">
You could use .filter method to get all the empty input element, then check the length.
if ($('#form1 input').filter(function(){return $(this).val().length == 0;}).length > 0) {
e.preventDefault();
}
Try using:
<script>
$(function(){
$('form input').each(function(){
if($(this).is(':empty')){
$('form #submit').preventDefault();
}
});
});
</script>
Use this: http://jsfiddle.net/qKG5F/641/
<input type="submit" id="register" value="Register" disabled="disabled" />
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
} else {
$('#register').removeAttr('disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
}
});
})()
You'll need the OR operator - ||
So if display_name is empty OR public_email is empty etc...
$(function(){
$("#submit").submit(function(e){
if($("#display_name").val()=="" || $("#public_email").val()=="" || $("#phone").val()=="" || $("#age").val()=="")
{
e.preventDefault();
}
});
});
Give all of your text fields you want to include in this validation a class class="required" or something along those lines, then you can do this
var empty = $('.required').filter(function(){ return $(this).val() == "" }).length;
if(empty === 0){
//Enable your submit button all text fields have a value
}
Try this function:
function checkInputs(form) {
var inputs, all,
status = true;
if (form && form instanceof jQuery && form.length) {
inputs = form.find("input[type=text]");
all = inputs.length;
while (all--) {
if (!inputs[all].value) {
status = false;
break;
}
}
return status;
}
}
And demo here: http://jsbin.com/afukir/1/edit
EDIT: I've added instanceof to make sure that this function will only proceed if the form is actually a jQuery object.