April 25, 2011

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 value val

  • .html(text): Inserts a Text for the option

    var myOptions = {val1:'text1', val2:'text2'};: It defines an array which contains the value and text which 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.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!