Arnell Vasquez C
Arnell Vasquez C

Reputation: 97

How to correctly execute a function JS with onclick?

I'm trying to execute a function by clicking on a span, but it tells me that it is undefined.

$(document).ready(function() {
  function callTo(param) {
    alert(param);
  }
});
.file-up {
  background: #f5f5f5 none repeat scroll 0 0;
  border: 1px solid #ccc;
  color: #383f45;
  font-size: 12px;
  margin-bottom: 10px;
  padding: 6px;
  font-size: 10px;
  text-align: center;
  text-transform: uppercase;
  cursor: pointer;
}
<div>
  <span class="file-up" onclick="callTo('test')">Click to call</span>
</div>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 0

Views: 64

Answers (2)

samar taj Shaikh
samar taj Shaikh

Reputation: 1185

<!DOCTYPE html>
<html>
<head>
    <title>
        sample
    </title>
</head>
<body>
    <script>
        function callTo(param) {
            alert(param);
        }
    </script>
    <div>
        <span class="file-up" id="index" onclick="callTo('test')">
            Click to call
        </span>
    </div>
</body>

This is a working example without using jQuery, just by vanilla javascript. Insert it and use it directly. If you want me to post an answer which uses only jQuery for the stated task that you want to accomplish then please let me know.

This is code using jQuery, as you asked -

<!DOCTYPE html>
<html>
<head>
    <title>
        sample
    </title>
</head>
<body>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
    $(document).ready(function() {
      $('#index').click (function callTo() {
        alert("Your values is :"+ $(this).data("value"));
      });
    });
</script>
<div>
    <span class="file-up" id="index" data-value="test">
        Click to call
    </span>
</div>

Upvotes: 1

Seva Kalashnikov
Seva Kalashnikov

Reputation: 4392

Try to move your function definition away from $(documents).ready

<script>
    function callTo(param) {
        alert(param);
    }
</script>

Or define event listener like

<script>
    $(document).ready(function() {
        $('.file-up').click(function() {
            //action
        });
    });
</script>

(I'd better give it an id in this case and change the selector to #id instead of .file-up because other elements can have the same class applied)

Upvotes: 1

Related Questions