最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get latest value selected from multiselect dropdown - Stack Overflow

programmeradmin1浏览0评论

I have a multiselect dropdown where I want to get the value of latest selected value. In my example, I've just used an alert to display the selected option. When I select 'volvo' it alerts volvo and now if I press ctrl and multiselect 'opel', I still get alerted 'volvo'. But I want it to alert 'opel'. I tried using an array to store the values but I'm not able to use the second option in the dropdown.

My actual code is about inserting these values dynamically to a new row in a table. But 'volvo' gets added evrytime instead of other selected options

Here's the code:

<!DOCTYPE html>
<html>

<body>

  <form action="/action_page.php">
    <select name="cars" onchange="myFucntion(this.value)" multiple>
    <option value="volvo">Volvo</option>
    <option value="bmw">Bmw</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
    </select>
    <input type="submit">
  </form>

  <p>Hold down the Ctrl (windows) / Command (Mac) button to select multiple options.</p>

  <script type="text/javascript">
    function myFucntion(val) {
      alert(val);
    }
  </script>
</body>

</html>

I have a multiselect dropdown where I want to get the value of latest selected value. In my example, I've just used an alert to display the selected option. When I select 'volvo' it alerts volvo and now if I press ctrl and multiselect 'opel', I still get alerted 'volvo'. But I want it to alert 'opel'. I tried using an array to store the values but I'm not able to use the second option in the dropdown.

My actual code is about inserting these values dynamically to a new row in a table. But 'volvo' gets added evrytime instead of other selected options

Here's the code:

<!DOCTYPE html>
<html>

<body>

  <form action="/action_page.php">
    <select name="cars" onchange="myFucntion(this.value)" multiple>
    <option value="volvo">Volvo</option>
    <option value="bmw">Bmw</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
    </select>
    <input type="submit">
  </form>

  <p>Hold down the Ctrl (windows) / Command (Mac) button to select multiple options.</p>

  <script type="text/javascript">
    function myFucntion(val) {
      alert(val);
    }
  </script>
</body>

</html>

EDIT: There seems to be a problem with only selectpicker multiselect dropdown. It works fine when I remove selectpicker class. Is there anyway to solve it when using selectpicker?

Share Improve this question edited Jul 3, 2017 at 11:10 coder1456 asked Jul 3, 2017 at 9:50 coder1456coder1456 1814 silver badges11 bronze badges 1
  • Check my answer, it really implement the latest selection tracking. For all other answers you will see that when you deselects a option you get that value as latest selection. Mine is not like that. You can understand well when you run it. – Ankit Agarwal Commented Jul 3, 2017 at 10:16
Add a ment  | 

5 Answers 5

Reset to default 2

You need to put a click handler on the options. Then just test whether the option is selected or not (so you don't alert when you're de-selecting the option).

<!DOCTYPE html>
<html>

<body>

  <form action="/action_page.php">
    <select name="cars"  multiple>
    <option value="volvo" onclick="myFunction(this)">Volvo</option>
    <option value="bmw" onclick="myFunction(this)">Bmw</option>
    <option value="opel" onclick="myFunction(this)">Opel</option>
    <option value="audi" onclick="myFunction(this)">Audi</option>
    </select>
    <input type="submit">
  </form>

  <p>Hold down the Ctrl (windows) / Command (Mac) button to select multiple options.</p>

<script type="text/javascript">
function myFunction(option) {
    if (option.selected) {
        alert(option.text);
    }
}
</script>
</body>

</html>

This gets the last selected item in your option list.

<!DOCTYPE html>
<html>

<body>

  <form action="/action_page.php">
    <select name="cars" onchange="myFucntion(this.value)" multiple>
    <option value="volvo">Volvo</option>
    <option value="bmw">Bmw</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
    </select>
    <input type="submit">
  </form>

  <p>Hold down the Ctrl (windows) / Command (Mac) button to select multiple options.</p>

  <script type="text/javascript">
    var lastSelected = null;
    function myFucntion(val) {
      alert(lastSelected === null ? 'There was no last selected item' : lastSelected);
      lastSelected = val;
    }
  </script>
