RazorFinger RazorFinger - 5 months ago 9
HTML Question

I need to show and hide an object through javascript

I've searched thoroughly and read many of the questions on the same subject in here, however, none of them seemed to help with my issue.
I need to show a textbox for the user to inform the reason for impediment, but only when the option "Impeded" is selected in the combobox.
Here is my code:

<tr>
<td class="titulos">Status:</td>
</tr>
<tr>
<td>
<SELECT class=caixas id=cbostatus style="WIDTH: 3cm;" tabIndex=25 name=cbostatus onselect= "StatusTest();">
<option selected></option>
<option value "Opened">Opened</option>
<option value "Started">Started</option>
<option value "Not Concluded">Not Concluded</option>
<option value "Concluded">Concluded</option>
<option value "Impeded">Impeded</option>
</SELECT>
</td>
</tr>


And it is calling the JavaScript function "StatusTest", which reads like so:

if (document.getElementById('cbostatus').options[cbostatus.selectedIndex].value == "Impeded"){
// show
document.getElementById("ImpReason").style.display = 'block';
} else {
// hide
document.getElementById("ImpReason").style.display = 'none';
}


With "ImpReason" being the textbox that i want to hide or show. I got much of this code from here, however, it doesnt work. If there is anything wrong with the question please tell me, so i can ask it properly, since i really really need an answer.
Thanks!

Answer

You need and equals sign after your value attributes:

value="Opened"

You need to change onSelect to onChange

I also added a span tag with ImpReason because it wasn't included in the example.

Here is the jsfiddle showing it:

https://jsfiddle.net/hh4xy9v7/

<tr>
  <td class="titulos">Status:</td>
</tr>
<tr>
  <td>
  <select class="caixas" id="cbostatus" style="WIDTH: 3cm;" 
    tabIndex="25" name="cbostatus" onChange="StatusTest()">   
                            <option selected></option>
                            <option value="Opened">Opened</option>
                            <option value="Started">Started</option>
                            <option value="Not Concluded">Not Concluded</option>
                            <option value="Concluded">Concluded</option>
                            <option value="Impeded">Impeded</option>
                        </select>
                </td>
            </tr>   


<span id='ImpReason' style='display:none;'>This is the reason</span>

<script>
function StatusTest () {
    if (document.getElementById('cbostatus').value == "Impeded") {
        // show
        document.getElementById("ImpReason").style.display = 'block';
    } else {
        // hide
        document.getElementById("ImpReason").style.display = 'none';
    }
}
</script>