简体   繁体   中英

Where am I wrong in this php code while working with select option?

I am working on a form in which I want to take select values and when user select yes value then I want to display a text box section, but following code is not working for me.

<select id="gap" name="gap" onclick="gap_textbox();">
    <option value='select'>Select</option>
    <option value='yes'>Yes</option>
    <option value='no'>No</option>
</select>

<input type="text" name="gap_box" id="gap_text_box" />

<script type="text/javascript">
    function gap_textbox() {
        alert ("am here" + "  " +document.getElementById("gap").value);
        if (document.getElementById("gap").value =='select') {
            alert ("in value = select");
            document.getElementById("gap_text_box").disable=true;
        }
        else if (document.getElementById("gap").value =='no') {
            alert ("in value = no");
            document.getElementById("gap_text_box").disable=true;
        } else {
            alert ("in value = yes");
            document.getElementById("gap_text_box").disable=false;
        }
    }
</script>

In the following line...

<select id="gap" name="gap" onclick="gap_textbox();">

...you need to use onchange instead of onclick .

However, using inline click handlers is considered old-fashioned and hard to maintain. You should be using proper JavaScript event handling...

document.getElementById("gap").onchange = function() {
    gap_textbox()
};

Or, better yet, use a library, such as jQuery...

$('#gap').change(function() {
    gap_textbox();
});

Try below code . Only change made is, replaced onclick function with onchange . For selection box you must use onChange function. We are not clicking anything in selection box.

<select id="gap" name="gap" onchange="gap_textbox();">
<option value='select'>Select</option>
<option value='yes'>Yes</option>
<option value='no'>No</option>
</select>
<input type="text" name="gap_box" id="gap_text_box" />
<script type="text/javascript">
function gap_textbox()
{
  alert ("am here" + "  " +document.getElementById("gap").value);
  if (document.getElementById("gap").value =='select') 
  {
    alert ("in value = select");
    document.getElementById("gap_text_box").disable=true;
  }
  else if (document.getElementById("gap").value =='no') 
  {
    alert ("in value = no");
    document.getElementById("gap_text_box").disable=true;
  }
  else 
  {
    alert ("in value = yes");
    document.getElementById("gap_text_box").disable=false;
  }
}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM