Samuel Gray Samuel Gray - 3 months ago 8
jQuery Question

How do I close the input if submit is clicked

So I've got a submit button with a class of search, when clicked and the value of the input with a class of searchBar is empty then searchBar display:block and doesn't submit the form. However i want to be able to close searchBar if the value is still empty but the submit (search) is clicked again.

$('#form').submit(function() {
if ($.trim($(".searchBar").val()) === "") {
$('.searchBar').css('display', 'block');
return false;
} else {
return true;
}
});


HTML:

<form id="form" action="">
<input value="" type="text" placeholder="Product name or ID" name="search" class="searchBar" />
<input type="submit" readonly="readonly" class="search" />
</form>


CSS:

#form .searchBar {
display: none;
}

Answer

If my understanding of question is correct, You can toggle the display of the searchbox to achieve what you need

 $('.searchBar').css('display', 'block'); // instead of this


 $('.searchBar').toggle(); // put this