I'm trying to keep my JS modular for easier readability and generalized, however I am having trouble getting the $(this) of the checkboxButton.on("click") to make define the variable checkboxSelected.
How do I make a global variable from within a function() (if that is the right way of putting it)?
var checkboxButton = $("[data-checkbox-id]"), checkboxContainer = checkboxButton.parent(); function checkboxRadio() { var checkboxSelected = $(this).attr("data-checkbox-id"); console.log(checkboxSelected); checkboxSelected.attr("aria-checked","true"); if (!$('[data-checkbox-id="' + checkboxSelected +'"]')) { checkboxButton.attr("aria-checked","false"); } } function checkboxInit() { console.log("Checkbox Initialised"); checkboxButton.on("touchend click", function(e) { e.preventDefault(); // Check the checkbox type if (checkboxContainer.attr("data-checkbox-type") == "radio") { checkboxRadio(); } else { // checkboxMultiple(); } }); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <fieldset data-checkbox-type="radio"> <label>Gender</label> <button class="checkbox-radio" value="male" name="male" aria-checked="true" data-checkbox-id="1"> <span class="icon-checkbox"></span> No </button> <button class="checkbox-radio" value="female" name="female" aria-checked="false" data-checkbox-id="2"> <span class="icon-checkbox"></span> Yes </button> </fieldset>
checkboxRadio.call(this).thiswhen you call the function: (1)checkboxRadio(this);(2)function checkboxRadio(btn) {(3)var checkboxSelected=$(btn).attr("data-checkbox-id");.attr("data-checkbox-type")I'd recommend using.data("checkbox-type").this, but are there more reasons?)