简体   繁体   中英

How to get the placeholder value of a select2 dropdown using jQuery

I have a select2 dropdown like this:

$('.to_country_dropdown').select2({
    placeholder: "Sweden",
    language: {
        noResults: function () {
            return "Vi hittar inte landet!"
        }  
    }
});

Then in another place I want to get this placeholder value. I have tried this:

$('.to_country_dropdown').attr('placeholder').val();
$('.to_country_dropdown').attr('placeholder');

But both that returns undefined.

I've you need to select the placeholder value of the select you will have to select it by the class select2-selection__placeholder'

 $('.to_country_dropdown').select2({ placeholder: "Sweden", language: { noResults: function () { return "Vi hittar inte landet!" } } }); $(document).ready(function() { console.log($(".to_country_dropdown ").next().find('.select2-selection__placeholder').text()) }) 
 <link href="https://select2.github.io/dist/css/select2.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://select2.github.io/dist/js/select2.full.js"></script> <select class="to_country_dropdown"></select> 

$('.to_country_dropdown').data('select2').selection.placeholder.text

Do you have other inputs with a "to_country_dropdown" class? If so, you should put an ID(unique) to each one of it. So you could do something like this

    $('#ID.to_country_dropdown').attr('placeholder')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM