Set select option 'selected', by value

后端 未结 28 2262
攒了一身酷
攒了一身酷 2020-11-22 10:40

I have a select field with some options in it. Now I need to select one of those options with jQuery. But how can I do that when I only know the

28条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 11:31

    There's no reason to overthink this, all you are doing is accessing and setting a property. That's it.

    Okay, so some basic dom: If you were doing this in straight JavaScript, it you would this:

    window.document.getElementById('my_stuff').selectedIndex = 4;
    

    But you're not doing it with straight JavaScript, you're doing it with jQuery. And in jQuery, you want to use the .prop() function to set a property, so you would do it like this:

    $("#my_stuff").prop('selectedIndex', 4);
    

    Anyway, just make sure your id is unique. Otherwise, you'll be banging your head on the wall wondering why this didn't work.

提交回复
热议问题