Get first value of selected items from a multiple select in JavaScript? - javascript

I have this code to get the text of the selected option from a in JavaScript:
form_name.select_name.options[form_name.select_name.selectedIndex].text
For example, with
<select>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
When user selects 3, the code would return 3.
My question is, when it's a multiple select such as:
<select multiple="multiple">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
How to return the text of the first selected item in JavaScript? For example, when 2 and 3 are selected, it would return 2.
Any help would be appreciated. Thanks!

see below
<html>
<body>
<form name="myForm">
<select name="myOption" multiple>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
<BR><BR>
<input type=submit value="Print First" onClick="printMe()">
<input type=submit value="Print All" onClick="printAll()">
</body>
<script>
function printMe() {
alert ("Selected option is " + myForm.myOption.value);
}
function printAll() {
var str="",i;
for (i=0;i<myForm.myOption.options.length;i++) {
if (myForm.myOption.options[i].selected) {
str = str + i + " ";
}
}
alert("Options selected are " + str);
}
</script>
</html>
Hope this is what you want...
I have also provided print all and print first option...
Good Luck

You can do it like so with jQuery:
$('select option:selected').first().text()

Something like this should do the job, and is easily modified to get all values, or a specific index.
var selected = ''; // make this into an array to get all / specific value
var mySelect = form_name.select_name;
while(mySelect.selectedIndex != -1)
{
if(mySelect.selectedIndex != 0)
{
selected = mySelect.options[mySelect.selectedIndex].text; // change this to selected.push(...) for all/specific values
}
}
if (selected.length)
{
// at least one thing was selected, have fun
}

HTML
<select id="your-select" multiple="multiple">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
JavaScript
function getFirstSelected(yourSelectId)
{
var yourSelect = document.getElementById(yourSelectId);
var optionLength = yourSelect.options.length;
for (i = 0; i < optionLength; i++) {
var option = yourSelect.options[i];
if (option.selected) {
return option.value;
}
}
return "";
}
Usage
var firstSelectedOption = getFirstSelected("your-select");
Edit
Just realized that this will give you the first selected value and the function is not needed
var firstSelectedOption = document.getElementById("your-select").value;

Related

prevent options from being selected multiple times

I have a form that contains 5 select elements and each one has the same options as the others, now I want each option to be selected only once so i need the code to achieve the following:
when a user select some option in one of the select elements that option should be deleted or disabled in the other select elements
when the user change his selection the old option should be added again to the other select elements or re-enabled so that the user can select it in another select
I've achieved both of these but my code only works for 2 selects but if i add more selects when the user change the select number 3 or higher the old options will be enabled in lower selects
My code:
<!DOCTYPE html>
<html>
<head>
<script>
function updateDepartments2(event){
var selectNodes = document.getElementsByClassName("choice");
for (node of selectNodes){
if (node !== event.target){
for (child of node){
if (child.index != event.target.selectedIndex || child.index == 0){
var disabledState = ""
}else{
var disabledState = "disabled"
}
node[child.index].disabled = disabledState
}
if (node.selectedIndex == event.target.selectedIndex)
{
node.selectedIndex = 0
}
}
}
}
</script>
</head>
<body>
Person Number 1
<select id="choice1" name="choice1" class="choice">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br/>
Person Number 2
<select id="choice2" name="choice2" class="choice">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br/>
Person Number 3
<select id="choice3" name="choice3" class="choice">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<script type="text/javascript">
var selectNodes = document.getElementsByClassName("choice");
for (node of selectNodes){
node.onchange=updateDepartments2
}
</script>
</body>
</html>
First add all the selected options from all the checkboxes in an array.
Then traverse every option in other select box and see if value exists.
Here's the updated js function for it.
function updateDepartments2(event) {
var selectNodes = document.getElementsByClassName("choice");
var x = [];
for (node of selectNodes) {
var opt = node.options[node.selectedIndex].value;
x.push(opt);
}
for (node of selectNodes) {
if (node !== event.target) {
for (child of node) {
if (x.includes(String(child.index))) {
var disabledState = "disabled"
} else {
var disabledState = ""
}
node[child.index].disabled = disabledState
}
if (node.selectedIndex == event.target.selectedIndex) {
node.selectedIndex = 0
}
}
}
}
Updated fiddle
https://jsfiddle.net/se1dofzb/1/
Update 2 :
I have reworked your function from scratch and please check for any bugs or clarification needed.
function updateDepartments2(event) {
var selectNodes = document.getElementsByClassName("choice");
var x = [];
for (var node of selectNodes) {
if (node.selectedIndex != 0)
x.push(node.selectedIndex);// Add index of all selected elements
}
for (var node of selectNodes) {
for (var child of node) {
//Traverse all option in every select box
var disabledState;
if (x.includes(child.index)) {
//If it is selected, disable it
disabledState = "disabled"
} else {
disabledState = ""
}
node[child.index].disabled = disabledState
}
}
}
Call the function on change of the select and get the option index. Get all the select elements and disable the selected option in the select elements
function a(e)
{
console.log(e.selectedIndex)
var k=document.querySelectorAll('select')
for(let i=0;i<k.length;i++)
{
if(k[i]!=e)
k[i].options[e.selectedIndex].setAttribute("disabled","disabled")
}
}
function d()
{
var k=document.querySelectorAll('select')
for(let i=0;i<k.length;i++)
{
var c=k[i].querySelectorAll('option');
for(let i=0;i<c.length;i++)
c[i].removeAttribute("disabled")
}
}
<!DOCTYPE html>
<html>
<body>
Person Number 1
<select id="choice1" name="choice1" class="choice" onchange="a(this)">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br/>
Person Number 2
<select id="choice2" name="choice2" class="choice" onchange="a(this)">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br/>
Person Number 3
<select id="choice3" name="choice3" class="choice" onchange="a(this)">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br>
<input type="button" onclick="d()" value="Reset">
</body>
</html>

