techie_28 techie_28 - 6 months ago 18
Javascript Question

How to use jQuery object for a select box

I am in need to have a value selected in a drop down and show that at a place.
The select box is formed using a variable,So what I did is

jQuery('<select>'+projAddHocs+'</select>')
.find('[value='+val[59]+']')
.attr('selected','selected')
.prop('outerHTML');


or

jQuery('<select>'+projAddHocs+'</select>').val(val[59]).prop('outerHTML');


val[59] has the value which I need to be selected in the drop down before displaying.

It is easy when select exist in the DOM,but I am unable to do it using jQuery wrapper.

Any help/directions please?

Regards.

Answer

You are selecting outerHTML of your selected <option> because you got there through find().

Go back to your select using parent():

jQuery('<select>'+projAddHocs+'</select>')
    .find('[value='+val[59]+']')
    .attr('selected','selected')
    .parent()
    .prop('outerHTML');

See fiddle

or, better:

var select = jQuery('<select>'+projAddHocs+'</select>');
select.find('[value='+val[59]+']').attr('selected','selected');

$('#wrapper').html(select.prop('outerHTML'));

See fiddle

Comments