Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
186
rated 0 times [  188] [ 2]  / answers: 1 / hits: 19577  / 9 Years ago, sun, november 29, 2015, 12:00:00
$(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.


More From » jquery

 Answers
60

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>' );
});
});

[#64237] Thursday, November 26, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
trentb

Total Points: 261
Total Questions: 101
Total Answers: 90

Location: French Southern and Antarctic Lands
Member since Fri, Jan 6, 2023
1 Year ago
;