Adrian Adrian - 4 months ago 8
HTML Question

Select that generate a different nput type number

I have this html markup.

<select name="components">
<option value="solo">solo</option>
<option value="group">group</option>
<option value="band">band</option>
</select>


I want to generate a input type number after select an option without reload the page.

Like this:

// When I select solo option:
<input type="number" name="dancers" value="1" min="1" max="1">

// When I select group option:
<input type="number" name="dancers" value="2" min="2" max="6">

// When I select band option:
<input type="number" name="dancers" value="7" min="7" max="12">


*I need to submit only the input generated by the option selected.

Thank you in advance!

Answer

Store data in object structure, and when options selected set value, min, max to attribute according to selected option:

Javascript:

data = {"solo": {"value": 1, "min": 1, "max": 1},
        "group": {"value": 2, "min": 2, "max": 6},
        "band": {"value": 7, "min": 7, "max": 12}};

 $("select[name='components']").change(function(){
    selected_option = $(this).val();
    selected_data = data[selected_option];
    ["value", "min", "max"].forEach(function(key){
      $("input[name='dancers']").attr(key, selected_data[key]);
    });
 });

HTML:

<select name="components">
  <option value="solo">solo</option>
  <option value="group">group</option>
  <option value="band">band</option>
</select>

<input type="number" name="dancers">

jsfilddle

Comments