0

I'm a programming noob. I have a selectmenu where I have two buttons that allow the user to add and remove options in the menu. I would like to assign each option in the selectmenu to a variable of type object, but unfortunately I don't know how many options the user will add to the selectmenu up front. Is there a way to dynamically declare a new global variable each time as the user adds a new option to the selectmenu?

Please see html code for selectmenu below.

<select id="List">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</select>

Please see jquery code below to add an option to the selectmenu.

$(".bt1").click(function () {
var opt = $("#ip1").val();
$('#List')
    .append($("<option></option>")
    .attr("value", opt)
    .text(opt));
AS3Noob
  • 131
  • 5

2 Answers2

0

If you're a beginner, my first recommendation would be to avoid global variables at all costs (no matter the programming language). In this post you can find many ways of how to avoid their use in js.

Going back to your problem, you could extend the object that contains the buttons with a new one everytime the user adds a button and remove it once the button is removed. Or you could use an array to store buttons (objects and arrays are almost the same in js). There are many ways. But try to wrap your variables in functions and avoid clustering the global space at all costs.

Community
  • 1
  • 1
acontell
  • 6,792
  • 1
  • 19
  • 32
0

HTML

<select id="List">
    <option value="select">Select</option>
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="new">new</option>
    <option value="old">old</option>
</select>
<input type="button" id="delete"
 value="delete" />
<br />

<input type='text' id="readme" /><input id="add" type="button" value="add" /><br />

JQUERY

$('#add').on('click',function(){
    $("#List").append('<option>'+$('#readme').val()+'</option>');
});
$('#delete').on('click',function(){
    $("#List option:selected").remove();
});

Demo URL Below

http://jsfiddle.net/bxsnevzs/

Nadeemmnn Mohd
  • 713
  • 5
  • 14