Fill select javascript / jquery field

Asked

Viewed 1,291 times

1

Hello, I need to fill a select field with the return of this function, in this example, the RES variable returns:

<option value="">setor 1</option>

exactly that, I need it to become one of the options of my select field, but nothing happens, I am trying so:

$('#cSetor').html(res);      

where cSetor is the ID of my select field

Javascript:

$(document).ready(function() {
    $('#cSecretaria').on('change', function() {
        $.post('_require/_jp/jpcarregasetor.php', {
            id_sec: document.getElementById("cSecretaria").value,
        }, function(res) {
            $('#cSetor').html(res);
        })
    })
})

HTML:

<div class="form-group col-md-4">
    <label for="cSetor">Setor pertencente</label>
    <select class="form-control selectpicker" title="--" name="tSetor" id="cSetor">
    </select>
</div>
  • What gives console.log(res) put in place of $('#cSetor').html(res);?

  • nothing happens

  • You know where to see the result of console.log? If not, use Alert.

  • put Alert(console.log(res)); the result of Alert was: Undefined

  • What I meant was alert(res);

  • ah, sorry, the result is an option pro select code, very straight: < option > test < option >

  • Okay, that’s good. So what if you do $('#cSetor').append(res).selectpicker('refresh'); works?

  • worked, but there’s a problem, this select #cSetor depends on which one I choose in the previous one, and each time I choose an option in the previous one, it updates select #cSetor, but the way you showed me it adds new options to #cSetor, when you should delete the previous ones and upload everything again, understand ?

  • I put the answer together with the two options.

  • hi, is there any other way? pq the way you showed me, every time I click is added one more option of my select, and I don’t want that

  • Marcelo: yes, as I put in the answer, see? using the .html() but calling the .selectpicker('refresh'); also. -> http://answall.com/a/129553/129

Show 6 more comments

3 answers

2


I see you’re using Boostrap’s select, so for any change you make you need to call the method .selectpicker('refresh'); for him to apply the changes.

If you want to replace HTML you can use

$('#cSetor').html(res).selectpicker('refresh');

If you want to add HTML you can use

$('#cSetor').append(res).selectpicker('refresh');
  • Sorry, I was taking care of the comments up there, it worked now using the . html(), really worth!

1

Replace "html" with "append":

$('#cSetor').append(res);
  • I tried, it didn’t work

0

Exchange value="", for value=''

Also confirm that ajax dataType is HTML

  • 1

    What a difference it makes "" or ''? using value= will delete the value and not fetch it...

Browser other questions tagged

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