javascript - Select not displaying correct selected value after update -
this select in html:
<select id="bgposition"> <option value="left top" selected="selected">left top</option> <option value="center top">center top</option> .. </select>
on page load need update selected value one, tried .each
.prop
, this:
function setactiveoption(el,val){ $(el).find('option:selected').removeattr('selected'); $(el).find('option[value="'+val+'"]').attr('selected','selected'); console.log('selected: '+$('#bgposition').val()) }
all ok other select boxes, not #bgposition
think because values contains spaces.
selected
attribute in right place, displaying first option selected
any idea how can fixed?
i tried different jquery libraries
update: my fiddle , how running functions.
given example fiddle, select
element doesn't respect value set middle one, #bgrepeat
, , that's because default you've got 2 option
set selected
attribute.
to fix problem, provide 1 option
selected
attribute.
that being said, better solution use .val()
setter on select
itself, one-liner , therefore renders setactiveoption()
function redundant. try this:
var template = [{ "mainbgimgposition": "right bottom", "mainbgimgrepeat": "no-repeat", "mainbgimgsize": "cover" }] jquery(function($) { var builder = { initialized: false, initialize: function() { if (this.initialized) return; this.initialized = true; $('#bgposition').val(template[0].mainbgimgposition); $('#bgrepeat').val(template[0].mainbgimgrepeat); $('#bgsize').val(template[0].mainbgimgsize); } } builder.initialize(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select name="bgposition" id="bgposition"> <option value="left top" selected="selected">left top</option> <option value="left center">left center</option> <option value="left bottom">left bottom</option> <option value="center top">center top</option> <option value="center center">center center</option> <option value="center bottom">center bottom</option> <option value="right top">right top</option> <option value="right center">right center</option> <option value="right bottom">right bottom</option> </select> <select name="bgrepeat" id="bgrepeat"> <option value="repeat" selected="selected">repeat all</option> <option value="repeat-x">repeat x</option> <option value="repeat-y">repeat y</option> <option value="no-repeat">no repeat</option> </select> <select name="bgsize" id="bgsize"> <option value="auto" selected="selected">auto</option> <option value="cover">cover</option> </select>
Comments
Post a Comment