jjj jjj - 3 years ago 94
Javascript Question

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="">

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

  • 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.

Thanks for your help.

Answer Source

I believe you are asking specifically on initial page load. Use jQuery:

$(document).ready(function() {
   if ($('#query').val() !== '') {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download