Change paragraph after selecting value in dropbox in js

I have a form with dropbox with a few options.
I want to change a paragraph according to the selected value in the dropbox, i.e. the selected value will replace the paragraph.
For ex. I have:
<select name="howmanyno1" size=1>
<option value=2 selected>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
</select>
//somewhere below
<p>number</p>`
I need the text "number" be replaced after selecting a value from the dropbox, with the value selected (2,3,4 or 5).
How should I do this?
Thanks.
<select onchange="myFunction()" name="howmanyno1" id="mySelect">
<option value=2 selected>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
</select>
<p id="demo">number</p>`
<script>
function myFunction() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
</script>
<select name="howmanyno1" id="selectDiv" size=1 onchange="changePara()">
<option value=2 selected>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
</select>
//somewhere below
<p id="changed">number</p>
js code
function changePara(){
var val = document.getElementById("selectDiv").value;
if(val == 2){
document.getElementById("changed").innerHTML = "something";
}
else if(val == 3){
document.getElementById("changed").innerHTML = "something else";
}
// and so on
}
A jQuery based solution
Add an id to your <p> element
<p id="para">number</p>
Use jQuery to select the <select> box
let select = $('select[name="howmanyno1"]')
Create a function for updating the text in <p>
let updateText = function(e) {
$('#para').text("Selected item: " + select.val())
}
And then make the select box listen to the change event
select.on('change', updateText)
I hope this solution will be usefull
var textBlocks = new Array(
'Select from the list to change this box',
'Text block two',
'Text block three');
function changeText(elemid) {
var ind = document.getElementById(elemid).selectedIndex;
document.getElementById("display").innerHTML=textBlocks[ind];
}
</head><body>
<select id="dropDown" onChange="changeText('dropDown');">
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3</option>
</select><br>
<div id="display">Select from the list to change this box</div>
</body></html>

how to get a value from option when select (this code working for chrome)

