admin管理员组

文章数量:1397502

I am using Select2 (via CDN / latest version) with data loaded from an array. (Note that data is pulled via AJAX/JSON, but due to some unusual circumstances, this is loaded via an array.) I need to programmatically select a value via text, not an ID. I can get this to work via an ID, but not text. While I can manually loop through the array, and determine the ID, and select from the ID, I would assume that there is a more elegant way...

Here are some code fragments...

// Now load all the elements into the array, which es from AJAX
         for (i = 0; i < rowCount; i++) {                      
         myData.push({id: i, text: p_data.rows[i].NN_NAME});                     
         }   

        // create my Select2 control           
        var $mySelectControl =  $(".mySelect").select2({
            data: myData,
            width:300,
            placeholder: "Select an account",
            allowClear: true
         });

At some later point, I want to programatically select 'Mainstay Electric'. I can select if I know the ID, but cannot find how to select if I just know the text.

// THIS WORKS
    $(".mySelect").val(null).trigger("change");

//.. but not this  

 $(".mySelect").val('Mainstay Electric').trigger("change");

In reviewing other questions, I found this example I modified...

 $(".mySelect").select2("trigger", "select", {
         data: { text: 'Mainstay Electric' }
         });

...but this gives a JavaScript error that a.ID is undefined.

Other than looping through the myData array to get the ID and use it, is there a way to just pass the text (i.e. the 'Mainstay Electric')?

Thanks

I am using Select2 (via CDN / latest version) with data loaded from an array. (Note that data is pulled via AJAX/JSON, but due to some unusual circumstances, this is loaded via an array.) I need to programmatically select a value via text, not an ID. I can get this to work via an ID, but not text. While I can manually loop through the array, and determine the ID, and select from the ID, I would assume that there is a more elegant way...

Here are some code fragments...

// Now load all the elements into the array, which es from AJAX
         for (i = 0; i < rowCount; i++) {                      
         myData.push({id: i, text: p_data.rows[i].NN_NAME});                     
         }   

        // create my Select2 control           
        var $mySelectControl =  $(".mySelect").select2({
            data: myData,
            width:300,
            placeholder: "Select an account",
            allowClear: true
         });

At some later point, I want to programatically select 'Mainstay Electric'. I can select if I know the ID, but cannot find how to select if I just know the text.

// THIS WORKS
    $(".mySelect").val(null).trigger("change");

//.. but not this  

 $(".mySelect").val('Mainstay Electric').trigger("change");

In reviewing other questions, I found this example I modified...

 $(".mySelect").select2("trigger", "select", {
         data: { text: 'Mainstay Electric' }
         });

...but this gives a JavaScript error that a.ID is undefined.

Other than looping through the myData array to get the ID and use it, is there a way to just pass the text (i.e. the 'Mainstay Electric')?

Thanks

Share Improve this question edited Jul 18, 2017 at 13:57 user1009073 asked Jul 18, 2017 at 13:51 user1009073user1009073 3,2389 gold badges46 silver badges93 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

A simple example, if your option text is unique and using this could return the id for you:

$("#test_id option:contains('Option 4')").val()

then call

$('#test_id').val($("#test_id option:contains('Option 4')").val()).change();

to select it by text and call trigger change so it is selected.

To get the exact match just add a function getOptId to get the id if text provided.

// Grade
$('#test_id').select2({
  width: '200px',
  data: [],
});



$('#text_btn').click(function() {
  $('#test_id').val(getOptId('Option 4')).change();
});


function getOptId(text) {
  let id = '';
  $('#test_id').find('*').filter(function() {
    if ($(this).text() === text) {
      id = $(this).val();
    }
  });
  return id;
}
<link href="https://cdnjs.cloudflare./ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/select2/4.0.3/js/select2.min.js"></script>

<div>
  <select id="test_id">
        <option></option>
        <option value="1">Option 1</option>
        <option value="2">Option 2</option>
        <option value="3">Option 3</option>
        <option value="4">Option 4 TEST</option>
        <option value="5">Option 4 This is 5</option>
        <option value="6">Option 4</option>
    </select>
</div>
<br>
<button id="text_btn">Select Option 4</button>

本文标签: javascriptSetting text value in Select2Stack Overflow