简体   繁体   中英

Unable to call JS function from onclick event

I am trying to call a JavaScript function from the onclick event of two different buttons. I have dug around and searched for like problems but have not found a solutions. When I click either button I get the error

Error: 'RemoveCode' is undefined'

What am I doing wrong?

<script type="text/javascript">
    $(document).ready(function ()
    {
        function RemoveCode(codeType)
        {
            var selectedProjectsField = $("#SelectedProjects");
            var selectedProjectCodesField = $("#SelectedProjectCodes");
            var selectedTasksField = $("#SelectedTasks");
            var selectedTaskCodesField = $("#SelectedTaskCodes");
            var selectedOption;

            if (codeType = "Project")
            {
                selectedOption = $("#SelectedProjects :selected").index();
            }
            else
            {
                selectedOption = $("#SelectedTasks :selected").index();
            }

            alert(selectedOption);
        }

    });
</script>

Code for my buttons:

        <li>
            <label for="SelectedProjects">Selected Projects:</label>
            <select size="1" id="SelectedProjects" name="SelectedProjects" multiple></select> <button class="removeButton" onclick="RemoveCode('Project')" type="button">-</button>
        </li>

        <li>
            <label for="SelectedTasks">Selected Tasks:</label>
            <select size="1" multiple id="SelectedTasks" name="SelectedTasks"></select> <button class="removeButton" onclick="RemoveCode('Task')" type="button">-</button>
        </li>

I should note that on the same page there are multiple change events for the other elements on the page and they all work fine. It is just this `onclickP that is failing.

You are defining your RemoveCode method inside a closure. This function will thus not be available as onclick callbacks of your HTML elements. You can just update your code to this and it should work:

<script type="text/javascript">

function RemoveCode(codeType)
{
    var selectedProjectsField = $("#SelectedProjects");
    var selectedProjectCodesField = $("#SelectedProjectCodes");
    var selectedTasksField = $("#SelectedTasks");
    var selectedTaskCodesField = $("#SelectedTaskCodes");
    var selectedOption;

    if (codeType = "Project")
    {
        selectedOption = $("#SelectedProjects :selected").index();
    }
    else
    {
        selectedOption = $("#SelectedTasks :selected").index();
    }

    alert(selectedOption);
}

</script>

Firstly note that in your if condition you need to use == (not = ) to compare values.

To solve your issue you have two options. Firstly you could simply move the RemoveCode function out of the scope of the document.ready handler so that it can be accessed from the onclick attribute:

<script type="text/javascript">
    function RemoveCode(codeType)
    {
        // your code...
    }

    $(document).ready(function ()
    {
        // your code...
    });
</script>

Alternatively, it would be much better practice to add your event handlers using unobtrusive Javascript. As you're using jQuery, here's how you can do that:

$(function() {
  $('button').click(function() {
    var $selectedProjectsField = $("#SelectedProjects");
    var $selectedProjectCodesField = $("#SelectedProjectCodes");
    var $selectedTasksField = $("#SelectedTasks");
    var $selectedTaskCodesField = $("#SelectedTaskCodes");
    var selectedOption;

    if ($(this).data('codetype') == "Project") {
      selectedOption = $selectedProjectsField.find(':selected').index();
    } else {
      selectedOption = $selectedTasksField.find(':selected').index();
    }

    alert(selectedOption);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>
    <label for="SelectedProjects">Selected Projects:</label>
    <select size="1" id="SelectedProjects" name="SelectedProjects" multiple></select>
    <button class="removeButton" data-codetype="Project" type="button">-</button>
  </li>

  <li>
    <label for="SelectedTasks">Selected Tasks:</label>
    <select size="1" multiple id="SelectedTasks" name="SelectedTasks"></select>
    <button class="removeButton" data-codetype="Task" type="button">-</button>
  </li>
</ul>

You are defining your ready() method inside of a closure . You then have two approaches you can use. First is you can not use $(document).ready() as the buttons that call ready() can't be clicked until the document is ready anyway. Second is you could bind the onclick inside of your $(document).ready() .

$(document).ready(function() {
  $('#firstItem').click(function() { Ready('Project'); });
  ....
});

put your function out side of document.ready()

<script type="text/javascript">
    $(document).ready(function () // No Need of this Function here
    {   });
        function RemoveCode(codeType) // Automatically load when Your page is getting loaded on Browser.
        {
            var selectedProjectsField = $("#SelectedProjects");
            var selectedProjectCodesField = $("#SelectedProjectCodes");
            var selectedTasksField = $("#SelectedTasks");
            var selectedTaskCodesField = $("#SelectedTaskCodes");
            var selectedOption;

            if (codeType = "Project")
            {
                selectedOption = $("#SelectedProjects :selected").index();
            }
            else
            {
                selectedOption = $("#SelectedTasks :selected").index();
            }

            alert(selectedOption);
        }


</script>

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