admin管理员组文章数量:1290935
$(document).ready(function() {
var element;
$(".form-element").on("mousedown", function(event){
element = $('<form><select name="dropdown"><option>Select...</option><option value="new-dropdown">add new...</option><option value="machine3">Machine 3</option><option value="machine4">Machine 4</option></select></form>');
$("#body-div").append(element);
});
});
The items in the list currently are just there for testing. But I need to be able to click on an add new option and add a new list item.
$(document).ready(function() {
var element;
$(".form-element").on("mousedown", function(event){
element = $('<form><select name="dropdown"><option>Select...</option><option value="new-dropdown">add new...</option><option value="machine3">Machine 3</option><option value="machine4">Machine 4</option></select></form>');
$("#body-div").append(element);
});
});
The items in the list currently are just there for testing. But I need to be able to click on an add new option and add a new list item.
Share Improve this question asked Nov 29, 2015 at 2:36 NucleusDevelopmentNucleusDevelopment 1191 gold badge2 silver badges12 bronze badges 1- Show you html or a fiddle please. – Nico Commented Nov 29, 2015 at 2:46
2 Answers
Reset to default 5Working Fiddle
It looks like you were trying to dynamically add the entire form, but you only need to add additional option
elements to your select
section of your form.
To do this add this HTML
HTML
<input id="text-to-add" type="text" value="Machine 3">
<button id="new-item">Add to dropdown</button>
<form>
<select name="dropdown">
<option>Select...</option>
<option>Machine 1</option>
<option>Machine 2</option>
</select>
</form>
Then to dynamically add a select element use the append jQuery function.
jQuery
$(document).ready(function () {
$('#new-item').click(function() {
console.log($('#text-to-add').val());
$('select').append( '<option>' + $('#text-to-add').val() + '</option>' );
});
});
First add a new id for both the select tag and the option tag with the value "new option";
element = $('<form>
<select name="dropdown"
id="sel"><option>Select...</option>
<option value=
"new-dropdown"id="anew">add new...
</option></select></form>');
now im assuming that you already have the values for both the value and the text for that option let both of them be x and y respectively; now add an onClick handler to #anew to append #sel with a new option with value x and text y:
z=$('<option value="'+x+'">'+y+'</option>');
$("#anew").onClick(function(){
$("#sel").append(z);
});
hope it solves your problem
版权声明:本文标题:javascript - How do I dynamically add new items to dropdown list within this form using jquery? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741515626a2382870.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论