How do I find a dropdown value from a dropdown label - javascript

Suppose I have a dropdown as
<select name="Countries" id="Countries">
<option value="USA">United States of America</option>
<option value="AUS">Australia</option>
</select>
Suppose on load of a page I get a sample text as "Australia" then I want to get its respective value as "AUS"
I want to get dropdown value from its label.

Would be something like this:
var e = document.getElementById("Countries");
var str = e.options[e.selectedIndex].value;

Thanks to everyone who helped me here.
Below is the solution to get label from the selected value of a droddown.
var e = document.getElementById("Countries");
var str = e.options[e.selectedIndex].innerHTML;

http://jsfiddle.net/mm18qrwd/1/
I think you don't have index of selected element,
hence,
var value = "";
Array.prototype.slice.
call(document.
getElementById("Countries").
options).
forEach(function(option){
if(option.text == "Australia") {
value = option.getAttribute("value")
}
})
alert(value);

if you are using JQuery, this code $('#Countries').val() will return what you want.

Related

Retrieve value from an HTML drop down into a Javascript

I am attempting to retrieve the results of my two drop down bars on my validation1.html script so I can determine if they have made a selection yet or not, giving a result of true or false. I am having a tough time as I don't have much experience with javascript, any help is greatly appreciated!
function validate1() {
valCheck3 = true;
var resultSelect = SelectCheck(document.forms["contact information"] ["gender"].value);
var image3 = getImage(true, "gender");
var labelGender = getNotification3(Boolean(resultSelect), "gender");
document.getElementById("Gender").appendChild(image3);
document.getElementById("Gender").appendChild(labelGender);
}
(This is only a snippet of code but,) but so far it seems to not be giving out any results.
This can help you
https://jsfiddle.net/af5nhx91/
<select id="testytest" name="testytest">
<option value ='option one'> option one </option>
<option value = 'option two'> option two </option>
</select>
var value = document.getElementById('testytest').value;
you can use .value function as this
var e = document.getElementById("dropdownID");
var strUser = e.options[e.selectedIndex].value;

There is a way to get all the option values in the SELECT TAG without an ID?

