简体   繁体   中英

Dynamic Dropdown menu through php

I visited a website a few weeks ago and came across a dynamic drop down menu. I came across a functionality that I am now trying to replicate but do not know how. In the dropdown you picked the desired number of cars and then it reiterated input fields according to the number of cars chosen. I believe this was done through javascript and a loop was involved. Is there a term for this action or way to display things? Also an example of how to accomplish something similar would help?

在此处输入图片说明

It's unlikely that this would be done with PHP, since that would require a page refresh. It's more likely that it would be done with Javascript listening for the onChange event of the Select element (the drop down menu). When the event is detected, Javascript could show / hide div elements (one for each Car), or dynamically create / destroy them.

This is done using java script , and here a hint

create a div and put inputs that you want inside it

<div id='controls'>
<input type="text" name="car_name" />
</div>

and using jQuery change event you can iterate view of controls div

ie if you have a div with id container , where you will place new controls

$('select').change(function(){
 var number = parseInt ($(this).val ());
 //And do for loop here
 for (var i=1;i<=number;i++){
     $('#controls').clone().appendTo($('#container');
  }
});

Please enhance this code to fit your requirement.

If you want it without refresh, you need use javascript, i have made one example here using jquery: HTML CODE

<label>How many cars?</label>
<select>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>
<div id="fields"></div>

JAVASCRIPT CODE

$('select').change(function() {
    var option = $(this).val();
    showFields(option);
    return false;
});
function showFields(option){
    var content = '';
    for (var i = 1; i <= option; i++){
        content += '<div id="field_'+i+'"><label>Car '+i+'</label><br /><label>Model:</label> <input id="model_'+i+'" /><br /><label>Maker:</label> <input id="maker_'+i+'" /><br /><label>Year:</label> <input id="year_'+i+'" /><br /><div><br />';
    }
    $('#fields').html(content);
}

Here the example: http://jsfiddle.net/zbzjm/1/

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