Sammy I. Sammy I. - 1 year ago 83
Javascript Question

How to make an HTML button trigger a Javascript function

The JSFiddle I am working with:

I've been trying to trigger a function called

on the click of a button.

I've tried it by doing
on the
tag, and I've tried by adding
document.getElementById("surveyButton").addEventListener("click", toggleCheckbox, false);
to the JS file. Neither of them have worked, and I am unsure why.

Answer Source

You're pretty close, just a couple of fixes.

First, you're not including jQuery in your JS fiddle. Secondly, your toggleCheckbox function is not in the global scope, so it can't be accessed inline. Lastly, you'd need to update your appear/disappear functions. It seemed like they weren't toggling both the checkbox and the button in the same way.

Updated Code


<input type="checkbox" name="toggle" id="toggle" />
<input type="button" value="Open" id="surveyButton" /> <!--removed inline JS-->


function toggleCheckbox() { //moved function to global scope, if you wanted to add the listner inline you'd do it this way.

  if($("#toggle").is(':checked')) {
  }  else {

var SurveyAppear = function() {
  $("#surveyButton").prop('value', 'Open'); //switched from Close
  $("#toggle").prop('checked', false); //changed to false

var SurveyDisappear = function() {
  $("#surveyButton").prop('value', 'Close'); //switched from Open
  $("#toggle").prop('checked', true);

document.getElementById("surveyButton").addEventListener("click", toggleCheckbox, false);

See it working in the updated fiddle.

Hope that helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download