Javascript Get Values from Multiple Select Option Box - javascript

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

Related

HTML using a function to write the <options> of a select inside a form

So I have a very complex form that contains selects with the same options that repeat probably around 300 times. The following is a very slimmed down example of that.
<select name="HelmAtt1">
<option value=" | | ">Choose Here</option>
<option value="toughness_pts|implicit_toughness_pts_2|AttributeFlatInt">Toughness</option>
<option value="agility_pts|ar_agility_pts_1|AttributeFlatInt">Agility</option>
</select><input type="number" name="Ha1val" value="0"><br>
Doing it this way is obviously very code intensive and not easily editable.
Is it possible to create a function that will display the options inside of a select for me, so I can end up with something like these two?
<select name="HelmAtt1">
printHTML();
</select><input type="number" name="Ha1val" value="0"><br>
<script>
function printHTML()
{
<option value=" | | ">Choose Here</option>
<option value="toughness_pts|implicit_toughness_pts_2|AttributeFlatInt">Toughness</option>
<option value="agility_pts|ar_agility_pts_1|AttributeFlatInt">Agility</option>
}
</script>
printHTML(HelmAtt1);
<input type="number" name="Ha1val" value="0"><br>
<script>
function printHTML(val)
{
<select name="val">
<option value=" | | ">Choose Here</option>
<option value="toughness_pts|implicit_toughness_pts_2|AttributeFlatInt">Toughness</option>
<option value="agility_pts|ar_agility_pts_1|AttributeFlatInt">Agility</option>
</select>
}
</script>
I'm not sure if its possible and any research I've found doesn't specify this exact problem or doesn't solve the issue so here I am.
IMHO you should do that on the backend layer when you render your template, but here goes a frontend solution:
function addOptions(classname) {
let elements = document.getElementsByClassName(classname);
for (let i=0; i<elements.length; i++){
let option = document.createElement('option');
option.innerText = 'your option';
option.value = 'your value';
elements[i].appendChild(option);
}
}
addOptions('foo');
Foo <select class="foo"></select>
Bar <select class="foo"></select>
Baz <select class="foo"></select>
<html>
<body>
<select name="HelmAtt1" id="select">
</select>
<script>
var html = '<option value="">default</option>';
for (var i = 0; i<10; i++)
{
html += '<option value="' + i + '"';
html += '>' + i + '</option>';
}
document.getElementById('select').innerHTML=html;
</script>
</body>
</html>

Getting the value of a dropdown menu using jQuery

