Sammy I. Sammy I. - 5 months ago 14
Javascript Question

How to make an HTML button trigger a Javascript function

The JSFiddle I am working with: https://jsfiddle.net/mL0uLx81/1/

I've been trying to trigger a function called

toggleCheckbox
on the click of a button.

I've tried it by doing
onclick="toggleCheckbox()"
on the
input
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

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

HTML

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

JavaScript

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')) {
    SurveyAppear();
  }  else {
    SurveyDisappear();
  }
}

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. https://jsfiddle.net/igor_9000/mL0uLx81/2/

Hope that helps!