Consider the following script for checking if search form is empty. The id's of search buttons are: mainSearch and searchIcon
<script type="text/javascript">
$(document).ready(function() {
$('#mainSearch').click(function() {
if($("input[type=text][name=search]").val() == "" || $("input[type=text][name=search]").val() == 'Напишете търсената дума'
|| $("input[type=text][name=search]").val() == 'Enter search keywords here')
return false;
});
});
$(document).ready(function() {
$('#searchIcon').click(function() {
if($("input[type=text][name=q]").val() == "" )
return false;
});
});
</script>
HTMLscheme:
<div class="searchForm">
<form action="search.php" method="get">
<input type="text" name="search" id="searchForm" value="<?php if(checkBgLanguage()) echo 'Напишете търсената дума'; else echo 'Enter search keywords here'; ?>" autocomplete="off"
maxlength="35"/>
<a href="search.php"><img src="css/imgs/searchIcon.png" width="24" height="24" id="mainSearch"/></a>
</form></div>
For some reason the second function is working on every page. The first function works only on the home page. Another problem is pressing enter button; nobody should submit clear form with enter. Any help is greatly appreciated.
You should put both those functions into a single $(document).ready(){} block, as each block will slow down your page by binding the event respectively. You can also use the shorthand $(function(){});. From there, try event.preventDefault() instead of returning false:
$(function(){
$('#mainSearch').click(function(event) {
var val = $("input[type=text][name=search]").val();
if(val == "" || val == 'Напишете търсената дума'
||val == 'Enter search keywords here') {
event.preventDefault();
}
});
$('#searchIcon').click(function(event) {
var val = $("input[type=text][name=q]").val();
if(val == "" ) {
event.preventDefault();
}
});
});
You just need one $(document).ready(function() {
Try changing to this:
<script type="text/javascript">
var texts = [ 'Enter search keywords here'
,'Напишете търсената дума'];
$(document).ready(function() {
$('form').bind('submit', function(e) {
var errors = 0;
if('' === $("input[type=text][name=q]").val()) {
errors++;
}
$(texts).each(function(i,x) {
if(x === $("input[type=text][name=q]").val()) {
errors++;
};
)};
if(0 != errors) {
e.preventDefault();
return false;
}
});
});
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With