user3369276
user3369276

Reputation: 71

Displaying a textbox depending on selection from the select box

I have an application in which the user needs to enter Industry while filling out a form. We have several pre-made choices in the drop down box, but he also needs to enter manually. He can click on Other, and a input box should be displayed asking for the manual entry.

I have written this javascript codes which solves my purpose, but when the page loads..I can see the box there even when the user hasn't selected anything. How can I fix this, so this only shows a checkbox when the user clicks Other, or removes the checkbox if the user clicks on another option after hitting Other once.

HTML code :p

<tr>
    <td>Industry*</td>
    <td>
        <select name="industry" id="industry" class="validate[required]" onchange="javascript: test()"> 
            <option value="BPO">BPO</option>
            <option value="Call Centre"> Call Centre </option>
            <option value="Software">Software</option>
            <option value="Networking">Networking</option>
            <option value="Management">Management</option>
            <option value="Other">Other</option>
        </select>
    </td>
</tr>
<tr>
    <td></td>
    <td>
        <input type="text" name="industryo" id="industryo" placeholder="Enter Manually">
    </td>
</tr>

JS

<script>
function test()
{
  //alert("something");
  var industry = document.getElementById('industry').value;
  if(industry == "Other")
  {
    $( document ).ready(function() {
      // Handler for .ready() called.
      $('#industryo').show();
    });
  }
  else
  {
    $( document ).ready(function() {
      $('#industryo').hide();
    });
  }
}
</script>

Any suggestion is helpful.

Upvotes: 1

Views: 1520

Answers (2)

Tricky12
Tricky12

Reputation: 6822

I think this is what you want. Initially hide your input, then show/hide it depending if the dropdown has "Other" selected. You can use the on change event to check that.

Demo here

//Hide initially
$('#industryo').hide();

$('#industry').on('change', function() {
    if($(this).val() == "Other") {
        $('#industryo').show();
    } else {
        $('#industryo').hide();
    }
});

Upvotes: 1

Code Maverick
Code Maverick

Reputation: 20415

You can initially hide with CSS in your HTML:

<input type="text" 
       name="industryo" 
       id="industryo" 
       placeholder="Enter Manually"
       style="display: none;" />

or in our CSS file:

#industryo { display: none; }

or with jQuery:

<script>
    // Shorthand for $( document ).ready()
    $(function() { $("#industryo").hide(); });
</script>

Upvotes: 1

Related Questions