how to get html select to show selected value with javascript - javascript

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?

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;
}
}
});

You could check the value of the selected options before a change event (e.g. item 1 and 2 are selected) and then again after the event (e.g. item 1, 2 and 3 are selected), and compare the difference.
Here is an example.
Fiddle here: http://jsfiddle.net/FnAuz/4/
I modified your select to allow multiple selections since I take it that's the crux of the problem.
HTML:
<form id="my-form">
<select name = "options" id="options" multiple>
<option value = "val1">Item1</option>
<option value = "val2">Item2</option>
<option value = "val3">Item3</option>
<option value = "val4">Item4</option>
</select>
</form>​
JS:
var oldValue = "";
document.getElementById('options').onchange = function() {
var myForm = document.getElementById ('my-form');
var value = "";
for (var intLoop = 0; intLoop < myForm.elements[0].length; intLoop++) {
if(myForm.elements[0][intLoop].selected) {
value = value + myForm.elements[0][intLoop].value;
}
}
for (var intLoop = 0; intLoop < myForm.elements[0].length; intLoop++) {
var optionVal = myForm.elements[0][intLoop].value;
if(myForm.elements[0][intLoop].selected && value.indexOf(optionVal) !== -1 && oldValue.indexOf(optionVal) === -1) {
console.log('Last clicked was ' + myForm.elements[0][intLoop].value)
}
}
oldValue = value;
};
EDIT: I just noticed that my example works when the user makes command/ctrl selections, but if they make a shift selection then ALL the new values will be counted as the 'last clicked item'. So my code would need some work to account for this scenario. I'm out of time, but hopefully my code is useful in its current state nevertheless!

Try this :
var e = document.getElementById("ID_of_Select_Element");
var _selectedValue= e.options[e.selectedIndex].value;

It started looking messy so I'm posting it as an answer:
<html>
<head>
<script type="text/javascript">
<!--
var value = '0';
document.getElementById('options').onchange = function() {
value = parseInt(value) + parseInt(this.value);
alert(value);
}
-->
</script>
</head>
<body>
<select name="options" id="options">
<option value = "1">Item1</option>
<option value = "2" selected>Item2</option>
<option value = "4">Item3</option>
<option value = "8">Item4</option>
</select>
</body>
</html>
Edition for selecting multiple items:
well, if you want to accumulate items you can assign binary IDs to each product and then you can extract all the selected products from the total. for example, if the total is: 7 you can easily translate it to a binary string "111" which means they selected items 1,2,4. Sounds a bit crazy, I know, just an idea ;)

Related

Find Options text in Dropdown and set selected and change text

with vanilla javascript I'd like to loop through my dropdown, and change the selected one, and then change the text that is displayed. I have it selecting, but I'm not getting the object name correct to change the optionText? of the item.
var textToFind = 'LdapUsers';
var dd = document.getElementById('membershipProvider');
for (var i = 0; i < dd.options.length; i++) {
if (dd.options[i].text === textToFind) {
dd.selectedIndex = i;
i.options.text = "Edgewood Login"; //This is WRONG
break;
}
}
guidance is appreciated.
You can use a querySelector and a selector to access it without a loop.
v = "222";
selProvider = document.querySelector("#membershipProvider option[value='" + v + "']");
if (selProvider) {
selProvider.text = "CHANGED!";
selProvider.selected = true;
}
<select id="membershipProvider">
<option value='111'>AAA</option>
<option value='222'>BBB</option>
</select>
You need to modify the option at that index. Right now you are trying to modify the index itself.
should be:
dd.options[i].text
not
i.options.text
var textToFind = 'LdapUsers';
var dd = document.getElementById('membershipProvider');
for (var i = 0; i < dd.options.length; i++) {
if (dd.options[i].text === textToFind) {
dd.selectedIndex = i;
dd.options[i].text = "Edgewood Login"; //This is WRONG
break;
}
}
<select id="membershipProvider">
<option value="cifs">CIFS</option>
<option value="LdapUsers">LdapUsers</option>
<option value="nfs">NFS</option>
<option value="test">Test</option>
</select>
You should use
dd.options[i].text = "Edgewood Login";
just like when checking for its value

Loop through a data array variable and select items from multi-select dropdown

