I have a web page with 2 sections, Search and Result. Each section has a button in it.
When the user focus on Search section and presses enter button, the search button should trigger.
Similarly, focusing on Result section and pressing enter button should trigger Save Changes button.
I tried the following code but, I am not getting the expected behavior. Any suggestion / guidance will be much appreciated.
function SetDefaultButton(parentContainer, button) {
$(document).off('keydown', parentContainer).
on('keydown', parentContainer, function (event) {
var eventTarget = event.target;
if (event.keyCode == 13) {
event.preventDefault();
$(button).trigger('click');
}
});
};
SetDefaultButton('#DivSearchSection', '#BtnSearch');
SetDefaultButton('#DivResultSection', '#BtnSave');
$('#BtnSearch').on('click', function(){
alert('Search is triggered');
});
$('#BtnSave').on('click', function(){
alert('Save is triggered');
});
#DivSearchSection
{
min-height:50px;
border:1px solid green;
background-color:lightgreen;
}
#DivResultSection
{
min-height:50px;
border:1px solid red;
background-color:yellow;
}
button{
margin-top:40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="DivContainer">
<div id="DivSearchSection">
This is search section.
<button type="button" id="BtnSearch">Search</button>
</div>
<div id="DivResultSection">
This is result section.
<button type="button" id="BtnSave">Save Changes</button>
</div>
</div>