Adding Selected="Selected" in input

Asked

Viewed 79 times

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

  • 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.

  • 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/

  • Yes, I can use Jquery...tested with change: $(Document). on('change', 'select#user>option', Function(){ $('select#user>option'). attr('Selected',true); });

  • tries like this: $(Document). on('change', 'select#user>option', Function(){ $(this). attr('Selected', 'Selected'); });

  • You can join selected inside the loop. How do you know which is the option What should be marked? Is there a pattern to this? Where do you know this information?

  • 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!

  • 1

    First check which option or options should be checked, then handle such options within the loop, using a condition with if... else

Show 3 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.