how to get value from option
<script>
function usgsChanged(el) {
window["display_" + el.options[el.selectedIndex].value]();
}
function display_1() {
//how to get value from option
}
</script>
how to get value from option when select
<select onchange="usgsChanged(this);">
<option value="1">1</option>
<option value="2">2</option>
<option value="">more</option>
<option value="">more</option>
<option value="">more</option>
</select>
<script>
function usgsChanged(option) {
var value = option.value; //The value now resides in this variable
}
</script>
<select onchange="usgsChanged(this);">
<option value="1">1</option>
<option value="2">2</option>
<option value="">more</option>
<option value="">more</option>
<option value="">more</option>
</select>
try something like this
$('#idOfSelectTag').change(function(){
var value = $(this).val();
alert(value);
});
Try looking at internet before sanding a question. For example here.
Try this:
<script type="text/javascript">
function usgsChanged(el) {
var index = el.selectedIndex;
var selectOptions = el.options;
var optionValue = selectOptions[index].value;
var optionText = selectOptions[index].text;
alert("Value is " + optionValue + " and text is " + optionText );
}
</script>
And HTML:
<select onchange="usgsChanged(this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="">more</option>
<option value="">more</option>
<option value="">more</option>
</select>

Display all selected value of multiple drop down list

Below is what I have...
<html>
<body>
<form name="myForm">
<select name="myOption" multiple>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
<BR><BR>
<input type=submit value="Print First" onClick="printMe()">
<input type=submit value="Print All" onClick="printAll()">
</body>
<script>
function printMe() {
alert ("Selected option is " + myForm.myOption.value);
}
function printAll() {
var str = "";
// what should I write here??
alert("Options selected are " + str);
}
</script>
</html>
Please let me know what should I write in printAll() so that I can print all the values that I selected... I know how can I print the first selected value...
how about this??
function printAll() {
var str="",i;
for (i=0;i<myForm.myOption.options.length;i++) {
if (myForm.myOption.options[i].selected) {
str = str + i + " ";
}
}
alert("Options selected are " + str);
}
Good Luck!!!
You can do something like this:
function printAll() {
var obj = myForm.myOption,
options = obj.options,
selected = [], i, str;
for (i = 0; i < options.length; i++) {
options[i].selected && selected.push(obj[i].value);
}
str = selected.join();
// what should I write here??
alert("Options selected are " + str);
}
Demo: http://jsfiddle.net/n3cXj/1/
I would use jquery as it's easier
JQuery:
$("myOption:selected").each(function () {
alert($(this).text());
});
http://jsfiddle.net/XBDmU/2/
var selected = [];
$("#Mymutiple option").each(function(){
$(this).click(function(evt){
myvar = $(this).val();
if (evt.ctrlKey){
if(jQuery.inArray(myvar, selected) >-1){
selected = jQuery.grep(selected , function(value) {
return value != myvar;
});
}
else{
selected.push(myvar);
}
}
else{
selected = [];
selected.push(myvar);
}
});
})
$("#printMe").click(function(){
alert("First selected is:" + selected[0]);
return false;
});
$("#printAll").click(function(){
alert("Options selected are :" + selected);
return false;
});
html:
<form name="myForm">
<select name="myOption" id="Mymutiple" multiple>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
<BR><BR>
<input type="submit" value="Print First" id="printMe">
<input type="submit" value="Print All" id="printAll">
This will help you. It's in pure js. no jquery, mootools...
<!DOCTYPE html>
<html>
<body>
<script>
function get(){
var str="",i;
for (i=0;i<asa.cars.options.length;i++) {
if (asa.cars.options[i].selected) {
str += asa.cars.options[i].value + ",";
}
}
if (str.charAt(str.length - 1) == ',') {
str = str.substr(0, str.length - 1);
}
alert("Options selected are " + str);
}
</script>
<form name="asa">
<select name="cars" id="combo" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input type="button" onclick="get()">
</form>
<p>Hold down the Ctrl (windows) / Command (Mac) button to select multiple options.</p>
</body>
</html>
In angular 4, instead of using angular multi-select dropdown I used the normal one.
Following is the code.
HTML file:
<select [ngModel]="DataValue" (change)="selectChangeHandler($event)"
id="multiple-select" name="multiple-select" class ="form-control" multiple>
<option *ngFor="let ref of Data" [value]="ref['title']">
{{ref['title']}}
</option>
</select>
Ts file:
selectChangeHandler (event: any) {
let oldvalue;
let mergedValue = "";
for ( let index = 0 ; index < event.currentTarget.selectedOptions.length; index++)
{
oldvalue = event.currentTarget.selectedOptions[index].value.replace(/["']/g, "");
oldvalue = oldvalue.split(': ')[1];
if (index ==`enter code here`= 0)
{ mergedValue += oldvalue; }
else
{ mergedValue += ", " + oldvalue; }
}
console.log(mergedValue);
}
Comments:
Using event.currentTarget.selectedOptions[index].value you can get multiple selected values of multi-select dropdown. In my case, mergedValue gives me proper multiple selected values.
I have used split and replace to format the string obtained as I wanted it common separated.
I hope this can help someone.

Javascript Get Values from Multiple Select Option Box

This one is driving me nuts. It’s got to be something simple and stupid that I am overlooking.
I have a multiple select box in a form. I am just trying to get the values that are selected. In my loop, if I use alert then I have no problem. As soon as try to concatenate the values I get the error ‘SelBranch[...].selected' is null or not an object
<form name="InventoryList" method="post" action="InventoryList.asp">
<select name="SelBranch" class="bnotes" size="5" multiple="multiple">
<option value="All">All</option>
<option value="001 Renton">001 Renton</option>
<option value="002 Spokane">002 Spokane</option>
<option value="003 Missoula">003 Missoula</option>
<option value="004 Chehalis">004 Chehalis</option>
<option value="005 Portland">005 Portland</option>
<option value="006 Anchorage">006 Anchorage</option>
<option value="018 PDC">018 PDC</option>
</select>
<input type="button" name="ViewReport" value="View" class="bnotes" onclick="GetInventory();">
</form>
<script language="JavaScript">
function GetInventory()
{
var InvForm = document.forms.InventoryList;
var SelBranchVal = "";
var x = 0;
for (x=0;x<=InvForm.SelBranch.length;x++)
{
if (InvForm.SelBranch[x].selected)
{
//alert(InvForm.SelBranch[x].value);
SelBranchVal = SelBranchVal + "," + InvForm.SelBranch[x].value;
}
}
alert(SelBranchVal);
}
</script>
The for loop is getting one extra run. Change
for (x=0;x<=InvForm.SelBranch.length;x++)
to
for (x=0; x < InvForm.SelBranch.length; x++)
Here i am posting the answer just for reference which may become useful.
<!DOCTYPE html>
<html>
<head>
<script>
function show()
{
var InvForm = document.forms.form;
var SelBranchVal = "";
var x = 0;
for (x=0;x<InvForm.kb.length;x++)
{
if(InvForm.kb[x].selected)
{
//alert(InvForm.kb[x].value);
SelBranchVal = InvForm.kb[x].value + "," + SelBranchVal ;
}
}
alert(SelBranchVal);
}
</script>
</head>
<body>
<form name="form">
<select name="kb" id="kb" onclick="show();" multiple>
<option value="India">India</option>
<option selected="selected" value="US">US</option>
<option value="UK">UK</option>
<option value="Japan">Japan</option>
</select>
<!--input type="submit" name="cmdShow" value="Customize Fields"
onclick="show();" id="cmdShow" /-->
</form>
</body>
</html>
Take a look at HTMLSelectElement.selectedOptions.
HTML
<select name="north-america" multiple>
<option valud="ca" selected>Canada</a>
<option value="mx" selected>Mexico</a>
<option value="us">USA</a>
</select>
JavaScript
var elem = document.querySelector("select");
console.log(elem.selectedOptions);
//=> HTMLCollection [<option value="ca">Canada</option>, <option value="mx">Mexico</option>]
This would also work on non-multiple <select> elements
Warning: Support for this selectedOptions seems pretty unknown at this point
Also, change this:
SelBranchVal = SelBranchVal + "," + InvForm.SelBranch[x].value;
to
SelBranchVal = SelBranchVal + InvForm.SelBranch[x].value+ "," ;
The reason is that for the first time the variable SelBranchVal will be empty

Categories

Resources