</body>

</html>

I suspect this is not what you want. You would likely want all the selected items in the list:

//Function courtesy of https://stackoverflow./a/27781069/4875631
function getSelectValues(select) {
  var result = [];
  var options = select && select.options;
  var opt;

  for (var i=0, iLen=options.length; i<iLen; i++) {
    opt = options[i];

    if (opt.selected) {
      result.push(opt.value || opt.text);
    }
  }
  return result;
}

function myFunction(select) {
    var values = getSelectValues(select);
    console.log(values);
}
<!DOCTYPE html>
<html>

<body>

  <form action="/action_page.php">
    <select name="cars" onchange="myFunction(this)" multiple>
    <option value="volvo">Volvo</option>
    <option value="bmw">Bmw</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
    </select>
    <input type="submit">
  </form>

  <p>Hold down the Ctrl (windows) / Command (Mac) button to select multiple options.</p>
</body>

</html>

Changing the event to click and using the target.value should do the trick.

const elem = document.getElementById('elem');
      elem.addEventListener('click', (e) => console.log(e.target.value));
<form action="/action_page.php">
  <select name="cars" id='elem' multiple>
    <option value="volvo">Volvo</option>
    <option value="bmw">Bmw</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
  </select>
  <input type="submit">
</form>

<p>Hold down the Ctrl (windows) / Command (Mac) button to select multiple options.</p>

I think we have to keep proper track of recent selection of the select values. Let's say user selects

A -> B-> C-> D

Then recent selection is D so we print D. Now what if user deselect option D. AT this case the proper recent tracking would work if you are able to print C, as C is recently selected before D. And so on when C is deselect. All of the answers above do not consider this. So i have my version of answer and logic here.

$(document).ready(function(){

var selectedValues = [];
$('#carsDdl').on('click',function(event){
  var recentSelection = event.target.value;
  var index = selectedValues.indexOf(recentSelection);
  if(index === -1){
     selectedValues.push(recentSelection);
  }else{
     selectedValues.splice(index,1);
  }
  if(selectedValues.length !== 0){
     var recentSelection = selectedValues[selectedValues.length-1];
     console.log('All selected cars: '+ selectedValues);
     console.log('Recently selected car: '+ recentSelection);
  }
 
})

});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <form action="/action_page.php">
    <select id = 'carsDdl' name="cars" multiple>
    <option value="volvo">Volvo</option>
    <option value="bmw">Bmw</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
    </select>
    <input type="submit">
  </form>

I added ability to find out appending and removing item from multiselect

var old_selected = [];
function getSelectValues(select) {
  var result = [];
  var options = select && select.options;
  var opt;

  for (var i=0, iLen=options.length; i<iLen; i++) {
    opt = options[i];

    if (opt.selected) {
      result.push(opt.value || opt.text);
    }
  }
  return result;
}
function myFucntion(el){
	new_selected = getSelectValues(el);
  //find added elemnts
  added = new_selected.filter(function(item){
  	return old_selected.indexOf(item)==-1
  });
  if(added.length>0)
  	alert(added+' added')
  //find removed 
  removed = old_selected.filter(function(item){
  	return new_selected.indexOf(item)==-1
  });
  if(removed.length>0)
  	alert(removed+' removed')
 
  old_selected = new_selected;
  
}
  

<form action="/action_page.php">
    <select name="cars" onchange="myFucntion(this)" multiple>
    <option value="volvo">Volvo</option>
    <option value="bmw">Bmw</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
    </select>
    <input type="submit">
  </form>

  <p>Hold down the Ctrl (windows) / Command (Mac) button to select multiple options.</p>

发布评论

评论列表(0)

  1. 暂无评论