James James - 6 months ago 10
Javascript Question

Javascript Hide Input Field based on Select change TEXT not VALUE

I have a drop down list (select) populated from SQL. This is dynamic so can change at any time. I need to hide an input field based on the selected items TEXT not its Value. Here is my current code:

<select name='addEventEventName' style="width:180px" id="addEventEventName" onchange="EventChanged(this)">

</select>
<script>
function EventChanged(changedEvent)
{
if (changedEvent.value == "val1" || changedEvent.value == "val2")
{ $("#jmtest").hide(); }
else
{ $("#jmtest").show(); }
}
</script>


This works perfectly now. But if "val1" and "val2" change in the future it will break.

I would like to use Sickness (val1) and Holiday (val2) instead. What do I need to change?

Answer
<script type="text/javascript">                    
function EventChanged(selectEl) 
                    {
  var text = selectEl.options[selectEl.selectedIndex].text;
  if (text == "Sickness" || text == "Holiday")
     { $("#jmtest").hide(); }
  else
     { $("#jmtest").show(); }
}
</script>

Is this it. I find it it usually bad practice to use Textual labels as the basis for any data decision. This breaks the MVC pattern.

Comments