I’m trying to make a check box to show/hide a HTML element, but I am trying to make it as efficient as possible (recycling one function and enabling it to evolve, rather than manually and statically writing unique functions).
I have already succeeded at this once, but in a slightly different scenario (included: “JavaScript Extract – Working Recycled Function”) but cannot get it to work in this new scenario (included: “JavaScript Extract – Not Working Recycled Function). I have scavenged what I can from it but I am having difficultly this time around. My brain has kinda ground to a halt after a couple of hours to solving other problems. I have multiple elements waiting to also use this, but for now I’m just trying to get it to work with the Google element first.
HTML Extract
<div id="googleContainer">
<input type="text" id="googleSearchBox" title="Google Search" class="searchBox" />
<input type="button" id="googleSearchButton" onClick="execSearchWithClick(this.id)" />
</div>
<input type="checkbox" id="googleCheck" checked="checked" onClick="setPref(this.id)"/>
JavaScript Extract – Working Recycled Function
var googleHome = "http://www.google.com/"; //Set home page
var googleSearchURL = googleHome + "search?q="; //Prime search URL
function execSearchWithClick(id){
alert(id) //Check ID
var searchBox = document.getElementById(id.replace("Button", "Box")); //Convert "googleSearchButton" to "googleSearchBox" to match target element
var searchQuery = searchBox.value; //Extract value from converted string-to-variable
if (searchQuery == ""){
if (id == "googleSearchButton") {
window.open(googleHome);
} //I would use "if(condition && condition)" rather than nested IFs here, but I plan to use ELSE IF very soon
} else {
if (id == "googleSearchButton") {
window.open(googleSearchURL + searchQuery);
}
}
}
JavaScript Extract – Not Working Recycled Function
var googleDisplay = true;
function setPref(id){
alert(id) //Check ID
var checkboxDisplayString = document.getElementById(id.replace("Check", "Display")); //Convert "googleCheck" to "googleDisplay" to match boolean variable
alert(checkboxDisplayString) //Null value reply
var checkboxDisplayVar = checkboxDisplayString //Convert (what I suspect to be) String to variable name
alert(checkboxDisplayVar) //Null value reply
if (id == "googleCheck" && checkboxDisplayVar == true){
checkboxDisplayVar = false;
applyPref();
} else {
checkboxDisplayVar = true;
applyPref();
}
}
function applyPref(){
if (googleDisplay == true){
document.getElementById("googleContainer").style.display = "block";
} else {
document.getElementById("googleContainer").style.display = "none";
}
}
EDIT: I’ve added much more detail for those who asked now. Sorry if everything has become more confusing.
This would be my attempt:
I may be missing something, but I think that something like the above should work