I am attempting to toggle the value of hidden inputs between true and false by users clicking on table cells. I am able to successfully assign event handlers to the cells, and get their values. My toggling function (true_switch
) appears to always return false, however, and I can't be sure if it actually switches the values.
I would love it if someone could tell me what I am doing wrong? I had previously tried this using Boolean data-type variables, but I gave up on that because I wasn't sure how HTML value fields, and JavaScript's Boolean datatypes interact (I seemed to be getting false a lot, even when I expected true).
JavaScript:
var JS_elements = document.getElementsByClassName("JS")
for (y = 0; y < JS_elements.length; y++){
x = JS_elements[y].getElementsByTagName("input")[0]
JS_elements[y].addEventListener('click', function() {
switch_JS(this);
});
}
function true_switch(val) {
document.getElementById("testblock").innerHTML += " ; true_switch worked "; <!-- debug line -->
if (val = "true") {
return "false"
} else if (val = "false") {
return "true"
} else {
alert("Error in the true_switch routine.")
}
}
function switch_JS(domobj) {
<!-- takes as input an HTML object, and switched the value from true to false, or from false to true -->
val = domobj.getElementsByTagName("input")[0].value
<!-- alert(val); -->
document.getElementById("testblock").innerHTML = document.getElementById("testblock").innerHTML + " | Step 1 worked; "; <!-- debug line -->
document.getElementById("testblock").innerHTML = document.getElementById("testblock").innerHTML +' ; val: ' + val + ' ; type: ' + typeof val + " ; true_switch(val): " + true_switch(val); <!-- debug line -->
domobj.getElementsByTagName("input")[0].value = true_switch(val);
document.getElementById("testblock").innerHTML = document.getElementById("testblock").innerHTML + " ; input value: " + domobj.getElementsByTagName("input")[0].value; <!-- debug line -->
}
HTML:
<header>
<hr>
<p>- Header Background Color Controller -</p>
<table>
<tr>
<td>Javascript Controller:</td>
<td class="JS">Red
<input type="hidden" value="true">
</td>
<td class="JS">Green
<input type="hidden" value="true">
</td>
<td class="JS">Blue
<input type="hidden" value="true">
</td>
</tr>
<tr>
<td>jQuery Controller:</td>
<td class="jQ" value=false>Red</td>
<td class="jQ" value=false>Green</td>
<td class="jQ" value=false>Blue</td>
<tr>
</table>
<hr>
</header>
The problem is this line:
You're doing an assignment, rather than a comparison. It should be:
(and then the same for the comparison with
"false"
)As an aside, a better way to perform debug logging is to use
console.log
and view the output in your browser's developer tools (usually F12 to open).