do you know if there is a way to take all the values in the OPTION VALUE included in a SELECT?
i Will show you an example, I have this code:
<SELECT onChange="chData(this,this.value)">
<OPTION VALUE=MIPS1 >MIPS
<OPTION VALUE=MSU1 >MSU
<OPTION VALUE=PERCEN1 >% CEC
<OPTION VALUE=NUMGCP1 >nCPU
</SELECT>
I only know the first value which is MIPS1, and I need to take the other values. The is a way to write that if I know the first MIPS1 I will search for the other values Included from the ?
Thanks in advance :)
You can get the <select> element that has an option with a specific value using something like this:
const select = document.querySelector('option[value=MIPS1]').closest('select');
Once you have the <select> element you can retrieve it's options using something like this:
const options = select.querySelectorAll('option');
Or:
const options = select.options;
As #charlietfl mentioned, .closest is not supported by all browsers, instead of that, you could use .parentElement.
jQuery version
var opt = "MIPS1";
const $sel = $("option[value='"+opt+"']").parent()
const options = $("option",$sel).map(function() { return this.value }).get()
console.log(options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<SELECT onChange="chData(this,this.value)">
<OPTION VALUE=MIPS1>MIPS
<OPTION VALUE=MSU1>MSU
<OPTION VALUE=PERCEN1>% CEC
<OPTION VALUE=NUMGCP1>nCPU
</SELECT>
The example below shows how you can do this. The Jquery is fully commented.
Let me know if it isn't what you were hoping for.
Demo
// Create array
var options = [];
// Load option value you're looking for into a variable
var search_term = "MIPS1";
// Find option with known value, travel up DOM tree to select and then find all options within it
$("option[value='" + search_term + "']").closest("select").find("option").each(function() {
// Add values to array
options.push($(this).val());
});
// Print the array
console.log(options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<SELECT onChange="chData(this,this.value)">
<OPTION VALUE=MIPS1>MIPS
<OPTION VALUE=MSU1>MSU
<OPTION VALUE=PERCEN1>% CEC
<OPTION VALUE=NUMGCP1>nCPU
</SELECT>
I think it is a bad idea not to give id to your html element in the first place, however if you need to do it that way, then the code below assumes you have only one select tag on your page.
let select = document.querySelector('select');
options = select.childNodes.filter((c) => c.tagName==='OPTION')
.map((o) => o.value);
console.log(options)
This will help you get: selected value, selected text and all the values in the dropdown.
$(document).ready(function(){
$("button").click(function(){
var option = $('option[value="MIPS1"]');
var select = option.parent();
var value = $(select).find(":selected").val();
var optionName = $(select).find(":selected").text();
var result = "value = "+value+"\noption name = "+optionName+"\nall values = ";
$(select).each(function(){
result+=($(this).text()+" ");
});
console.log(result);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option value=MIPS1 >MIPS</option>
<option value=MSU1 >MSU</option>
<option value=PERCEN1 >% CEC</option>
<option value=NUMGCP1 >nCPU</option>
</select>
<button>click</button>

How get the Value of DropDown in TypeScript

I have a drop down list in my MVC view as :
<select id="organization" class="create-user-select-half"></select>
I try to get the value of dropdown in Type Script like this:
var e = (<HTMLInputElement>document.getElementById("organization")).value;
but it return empty, this is how I get the textbox value and it is working. Also I tired this code but options and selectedIndex are undefined.
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;
You need to use the HTMLSelectElement instead, but this can be tricky
var e = (document.getElementById("organization")) as HTMLSelectElement;
var sel = e.selectedIndex;
var opt = e.options[sel];
var CurValue = (<HTMLSelectElement>opt).value;
var CurText = (<HTMLSelectElement>opt).text;
You will need to define the value or text though if you want anything back
'<select id="organization" value="ThisIsMyValue">This is my text</select>
Output
CurValue = "ThisIsMyValue"
CurText = "This is my text"
You only need this line of code:
let value = (<HTMLSelectElement>document.getElementById('organization')).value;
This worked for me:
const target = e.target as HTMLSelectElement
console.log("%s is selected", (target[clickedIndex] as HTMLOptionElement).value)
I'm using Angular 9 and the following worked for me:
(document.getElementById("inputCategory") as HTMLSelectElement).value
My suggestion is for you to refactor your statement to:
var e = (document.getElementById("organization") as HTMLSelectElement).value
Happy coding!
Try this
In HTML:
<select #organization (change)="selectOrganization(organization.value)" class="create-user-select-half">
<option *ngFor="let o of organizationList"
[value]="organization.id"
[selected]="organizationFromDB == o.organization_name">
{{ o.organization_name }}
</option>
</select>
In TS:
selectOrganization(id) {
console.log('id', id);
}
You can use the $any typecast function
$any($event.target).value
Which will stop the type checking in the template
In below code updatePageSize takes a number as argument:
<select (change) = "updatePageSize($any($event.target).value)">
<option selected = "true">5</option>
<option>10</option>
<option>20</option>
<option>50</option>
</select>
Credits:https://www.tektutorialshub.com/angular/property-value-does-not-exist-on-type-eventtarget-error-in-angular/

Get data attribute for selected dropdown options

I'm trying to post a custom data attribute on a select box option to a hidden form field.
Here's my html:
<select id="sampleorder" multiple="multiple">
<option value='xxx' data-amount='5'>Name</OPTION>
<option value='xxx' data-amount='15'>Name</OPTION>
<option value='xxx' data-amount='2'>Name</OPTION>
</select>
And jQuery
$('#submit_btn').click(function() {
var options = $('select#sampleorder');
var samplesSelected = options.val();
$('input[name=order]').val(samplesSelected);
$('input[name=quantity]').val(sampleAmount);
});
I'm guessing that my variable "sampleAmount" should look somewhat like this
var sampleAmount = options.val().data("amount");
But it's not giving me the expected results.
What would be a good approach to get the data attribute value per item?
Thanks!
why use jQuery? Just use event.target.options[event.target.selectedIndex].dataset.amount
Try this:
$('#submit_btn').click(function() {
var samplesSelected = $('#sampleorder').val(),
sampleAmount = $('#sampleorder option:selected').data("amount");
$('input[name=order]').val(samplesSelected);
$('input[name=quantity]').val(sampleAmount);
});
In pure vanilla javascript you can use :
var sampleAmount = this.selectedOptions[0].getAttribute('data-amount'));
Example:
function SelectChange(event) {
console.log(event.selectedOptions[0].getAttribute('data-amount'));
}
<select onchange="SelectChange(this)">
<option data-amount="1">one</option>
<option data-amount="2">two</option>
<option data-amount="3">three</option>
</select>
Try this,
HTML
Add id attribute to your select drop down
like
<select id="sampleorder" >
....
SCRIPT
var sampleAmount = $('select#sampleorder option:selected').data("amount");
Fiddle http://fiddle.jshell.net/3gCKH/
Another vanilla JS answer:
var selectContainer = document.getElementById('sampleorder')
var selectedOption = selectContainer.selectedOptions.item()
var amount = selectedOption.getAttribute('data-amount')
I forgot to mention it has to be a multi select box, sorry.
With your help and a brief look into the jQuery documentation I've managed to solve it:
$("select#sampleorderm").change(function () {
var samplesSelected = options.val().join("::");
var samplesAmount = "";
$("select#sampleorderm option:selected").each(function () {
samplesAmount += $(this).data("amount") + " ";
});
$('input[name=sampleorder]').val(samplesSelected);
$('input[name=sampleorderquantity]').val(samplesAmount);
});

Retrieving the value of a specific attribute via javascript for the onChange attribute

Good morning/afternoon,
Not so much a problem but more of a query. If I have the following code to grab hold of the users selection on a drop-down box (see figure 1), how do I also add the ability to also grab the value of a specific attribute? (see figure 2)
Figure 1:
<select onChange="productString(this.value)">
<option selected>Please Choose an Option</option>
<option value="Foo"></option>
</select>
Figure 2:
<select onChange="productString(this)">
<option selected>Please Choose an Option</option>
<option value="Foo" id="Bar"></option>
</select>
If anyone would be so kind as too show me where I am going wrong in figure 2 it would be greatly appreciated.
Thanks in advance,
Dan.
EDIT:::::
Would the following work it collecting the information?
function productString(element) {
var id = element.value;
var name = element.id;
var box = element.class;
}
Just pass though this:
<select onChange="productString(this)">
and then you can get whatever you want:
function productString(element) {
var value = element.value, id = element.id;
// ...
}
Here is a sample jsfiddle.
edit — oops sorry - the element that's being passed through is, in IE everywhere (gee I must be blind), the "select" element, not the "option". Thus:
function productString(element) {
if (element.tagName.toLowerCase() === 'select')
element = element.options[element.selectedIndex];
var id = element.id;
var value = element.value;
// ...
}
Updated jsfiddle.

Categories