Home > Net >  Call jQuery function from HTML
Call jQuery function from HTML

Time:07-30

I have this code and I am trying do call a function, but it doesn't work. Can anyone tell me what I need to do to fix this?

$(document).ready(function() {
  function BoxMsg(mess) {
    $.MessageBox(mess);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<input id="rxc021" name="rxc021" type="button"  value="Ask" onclick="BoxMsg('rxc021 - option 1')">
<input id="rxc022" name="rxc022" type="button"  value="Ask" onclick="BoxMsg('rxc022 - option 2')">
<input id="rxc023" name="rxc023" type="button"  value="Ask" onclick="BoxMsg('rxc023 - option 3')">
<input id="rxc024" name="rxc024" type="button"  value="Ask" onclick="BoxMsg('rxc024 - option 4')">

CodePudding user response:

For functions referenced by onclick attributes they need to be placed in global scope. As your function is defined in document.ready, it's not in scope. To fix the problem, move your function definition:

function BoxMsg(mess) {
  $.MessageBox(mess);
}
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/messagebox.min.js"></script>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/messagebox.min.css" />
<input id="rxc021" name="rxc021" type="button"  value="Ask" onclick="BoxMsg('rxc021 - option 1')">
<input id="rxc022" name="rxc022" type="button"  value="Ask" onclick="BoxMsg('rxc022 - option 2')">
<input id="rxc023" name="rxc023" type="button"  value="Ask" onclick="BoxMsg('rxc023 - option 3')">
<input id="rxc024" name="rxc024" type="button"  value="Ask" onclick="BoxMsg('rxc024 - option 4')">

Better still, do not use onclick. It's outdated and not good practice.

The better alternative is to use unobtrusive event handlers bound in your JS code, not the HTML. You can use data attributes to retrieve element metadata within these event handlers:

jQuery($ => {
  $('.e-btn').on('click', e => {
    let $btn = $(e.target);
    $.MessageBox($btn.data('message'));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/messagebox.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/messagebox.min.css" />
<input id="rxc021" name="rxc021" type="button"  value="Ask" data-message="rxc021 - option 1" />
<input id="rxc022" name="rxc022" type="button"  value="Ask" data-message="rxc022 - option 2" />
<input id="rxc023" name="rxc023" type="button"  value="Ask" data-message="rxc023 - option 3" />
<input id="rxc024" name="rxc024" type="button"  value="Ask" data-message="rxc024 - option 4" />

  • Related