简体   繁体   中英

Dynamically generate a single new drop down menu in a html form

I have a html form defined . I have a button for the user to select his occupation . If his occupation happens to be a student then i need to generate another new button dynamically . If the user selects anything other than a student then i dont want any new button . I am unsure how to do . Do i use jquery ? I have no idea to use jquery . Can some one help ? Any pointers

Thanks.

<?php

?>
<script language="javascript" type="text/javascript">
$(document).ready(function()
{
    $('#occupation').change(function()
    {
        if($(this).val() == 'Student')
        {
            $('#school').show();
        } else {
            $('#school').hide();
        }
    });
});


</script>

<html>
<body>

<h1>My First Heading</h1>

<p>My first paragraph.</p>


<form>

<select name="occupation" id="occupation">
    <option value="">- Select Occupation -</option>
    <option value="Worker">Worker</option>
    <option value="Student">Student</option>
</select>
<select name="school" id="school" style="display: none;">
    <option value="">Select School Type</option>
    <option value="4 Year">4 Year</option>
    <option value="2 Year">2 Year</option>
</select>


</form>

</body>
</html>

Personally I accomplish this by placing the additional form element in the HTML, simply hidden like so:

<select name="occupation" id="occupation">
    <option value="">- Select Occupation -</option>
    <option value="Worker">Worker</option>
    <option value="Student">Student</option>
</select>
<select name="school" id="school" style="display: none;">
    <option value="">Select School Type</option>
    <option value="4 Year">4 Year</option>
    <option value="2 Year">2 Year</option>
</select>

Then you can use JS, as I prefer jQuery, to show the div or hide the div when applicable:

$(document).ready(function()
{
    $('#occupation').change(function()
    {
        if($(this).val() == 'Student')
        {
            $('#school').show();
        } else {
            $('#school').hide();
        }
    });
});

Using jQuery would simplify this:

Let's say you have the following:

<form>

  <select name="occupation">
      <option value="Non-Student">Non-Student</option>
      <option value="Student">Student</option>
  </select>

</form>

Then the following would be used to append the button if the user selected 'Student':

$(function(){
    $('select[name="occupation"]').change(function(){
      var val = $(this).val();
      if(val=='Student'){
         $('form').append('<button>New Button</button>');
      }
    });
});

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