0
I have a loop in js with a <select>
and <option>
, need to define a selected
to the <option>
, but as it is in the loop I can’t add straight into that <option>
, has any suggestion or hint?
Follows the code:
var $html = "<select class='form-control' name='usuario' id='usuario'>";
for( var i in data ){
var u = data[i];
$html += '<option value="'+ u.login +'">' + u.login + '</option>';
}
$html += '</select>';
better describe which field or field condition you want, so that the field is selected
– alexandre9865
The option that the user selects, it should stick to the attribute Selected="Selected"... I’ve tried onclick on option but it doesn’t work.
– David Silva
it’s not the click that tests this, it’s better to test it with the onchange, you can use jquery? if you can, you have the ':lected' selector as per the link: http://api.jquery.com/selected-selector/
– alexandre9865
Yes, I can use Jquery...tested with change: $(Document). on('change', 'select#user>option', Function(){ $('select#user>option'). attr('Selected',true); });
– David Silva
tries like this: $(Document). on('change', 'select#user>option', Function(){ $(this). attr('Selected', 'Selected'); });
– alexandre9865
You can join
selected
inside the loop. How do you know which is theoption
What should be marked? Is there a pattern to this? Where do you know this information?– Sergio
If I put Selected inside the option, because it is inside a loop, all s will have this property, and when the user chooses, regardless of their choice, the value will always be the last one added!
– David Silva
First check which option or options should be checked, then handle such options within the loop, using a condition with
if... else
– user28595