1

$('#btnadd').click(addBulletinBoard);

function addBulletinBoard() {
  var show = $('#show').val();
  var show1;
  console.log("before " + $('#show').val())
  if (jQuery.inArray("*", show) !== -1) {
    show1 = $("select#show option").map(function() {
      return $(this).val();
    }).get();
  }
  console.log("after :" + show)
  console.log("after " + show1.splice(0, 2))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" name="show" id="show" multiple="">
  <option value="" selected="" disabled="">Select...</option>
  <option value="*">All</option>
  <option value="1">option 1</option>
  <option value="2">option 2</option>
</select>
<button type="button" class="btn btn-primary" id="btnadd">Submit</button>

I have a demo above. What I want to happened is when Selecting option from the select and the option ALL is among the selected. I want to get all option except the first one and the second. So I used map with splice. But as seen in the console it is not what I am expecting.

How to get option values except first two in jquery

Manlapig
  • 33
  • 9

2 Answers2

1

Can simply use Array#filter()

$('#btnadd').click(addBulletinBoard);

function addBulletinBoard() {
  var show = $('#show').val().filter(function(val) {
    return val && val !== '*'
  });

  console.log("after :", show)

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" name="show" id="show" multiple="">
  <option value="" selected="" disabled="">Select...</option>
  <option value="*">All</option>
  <option value="1">option 1</option>
  <option value="2">option 2</option>
</select>
<button type="button" class="btn btn-primary" id="btnadd">Submit</button>
charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

splice would return an array containing the deleted elements and change the original array. So console.log("after " + show1.splice(0, 2)) would show the deleted elements that is not what you really want. Simply move show1.splice(0, 2) out of console.log() and it works as what you expected.

$('#btnadd').click(addBulletinBoard);

function addBulletinBoard() {
  var show = $('#show').val();
  var show1;
  console.log("before " + $('#show').val())
  if (jQuery.inArray("*", show) !== -1) {
    show1 = $("select#show option").map(function() {
      return $(this).val();
    }).get();
    show1.splice(0, 2)
  }
  console.log("after :" + show)
  console.log("after :" + show1)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" name="show" id="show" multiple="">
  <option value="" selected="" disabled="">Select...</option>
  <option value="*">All</option>
  <option value="1">option 1</option>
  <option value="2">option 2</option>
</select>
<button type="button" class="btn btn-primary" id="btnadd">Submit</button>
Hikarunomemory
  • 4,237
  • 2
  • 11
  • 21