chellareddy v
chellareddy v

Reputation: 29

ONFOCUS event alert calling multiple times

Hi Please find the below code and help to resolve the issue

<html>
<body>
<script
  src="https://code.jquery.com/jquery-3.6.0.js"
  integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
  crossorigin="anonymous"></script>
<script>
function fnAlertTitle(){
    var strTitleFlag =document.test.fname.value.trim();
    console.log("strTitleFlag::"+strTitleFlag);
    if (strTitleFlag == "") {
            alert("Please Select Fname");
            document.test.fname.focus();
            window.event.returnValue =false;
            return;
        }
}
$('body').on('keydown', 'input, select', function(e) {
    if (e.key === "Enter") {
        var self = $(this), form = self.parents('form:eq(0)'), focusable, next;
        focusable = form.find('input,a,select,button,textarea').filter(':visible');
        next = focusable.eq(focusable.index(this)+1);
        if (next.length) {
            next.focus();
        } else {
            form.submit();
        }
        return false;
    }
});
</script>
<h1>The input element</h1>
<form  name="test" action="">
  <label for="fname">First name:</label>
  <input type="text" id="fname" name="fname" tabindex="1"><br><br>
  <label for="lname">Last name:</label>
  <input type="text" id="lname" name="lname" tabindex="2" onFocus="javascript:fnAlertTitle();"><br><br>
  <input type="submit" value="Submit">
</form>
</body>
</html>

Pressing tab ONFOCUS event calling once but while pressing enter its calling multiple times please help to resolve the issue

Upvotes: 1

Views: 862

Answers (1)

sachinkondana
sachinkondana

Reputation: 681

You can remove onFocus="javascript:fnAlertTitle();" from HTML and make smaller changes to your code as bellow:

function fnAlertTitle(){
    ...
    if (strTitleFlag == "") {
        ...
        return true;
    }
}

$('body').on('keydown', 'input, select', function(e) {

   if (e.key === "Enter") {
    if(fnAlertTitle()) return;
    
    var self = ...
   }
});

Upvotes: 1

Related Questions