I have added a little drop down menu to a webpage:
function addDropDownMenu() {
var positionMenu = $(
"<form class='drop_down_menu'>" +
"<select name='roles'>" +
"<option value='notSelected'>Not Selected</option>"+
"<option value='relevant'>Relevant</option>"+
"<option value='notRelevant'>Not Relevant</option>" +
"</select>" +
"</form>");
$('#profile-experience .position').prepend(positionMenu)
}
I am trying to get the value of either Relevant or Not Relevant.
However, when I run this code I keep getting an empty string.
var x = $('.drop_down_menu')[0]
// x is the form
$(x).val()
returns ""
What am I missing? Doing wrong?
You could try this:
var selectedValue = $('.drop_down_menu>select').val();
var selectedValue = $('.drop_down_menu>select').val();
console.log('The selected value is: '+ selectedValue);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class='drop_down_menu'>
<select name='roles'>
<option value='notSelected'>Not Selected</option>
<option value='relevant' selected>Relevant</option>
<option value='notRelevant'>Not Relevant</option>
</select>
</form>
$('.drop_down_menu') statement returns a jquery element with the properties and methods corresponding to it, but $('.drop_down_menu')[0] just returns the HTML DOM element.
You have to use value property in order to obtain the value of select element.
console.log($('select')[0].value);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name='roles'>
<option value='notSelected'>Not Selected</option>
<option value='relevant' selected>Relevant</option>
<option value='notRelevant'>Not Relevant</option>
</select>
Your example does not work because you have to use a selector for select element
var x = $('.drop_down_menu > select')[0]
console.log($(x).val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class='drop_down_menu'>
<select name='roles'>
<option value='notSelected'>Not Selected</option>
<option value='relevant' selected>Relevant</option>
<option value='notRelevant'>Not Relevant</option>
</select>
</form>
var _val = $("[name='roles']").val();
console.log(_val);

while loop is not working in javascript code?

In this code I'm trying to generate dynamic text fields based on the input of select field which handled by addInput(divname) function using on change event but the while loop inside addInput function is not working and when i remove while loop its working. i have to generate selected no. of text fields... and also the text fields should change when i select different number...
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="adduniv.php" method="post">
University Name: <input type="text" name="college">
No. of branches:
<div id="dynamicInput">
<select name="branches" id="branches" onchange="if (this.selectedIndex) addInput('dynamicInput');;" ">
<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>
</div>
<script>
var counter = 0;
var limit = 3;
function addInput(divName)
{
var k=parseInt(document.getElementById("branches"));
var newdiv;
while(k>0)
{
newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
k--;
}
}
</script>
<input type="submit" value="submit" />
</form>
</body>
</html>
var k=parseInt(document.getElementById("branches"))
You can't parseInt a DOM element.
Suspect you meant
var k=parseInt(document.getElementById("branches").value,10)
with thanks to the comment from Shikiryu re: specifying the radix explicitly.
document.getElementById("branches") returns a DOM-Node, but what you need to do, is to get the value of this DOM-Node. So try the following to generate k.
var k=parseInt(document.getElementById("branches").value);
change the line
var k=parseInt(document.getElementById("branches"));
to
var k=parseInt(document.getElementById("branches").value);
i think you forgot to add .value to document.getElementById("branches")
parseInt(document.getElementById("branches"));
will result in NaN as far as I can tell. You are trying to parse a whole DOM node as an integer, what did you expect? You might want to get the value property from it:
parseInt(document.getElementById("branches").value, 10);
Ok, I know the problem was solved, but I would try do this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Creating input fields</title>
<script>
function addInput(nr_branches) {
var nCounter = 0;
//-- Cleaning all elements
var divB = document.getElementById('divBranches');
if(divB.hasChildNodes()) {
while(divB.childNodes.length >= 1) {
divB.removeChild(divB.firstChild);
}
}
while(nCounter < nr_branches) {
//-- Create a input field
var input = document.createElement("input");
input.type = 'text';
input.name = 'branche_nr_' + nCounter;
input.placeholder = 'Branche Nr.' + nCounter;
//document.getElementById("divBranches").innerHTML = "<input type='text' name='branche_nr_'"+ nCounter +" placeholder='Branche Nr."+ nCounter +"' />";
document.getElementById('divBranches').appendChild(input);
nCounter++;
}
}
</script>
</head>
<body>
<form name="frm" action="adduniv.php" method="post">
<input type="text" name="college" placeholder="University Name" />
<select name="branches" id="branches" onchange="addInput(this.value)">
<option value="0">-select your branche-</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>
<div id="divBranches"></div>
<input type="submit" value="submit" />
</form>
</body>
</html>

Get first value of selected items from a multiple select in 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;

Using jQuery, how can I store the selected values of a select into an array?

Thanks for reading this.
I would have thought it would be as simple as using the .split function on the select .val(), but I get a js error. This is the code I am using. I will use .each() to loop through the selected items...but would like to understand what I am doing wrong...
If I set opts with a literal..the split works (commented code)
Thanks
<html><head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/JavaScript">
$(function(){
$("#multOpts").bind("click", function() {
// var opts = "OPT1,OPT2,OPT3" ;
var opts = $("#select1").val() ;
$("#text1").val(opts);
});
$("#oneOpt").bind("click", function() {
// var opts = "OPT1,OPT2,OPT3" ;
var opts = $("#select1").val() ;
var optsArray = opts.split(",") ;
$("#text2").val("1st opt: " + optsArray[0]);
});
}); // End eventlistener
</script>
</head><body>
<select id="select1" multiple size="5">
<option value="OPT1">Option 1</option>
<option value="OPT2">Option 2</option>
<option value="OPT3">Option 3</option>
<option value="OPT4">Option 4</option>
<option value="OPT5">Option 5</option>
</select>
<div>
<input id="multOpts" type="button" value="Show Options"/>
<input id="text1" type="text"/>
</div>
<input id="oneOpt" type="button" value="One Option"/>
<input id="text2" type="text"/>
</body></html>
The val() function when there are more than one option selected returns you already an array, you don't need to do the split.
$("#oneOpt").bind("click", function() {
var opts = $("#select1").val();
$("#text2").val("1st opt: " + opts[0]);
});
Since jQuery 1.2, .val() returns array of values is return on multiple select.
var opts = $("#select1").val() || [];
$("#text2").val("values is: " +opts.join(", "));

Categories

Resources