简体   繁体   中英

I have a windows onload function for onclick How can I add an onblur event and combine into one?

I need to have all javaScript external and I have window.onload = function

window.onload = function(){//onload allows external onclick
      document.getElementById('submit').onclick = function(evt) { 
       calcOrder();//validation of input(s)

} }//end window.onload = function()

this works when the submit button is clicked in the form, My question is I have an onBlur event also in the form how can I combine it into the window.onload = function ? Or can I?

<p><input name="fname" id="fname" type="text" size="20" maxlength ="15" placeholder="First Name" onblur="validateFirstname();"/>&nbsp;<span id ="fnameprompt"></span>
     <br>First name - Must be between 2 to 15 Characters </p>

You just need to add the following line inside the window.onload function

document.getElementById('fname').onblur = function(evt) { validateFirstname();

Here is an example

<html>
<body>

<script language="javascript">
window.onload = function(){
  document.getElementById('submit').onclick = function(evt) { calcOrder(); }
  document.getElementById('fname').onblur = function(evt) { validateFirstname(); }
}

function calcOrder() {
   alert('calcOrder');
}

function validateFirstname() {
   alert('validateFirstname');
}
</script>

<p><input name="fname" id="fname" type="text" size="20" maxlength ="15" placeholder="First Name"/>&nbsp;<span id ="fnameprompt"></span>
 <br>First name - Must be between 2 to 15 Characters </p>
  <input type="button" id="submit" name="submit" value="submit">
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM