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
Add a ment  | 

2 Answers 2

Reset to default 5

Working 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

本文标签: javascriptHow do I dynamically add new items to dropdown list within this form using jqueryStack Overflow