Created a multi-select dropdown, when I click on any of the options I have a input field which stores the values in a textbox. When the page reloads- I want to reselect the values in the multi-select drop down. The text box keeps its values so i was hoping to loop through this if i put it in an array.
E.g. Text contains: "cheese,mozarella"
It is important to only check the items that have the value in the textbox
Jquery:
document.getElementById("txt1").value = "cheese,mozarella";
var data = document.getElementById("txt1").value;
var dataarray = data.split(","); //splits values (,)
console.log(dataarray);
var i;
for (i = 0; i < dataarray.length; i++) {
}
HTML:
<input type="text" runat="server" id="txt1" visible="true" value="0" />
<div class="container">
<select id="basic" multiple="multiple">
<option value="cheese">Cheese</option>
<option value="tomatoes">Tomatoes</option>
<option value="mozarella">Mozzarella</option>
<option value="mushrooms">Mushrooms</option>
<option value="pepperoni">Pepperoni</option>
<option value="onions">Onions</option>
</select>
</div>
I have a codeply to demonstrate: https://www.codeply.com/go/mCcxCM0vHs
My aim is to get some jquery code to loop through a dataarray variable and check the box if the value exists and tick it.
This function receives a select and a value and will cycle through the select's options, compare to the given value and mark matching options as selected.
function prepopulateOptions(selectElement, value) {
var options = selectElement.options;
for (var i = 0, numberOfOptions = options.length; i < numberOfOptions; i++) {
if (options[i].value == value) {
options[i].selected = true;
}
}
}
This function clears all selected options.
function clearSelect(selectElement) {
var options = selectElement.options;
for (var i = 0, numberOfOptions = options.length; i < numberOfOptions; i++) {
options[i].selected = false;
}
}
Then tweak your script:
var data = "cheese,mozarella",
dataarray = data.split(","),
selectElement = document.getElementById('basic');
// clear select first
clearSelect(selectElement);
for (var i = 0; i < dataarray.length; i++) {
prepopulateOptions(selectElement, dataarray[i]);
}
Check the fiddle
With jQuery this could be rewritten even easier:
https://jsfiddle.net/rtm0n53b/
Use the localStorage and jQuery.
<script type="text/javascript">
function fnLoadOptions(text){
//--clear selection
$('#basic option').prop("selected", false);
//--load selection
text = text||'';
var items = text.split(',');
for(var i in items) {
$('#basic option[value="'+items[i]+'"]').prop("selected", true);
}
if($.fn.multiselect!=null) {
$('#basic').multiselect('refresh'); //--if using the bootstrap multiselect plugin, then refresh it.
}
}
var key = 'checkedOptions';
//--load previous selection
var previousSelection = localStorage.getItem(key);
fnLoadOptions(previousSelection);
$("#txt1").val(previousSelection);
//--bind to new selection
$('#basic').change(function () {
var v = $('#basic').val();
$("#txt1").val(v);
localStorage.setItem(key,v);
});
$('#txt1').bind("keyup change",function () {
fnLoadOptions($(this).val());
});
</script>

How to update options of select but keep previously selected one as selected?

