JQuery .val(value)
Question by Suzanne
Could anyone help me understand how this code segment works? I’m assuming it produces something like <option value="val">text</option>, but I just don’t see how it does that.
$('<option></option>').val(val).html(text)
The above snippet is part the following code I used to add two options to a <select> statement.
var myOptions = {val1:'text1', val2:'text2'};
$.each(myOptions, function(val, text)
{
$('#mySelect').append($('<option></option>').val(val).html(text));
}
Answer by Starx
Basically, it interprets as
<option value="val">text</option>
Detailed:
-
$('<option></option>'): Creates a new option element -
.val(val): Gives it the valueval -
.html(text): Inserts a Text for the optionvar myOptions = {val1:'text1', val2:'text2'};: It defines an array which contains thevalueandtextwhich is used to populate the select box
$.each(myOptions, function(val, text) {}: This part interate over all the myOptions available and receives the value as val and text as text.
The $('#mySelect').append part adds the above markup (<option value="val">text</option>) into the select box $('#mySelect') at the end.