jQuery: binding Function to text input on blur

581 views Asked by At

I know many related questions to this have been asked so far, but I could find none that really solve my problem.
I´ve got the same form as from my last question -

body {
  background-color: black;
}
.input-icon{
   float:left;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet"/>
<form class="w3-container w3-white">
  <div class="w3-row-padding">
    <div class="w3-col m12">
      
<p>
<i class="fa fa-envelope-o fa-2x fa-fw input-icon" aria-hidden="true"></i>
<input class="w3-input w3-animate-input" type="text" placeholder="E-Mail" style="width: 40%; max-width: 90% !important;">
</p>
    </div>
  </div>
</form>

And now want to bind a function to my textfield on blur via jQuery. This is what the new code looks like:

function myFunction(text) {
  alert(text);
}
$(document).ready(function() {
  $("#input").blur(myFunction("hello"));
});
body {
  background-color: black;
}

.input-icon {
  float: left;
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

<form class="w3-container w3-white">
  <div class="w3-row-padding">
    <div class="w3-col m12">

      <p>
        <i class="fa fa-envelope-o fa-2x fa-fw input-icon" aria-hidden="true"></i>
        <input class="w3-input w3-animate-input" type="text" placeholder="E-Mail" style="width: 40%; max-width: 90% !important;" id="input">
      </p>
    </div>
  </div>
</form>

You can see the problem pretty clearly - It executes myFunction() once and never again. I´ve heard that setting a Timeout before executing myFunction() in the .bind() would help, but that doesn´t really explain to me: WHY?
Thanks for all answers, as always, in advance,
- SearchingSolutions (yeah, searching solutions almost every day ;) )

1

There are 1 answers

0
jignesh patel On BEST ANSWER

Check this fiddle. Just removed external js you have included and changed blur function as

$('#lol').on('blur',function(){
    myFunction();
});

$('#lol').trigger('blur');