Here's my try on implementing this:
var select = document.getElementById(key);
var temp = select.value;
select.options.length = 0; // clear out existing items
for (var i = 0; i < data.length; i++) {
select.options.add(new Option(data.Value, data.Key))
}
select.value = temp;
In case of there is no such value anymore I would like to set some default values for selcted option.
This is a simple function called init_select
It clear the selection tag
-remembers the option that was previously selected
if the item that was previously selected item is not in the list of new options..it will select the option that you want (this is the default_opt) parameter
-if the previously item is IN the list it will ignore the default_opt paramater and use the previously selected item.
demo here (previously selected item NOT in list but default_opt is IN list)
function init_select(id,data,default_opt) {
var select = document.getElementById(id);
var temp = select.value;
select.innerHTML="";
for (var i = 0; i < data.length; i++) {
select.options.add(new Option(data[i]))
}
if (data.indexOf(temp) < 0 && data.indexOf(default_opt)>=0 ) {
select.value = default_opt;
console.log('this is select',select.value,default_opt,select);
} else if (data.indexOf(temp) >= 0){
//select.options.add(new Option(temp));
select.value = temp;
console.log(select.value,data.indexOf(temp));
}
}
init_select('key',["New Value", "New Value2", "New Value3", "New Value4"],"New Value2")
<select id="key">
<option>year1</option>
<option>year2</option>
<option>year3</option>
</select>
demo here (previously selected item IN list and default_opt is IN list, default options is ignored and the previously selected item is selected)
function init_select(id,data,default_opt) {
var select = document.getElementById(id);
var temp = select.value;
select.innerHTML="";
for (var i = 0; i < data.length; i++) {
select.options.add(new Option(data[i]))
}
if (data.indexOf(temp) < 0 && data.indexOf(default_opt)>=0 ) {
select.value = default_opt;
console.log('this is select',select.value,default_opt,select);
} else if (data.indexOf(temp) >= 0){
//select.options.add(new Option(temp));
select.value = temp;
console.log(select.value,data.indexOf(temp));
}
}
init_select('key',["New Value", "New Value2", "New Value3", "New Value4","year1"],"New Value2")
<select id="key">
<option>year1</option>
<option>year2</option>
<option>year3</option>
</select>
Your idea of getting the value of select and resetting it was right. You can achieve your wanted result with jQuery like this.
Note that if the old value is not available, select's value will be set to null.
$("button").on("click", function() {
var def = "4. Option";
var temp = $("select").val();
var select = $("select");
select.empty();
for (i = 2; i <= 10; i++) {
$("<option>").text(i + ". Option").appendTo(select);
}
select.val(temp);
if (select.val() == null)
select.val(def);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option>1. Option</option>
<option>2. Option</option>
<option>3. Option</option>
<option>4. Option</option>
<option>5. Option</option>
</select>
<button>Clear and Fill Select</button>

listbox select count not work dont work

I recently trying to make a form with multiple select box. When someone select the options the number of selected options will be display on another text. I'm a beginner in JavaScript.
The function is called, but it doesn't count the number of the selected options.
<select name="element_17_1[ ]"
size="7" multiple="multiple"
class="element select medium"
id="element_17_1[ ]"
onfocus="selectCount(this.form);"
onClick="selectCount(this.form);"
>
<option value="Opt1">Opt1</option>
<option value="Opt2">Opt2</option>
<option value="Opt3">Opt3</option>
<option value="Opt4">Opt4</option>
<option value="Opt5">Opt5</option>
<option value="Opt6">Opt6</option>
<option value="Opt7">Opt7</option>
</select>
and this is the function I tried in the <head>
function selectCount(f) {
var selObj = myForm.elements['element_17_1[]'];
var totalChecked = 0;
for (i = 0; i < selObj.options.length; i++) {
if (selObj.options[i].selected) {
totalChecked++;
}
}
f.element_9.value = totalChecked;
}
You're trying to get an element named element_17_1[], but your select box is named element_17_1[ ]. JavaScript just sees the name as a bunch of characters, and that space makes a difference.
In your HTML you have:
> <select name="element_17_1[ ]"
> size="7" multiple="multiple"
> class="element select medium"
> id="element_17_1[ ]"
> onfocus="selectCount(this.form);"
> onClick="selectCount(this.form);"
> >
Note that in the listener, this references the element itself, so just pass that:
onfocus="selectCount(this);"
onClick="selectCount(this);"
So a reference to the element is passed directly to the function, which can be:
function selectCount(selObj) {
// The following line isn't needed now
// var selObj = myForm.elements['element_17_1[]'];
var totalChecked = 0;
for (i = 0; i < selObj.options.length; i++) {
totalChecked += selObj.options[i].selected? 1 : 0;
}
// The next line needs the form, so
selObj.form.element_9.value = totalChecked;
}
Now you don't care what the select element is called. :-)
Edit
To click element_9 you might do:
<input name="element_9" onclick="
this.value = selectCount(this.form['element_17_1[ ]']);
">
Then the function is modified to:
function selectCount(selObj) {
var totalChecked = 0;
for (i = 0; i < selObj.options.length; i++) {
totalChecked += selObj.options[i].selected? 1 : 0;
}
return totalChecked;
}
Enough homework for now. ;-)
Change your select's name name="element_17_1"and id id="element_17_1" and in also you don't have myForm in your function so var selObj = myForm.elements['element_17_1']; should be var selObj = f.elements['element_17_1']; and also you can use only on event as follows
onChange="selectCount(this.form);"
instead of
onfocus="selectCount(this.form);"
onClick="selectCount(this.form);"
Complete function:
function selectCount(f) {
var selObj = f.elements['element_17_1'];
var totalChecked = 0;
for (i = 0; i < selObj.options.length; i++) {
if (selObj.options[i].selected) {
totalChecked++;
}
}
f.element_9.value = totalChecked;
}
Update:
For your php scriptyou can keep your select's name name="element_17_1[]" and so in the function it should be var selObj = f.elements['element_17_1[]']; but without space like[ ]
DEMO.

Setting One Drop Down after Selecting from Another

I have a couple select elements:
<select name="empID" onchange='setSupervisor(this);'>
<option value="111" sid="222">Eric Employee</option>
...
</select>
<select name="supervisorID">
<option value="333">Susie Supervisor</option>
<option value="222">Stan Supervisor</option>
</select>
And a javascript function:
function setSupervisor(sender)
{
??
}
How can I set the supervisor dropdown after the user selects from the employee dropdown? The tricky part here (at least to me) is having to use a custom sid and not the value from the employee dropdown.
function setSupervisor(sender) {
var selectedOption = sender.getElementsByTagName("option")[sender.selectedIndex];
var sid = selectedOption.getAttribute("sid");
var supervisorSelect = document.getElementsByName("supervisorID")[0];
for (var i = 0, len = supervisorSelect.options.length, option; i < len; ++i) {
option = supervisorSelect.options[i];
if (option.value == sid) {
option.selected = true;
return;
}
}
}
Try this:
var empID = document.getElementsByName("empID").item(0);
var supervisorID = document.getElementsByName("supervisorID").item(0); //This becomes a bit easier if you set an ID as well as a name in your HTML
var index = empID.selectedIndex;
var sid = empID.options[index].getAttribute("sid");
for(var i=0; i<supervisorID.options.length; i++)
{
if(supervisorID.options[i].value == sid)
{
supervisorID.selectedIndex = i;
break;
}
}

Categories