Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
113
rated 0 times [  119] [ 6]  / answers: 1 / hits: 32741  / 12 Years ago, wed, june 13, 2012, 12:00:00

I have a select dropdownlist with 1 item selected at page load in html.



<select name = options>
<option value = 1>Item1</option>
<option value = 2 selected>Item2</option>
<option value = 3>Item3</option>
<option value = 4>Item4</option>
</select>


Now I want to capture new select option when user press shift and select another option such as Item 3.



I have the following code to find all the selections in the list



 var value = ;
for (var intLoop = 0; intLoop < Form.elements[index].length; intLoop++) {

if(Form.elements[index][intLoop].selected )
value = value + Form.elements[index][intLoop].value;
}


I can see the Item 2 and Item 3 are selected but i want to get capture Item 3 only. Is it possible?


More From » html

 Answers
12

Here's code that will tell you what has been selected and what has been deselected http://jsfiddle.net/8dWzB/



It uses Array.prototype.indexOf, and it's not the fastest way to do it. But it should get you going in the right direction.



HTML



<select id=options multiple=multiple>
<option value = 1>Item1</option>
<option value = 2 selected>Item2</option>
<option value = 3>Item3</option>
<option value = 4>Item4</option>
</select>


JS



function getSelectedIndexes(select) {
var selected = [];
for (var i = 0; i < select.options.length; i++) {
if(select.options[i].selected ) {
selected.push(i);
}
}
return selected;
}

var select = document.getElementById(options);
var prevSelected = getSelectedIndexes(select);

select.onchange = function(e) {
var currentlySelected = getSelectedIndexes(this);

for (var i =0; i < currentlySelected.length; i++) {
if (prevSelected.indexOf(currentlySelected[i]) == -1) {
console.log(Added to selection , this.options[currentlySelected[i]].text);
}
}

for (var i =0; i < prevSelected.length; i++) {
if (currentlySelected.indexOf(prevSelected[i]) == -1) {
console.log(Removed from selection , this.options[prevSelected[i]].text);
}
}
prevSelected = currentlySelected;
};



If you really only want to know which item was last clicked, you can use the following code. I'll use jQuery so I can easily set a handler on all the option objects. Remember this won't work if you change the selection with the keyboard



    $('option').click(function(e){
var parentNode = this.parentNode;
for (var i=0; i < this.parentNode.options.length; i++) {
if (parentNode.options[i] == this) {
console.log('Clicked item with index', i);
break;
}
}
});

[#84925] Tuesday, June 12, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nikokorbinm

Total Points: 744
Total Questions: 126
Total Answers: 104

Location: Jersey
Member since Fri, Oct 1, 2021
3 Years ago
;