Reputation: 2672
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:
$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.$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.
Upvotes: 1
Views: 8493
Reputation: 1006
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/
Upvotes: 3
Reputation: 3034
I believe you are asking specifically on initial page load. Use jQuery:
$(document).ready(function() {
if ($('#query').val() !== '') {
$('#search-form').submit();
}
});
Upvotes: 3
Reputation: 488
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();
}
}
});
});
Upvotes: 1
Reputation: 61
<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>
Upvotes: 2