2014-04-11 53 views
0

我稍微困惑如何填充DIV作爲例子中看到一個DIV,說我有以下的下拉菜單和DIV:如何填充使用jQuery和下拉

<div id='drop'> 
    <select name='option'> 
     <option value="Opt1">Opt1</option> 
     <option value="Opt2">Opt2</option> 
     <option value="Opt3">Opt3</option> 
    </select> 
</div> 

<div id = 'NewContent'> 

</div> 

然後將下面的JS:

$('select[name="option"]').change(function() { 
    $('#NewContent').html(this.value); 
}); 

我將如何把下列的事業部:

<form> 
First name: <input type="text" name="firstname"><br> 
Last name: <input type="text" name="lastname"> 
</form> 

如果用戶選擇OPT2 FO r example

回答

0

您可以使用類似下面的jQuery追加的形式:

$('select[name="option"]').change(function() { 
    if (this.value == 'Opt2') { 
     var form = $('#test'); 
     if (form.length == 0) { 
      $('#NewContent').html('<form id="test">First name: <input type="text" name="firstname"><br>Last name: <input type="text" name="lastname"></form>'); 
     } 
    } 
}); 

Example

1

這是你在追求什麼?

$('select[name="option"]').change(function() { 
    if($("select.foo option:selected").val() == 'Opt2'){ 
     $('#NewContent').html('<form> \ 
           First name: <input type="text" name="firstname"><br> \ 
           Last name: <input type="text" name="lastname"> \ 
           </form>'); 
    } 
}); 
0

做到這一點:

您的HTML改爲:

<div style="display:none" id="hold"> 
    <form> 
    First name: <input type="text" name="firstname"><br> 
    Last name: <input type="text" name="lastname"> 
    </form> 
<div> 

而做到這一點:

$('select[name="option"]').change(function() { 
    if($(this).val()=="Opt2"){ 
     $('#NewContent').html($('#hold').html()); 
    } 
}); 
0

Chris的解決方案沒問題。
另一種方法是已經包括在NewContent DIV HTML:

<div id = 'NewContent'> 
<form> 
    First name: <input type="text" name="firstname"><br> 
    Last name: <input type="text" name="lastname"> 
    </form> 
</div> 

然後通過CSS隱藏:

#NewContent form { 
    display:none; 
} 

所以,當你點擊:

$('select[name="option"]').change(function() { 
    $('form', '#NewContent').show(); 
});