So, I have some problem. I have a search bar to search for a product, and can also redirect to another page if I type a word is match with pageKeywords
array value. So in 1 searchbar there can be 2 triggers.
The first is when I click on search keywords and when it matches it will lead to another page:
$('#submitForm').on("click",function(e){
pageKeywords($("#searchKeywords").val(),e)
})
And will also direct to the result page if the word written does not contain pageKeyword
:
$('#submitForm').on('click', function () {
console.log("another function submit")
$('#fform').submit()
return false;
});
The problem I’m having is, when I click Search, it will trigger the form submit. How to prevent form submission when the words typed in the searchbar match with pageKeywords
? If it doesn’t match ,the form submit can run. These two events cannot be contested, here I give an example of the code that I have made
function pageKeywords(searchValue,evt){
const pageKeywords = {
"home": "/homepage",
"about": "/about-us"
}
const getInputVal = searchValue;
if(pageKeywords[getInputVal]) {
evt.preventDefault();
console.log(pageKeywords[getInputVal])
return false;
}else{
console.log('not found')
}
}
$(document).ready(function() {
$('#submitForm').on("click",function(e){
pageKeywords($("#searchKeywords").val(),e)
})
$('#submitForm').on('click', function () {
console.log("another function submit")
$('#fform').submit()
return false;
});
$("#searchKeywords").on("keypress", function(e) {
if (e.which === 13) {
pageKeywords($(this).val(),e)
}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="fform" action="#">
<input type="text" id="searchKeywords">
<button id="submitForm">Search</button>
</form>