Reputation: 9225
I have the following code:
<form method="post" action="http://www.mypage.com/search.aspx" id="aspnetForm">
<input name="ctl00$centerContent$txtSearchPhysician" id="ctl00_centerContent_txtSearchPhysician" type="text" size="25" />
<input name="ctl00$centerContent$btnPhysicianSearch" id="ctl00_centerContent_btnPhysicianSearch" type=button value="Search" />
</form>
<script>
$(document).ready(function(){
jQuery('input[id="ctl00_centerContent_txtSearchPhysician"]').keyup(function() {
var raw_text = jQuery(this).val();
var return_text = raw_text.replace(/[^a-zA-Z]/g,'');
jQuery(this).val(return_text);
});
jQuery('input[id="ctl00_centerContent_txtSearchPhysician"]').keydown(function(e) {
jQuery(this).css('background-color', '#FFFFFF');
});
jQuery('input[id="ctl00_centerContent_btnPhysicianSearch"]').click(function() {
var raw_text = jQuery('input[id="ctl00_centerContent_txtSearchPhysician"]').val();
if (!raw_text) {
alert ('Search Query is Blank');
jQuery('input[id="ctl00_centerContent_txtSearchPhysician"]').css('background-color', '#FF3333');
jQuery('input[id="ctl00_centerContent_txtSearchPhysician"]').focus();
}
if (raw_text) {
//alert (raw_text); //displays the search string
//document.location.href="http://www.google.com"; //redirects to google.com
window.document.cookie='postbackcookie=';
window.document.location.href="http://www.mypage.com?searchtext=" + raw_text;
}
});
});
</script>
Almost everything is working fine except one thing. If the textbox has the focus and I hit enter without entering anything it just reloads the "action" page.
How do I modify the code so, when the above happens, The textbox background turns red and the enter is nulled. The only time enter will work in the textbox is if there is a string already there?
Upvotes: 0
Views: 677
Reputation: 762
add this to the input: required
<input name="ctl00$centerContent$btnPhysicianSearch" id="ctl00_centerContent_btnPhysicianSearch" type=button value="Search" required/>
Upvotes: 1
Reputation: 95022
Intercept the submit event and validate the form before allowing the submit to take place.
$("#aspnetForm").on("submit",function(e){
e.preventDefault();
if ( $("#someinput").val() != "" ) {
this.submit(); // this doesn't trigger another submit event
}
})
By doing it this way, it would be easy to later add more validation as needed.
Upvotes: 3