1

I am creating a array which contains text of selected values of a multi select bootstrap chosen-select. But i am not getting desired output like: ["Navy", "Dark Blue", "Light Green"] What I am getting is: ["NavyDark BlueLight Green"]. What is the reason..

This is my code..

$('[name="ci_claimed_for"]').each(function() {
      names.push($('[name="ci_claimed_for"]').find("option:selected").text());
});
3
  • Please add html-markup too Commented May 19, 2017 at 10:58
  • add all relevant code in OP like html and js Commented May 19, 2017 at 10:58
  • can you show your html Commented May 19, 2017 at 10:58

4 Answers 4

1

You don't even need to create a new array and then push into it: just use jQuery's .map() function:

var names = $('[name="ci_claimed_for"]').map(function() {
     return $(this).find("option:selected").text());
}).get();

Remember to chain .get() in the end, because it will return a jQuery collection. Use .get() to reference the actual array returned.

Here is a proof-of-concept example:

$(function() {
  var names = $('[name="ci_claimed_for"]').map(function() {
      return $(this).find("option:selected").text();
  }).get();
  
  console.log(names);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="ci_claimed_for">
  <option value="John" selected>John</option>
  <option value="Doe">Doe</option>
</select>
<select name="ci_claimed_for">
  <option value="Jane" selected>Jane</option>
  <option value="Doe">Doe</option>
</select>

Sign up to request clarification or add additional context in comments.

Comments

0

You can do it in this

//take a empty arr
var names = [""];
$('[name="ci_claimed_for"]').each(function() {
                $('[name="ci_claimed_for"] option:selected').each(function(){
                    names.push($(this).text());
                });
});

then just shift your array:

names.shift();

Comments

0

You should be iterating it as follows:

CODE

var arr=[];
var data=$('[name="ci_claimed_for"]').find("option:selected")
for(var i=0;i<data.length;i++){
   arr.push(data.eq(i).text())
}
console.log(arr) //desired result  

Using the $('[name="ci_claimed_for"]').text() will return all the text in array of nodes obtained

Comments

0

For your js code .you need a $(this) inside the each .You iterate the each element but not pushing with each element to array

 $('[name="ci_claimed_for"]').each(function() {
      name.push($(this).val())
    });

OR

$('[name="ci_claimed_for"]').each(function() {
          names.push($(this).find("option:selected").text());
        });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.