Option label as var in javascript function - javascript

<select id="wbox" name="listbox" size="20"onchange="call(this)">
<optgroup label="Taxes">
<option value="1694" label="DNA-option1"></option>
<option value="1642">RNA-option2</option>
I have a list box that I would like to extract the label of the selected option, and use it in a JavaScript function.
function call(op) {
alert(op.label);
alert(op.name);
alert(op.value);
var x = op.label;
}
However this always returns as label, undefined. I've tried changing the way the option label is written in the html. This might not be the best way to write the java script function. I absolutely cannot use the option value, it is a unique id and used for something else. Any suggestions on what I am doing wrong or a better way to do this?

To get the selected <option>, you need to use the selectedOptions property. This is an array, because <select> tags can (optionally) support multiple selection. This array contains <option> tag objects, so you should be able to get your label using op.selectedOptions[0].textContent.

I guess:
<select id="wbox" name="listbox" size="20" onchange="call(this.selectedOptions)">
<optgroup label="Taxes">
<option value="1694" label="DNA-option1">RNA-option1</option>
<option value="1642" label="DNA-option2">RNA-option2</option>
</select>
<script type="text/javascript">
function call(op){
for(var i=0;i<op.length;i++){
console.log('Label: '+ op[i].getAttribute('label'));
}
}
</script>

Related

Need Help to Scrape a Website [duplicate]

I have a drop-down list with known values. What I'm trying to do is set the drop down list to a particular value that I know exists using jQuery.
Using regular JavaScript, I would do something like:
ddl = document.getElementById("ID of element goes here");
ddl.value = 2; // 2 being the value I want to set it too.
However, I need to do this with jQuery, because I'm using a CSS class for my selector (stupid ASP.NET client ids...).
Here are a few things I've tried:
$("._statusDDL").val(2); // Doesn't find 2 as a value.
$("._statusDDL").children("option").val(2) // Also failed.
How can I do it with jQuery?
Update
So as it turns out, I had it right the first time with:
$("._statusDDL").val(2);
When I put an alert just above it works fine, but when I remove the alert and let it run at full speed, I get the error
Could not set the selected property. Invalid Index
I'm not sure if it's a bug with jQuery or Internet Explorer 6 (I'm guessing Internet Explorer 6), but it's terribly annoying.
jQuery's documentation states:
[jQuery.val] checks, or selects, all the radio buttons, checkboxes, and select options that match the set of values.
This behavior is in jQuery versions 1.2 and above.
You most likely want this:
$("._statusDDL").val('2');
Add .change() to see the option in the dropdown list frontend:
$("._statusDDL").val('2').change();
With hidden field you need to use like this:
$("._statusDDL").val(2);
$("._statusDDL").change();
or
$("._statusDDL").val(2).change();
These solutions seem to assume that each item in your drop down lists has a val() value relating to their position in the drop down list.
Things are a little more complicated if this isn't the case.
To read the selected index of a drop down list, you would use this:
$("#dropDownList").prop("selectedIndex");
To set the selected index of a drop down list, you would use this:
$("#dropDownList").prop("selectedIndex", 1);
Note that the prop() feature requires JQuery v1.6 or later.
Let's see how you would use these two functions.
Supposing you had a drop down list of month names.
<select id="listOfMonths">
<option id="JAN">January</option>
<option id="FEB">February</option>
<option id="MAR">March</option>
</select>
You could add a "Previous Month" and "Next Month" button, which looks at the currently selected drop down list item, and changes it to the previous/next month:
<button id="btnPrevMonth" title="Prev" onclick="btnPrevMonth_Click();return false;" />
<button id="btnNextMonth" title="Next" onclick="btnNextMonth_Click();return false;" />
And here's the JavaScript which these buttons would run:
function btnPrevMonth_Click() {
var selectedIndex = $("#listOfMonths").prop("selectedIndex");
if (selectedIndex > 0) {
$("#listOfMonths").prop("selectedIndex", selectedIndex - 1);
}
}
function btnNextMonth_Click() {
// Note: the JQuery "prop" function requires JQuery v1.6 or later
var selectedIndex = $("#listOfMonths").prop("selectedIndex");
var itemsInDropDownList = $("#listOfMonths option").length;
// If we're not already selecting the last item in the drop down list, then increment the SelectedIndex
if (selectedIndex < (itemsInDropDownList - 1)) {
$("#listOfMonths").prop("selectedIndex", selectedIndex + 1);
}
}
My site is also useful for showing how to populate a drop down list with JSON data:
http://mikesknowledgebase.com/pages/Services/WebServices-Page8.htm
Just an FYI, you don't need to use CSS classes to accomplish this.
You can write the following line of code to get the correct control name on the client:
$("#<%= statusDDL.ClientID %>").val("2");
ASP.NET will render the control ID correctly inside the jQuery.
Just try with
$("._statusDDL").val("2");
and not with
$("._statusDDL").val(2);
After looking at some solutions, this worked for me.
I have one drop-down list with some values and I want to select the same value from another drop-down list... So first I put in a variable the selectIndex of my first drop-down.
var indiceDatos = $('#myidddl')[0].selectedIndex;
Then, I select that index on my second drop-down list.
$('#myidddl2')[0].selectedIndex = indiceDatos;
Note:
I guess this is the shortest, reliable, general and elegant solution.
Because in my case, I'm using selected option's data attribute instead of value attribute.
So if you do not have unique value for each option, above method is the shortest and sweet!!
I know this is a old question and the above solutions works fine except in some cases.
Like
<select id="select_selector">
<option value="1">Item1</option>
<option value="2">Item2</option>
<option value="3">Item3</option>
<option value="4" selected="selected">Item4</option>
<option value="5">Item5</option>
</select>
So Item 4 will show as "Selected" in the browser and now you want to change the value as 3 and show "Item3" as selected instead of Item4.So as per the above solutions,if you use
jQuery("#select_selector").val(3);
You will see that Item 3 as selected in browser.But when you process the data either in php or asp , you will find the selected value as "4".The reason is that , your html will look like this.
<select id="select_selector">
<option value="1">Item1</option>
<option value="2">Item2</option>
<option value="3" selected="selected">Item3</option>
<option value="4" selected="selected">Item4</option>
<option value="5">Item5</option>
</select>
and it gets the last value as "4" in sever side language.
SO MY FINAL SOLUTION ON THIS REGARD
newselectedIndex = 3;
jQuery("#select_selector option:selected").removeAttr("selected");
jQuery("#select_selector option[value='"+newselectedIndex +"']").attr('selected', 'selected');
EDIT: Add single quote around "+newselectedIndex+" so that the same functionality can be used for non-numerical values.
So what I do is actually ,removed the selected attribute and then make the new one as selected.
I would appreciate comments on this from senior programmers like #strager , #y0mbo , #ISIK and others
If we have a dropdown with a title of "Data Classification":
<select title="Data Classification">
<option value="Top Secret">Top Secret</option>
<option value="Secret">Secret</option>
<option value="Confidential">Confidential</option>
</select>
We can get it into a variable:
var dataClsField = $('select[title="Data Classification"]');
Then put into another variable the value we want the dropdown to have:
var myValue = "Top Secret"; // this would have been "2" in your example
Then we can use the field we put into dataClsField, do a find for myValue and make it selected using .prop():
dataClsField.find('option[value="'+ myValue +'"]').prop('selected', 'selected');
Or, you could just use .val(), but your selector of . can only be used if it matches a class on the dropdown, and you should use quotes on the value inside the parenthesis, or just use the variable we set earlier:
dataClsField.val(myValue);
So I changed it so that now it
executes after a 300 miliseconds using
setTimeout. Seems to be working now.
I have run into this many times when loading data from an Ajax call. I too use .NET, and it takes time to get adjusted to the clientId when using the jQuery selector. To correct the problem that you're having and to avoid having to add a setTimeout property, you can simply put "async: false" in the Ajax call, and it will give the DOM enough time to have the objects back that you are adding to the select. A small sample below:
$.ajax({
type: "POST",
url: document.URL + '/PageList',
data: "{}",
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var pages = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$('#locPage' + locId).find('option').remove();
$.each(pages, function () {
$('#locPage' + locId).append(
$('<option></option>').val(this.PageId).html(this.Name)
);
});
}
});
I use an extend function to get client ids, like so:
$.extend({
clientID: function(id) {
return $("[id$='" + id + "']");
}
});
Then you can call ASP.NET controls in jQuery like this:
$.clientID("_statusDDL")
Another option is to set the control param ClientID="Static" in .net and then you can access the object in JQuery by the ID you set.
<asp:DropDownList id="MyDropDown" runat="server" />
Use $("select[name$='MyDropDown']").val().
Just a note - I've been using wildcard selectors in jQuery to grab items that are obfuscated by ASP.NET Client IDs - this might help you too:
<asp:DropDownList id="MyDropDown" runat="server" />
$("[id* = 'MyDropDown']").append("<option value='-1'> </option>"); //etc
Note the id* wildcard- this will find your element even if the name is "ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder1$MyDropDown"
How are you loading the values into the drop down list or determining which value to select? If you are doing this using Ajax, then the reason you need the delay before the selection occurs could be because the values were not loaded in at the time that the line in question executed. This would also explain why it worked when you put an alert statement on the line before setting the status since the alert action would give enough of a delay for the data to load.
If you are using one of jQuery's Ajax methods, you can specify a callback function and then put $("._statusDDL").val(2); into your callback function.
This would be a more reliable way of handling the issue since you could be sure that the method executed when the data was ready, even if it took longer than 300 ms.
<asp:DropDownList ID="DropUserType" ClientIDMode="Static" runat="server">
<asp:ListItem Value="1" Text="aaa"></asp:ListItem>
<asp:ListItem Value="2" Text="bbb"></asp:ListItem>
</asp:DropDownList>
ClientIDMode="Static"
$('#DropUserType').val('1');
In my case I was able to get it working using the .attr() method.
$("._statusDDL").attr("selected", "");
Pure JS
For modern browsers using CSS selectors is not a problem for pure JS
document.querySelector('._statusDDL').value = 2;
function change() {
document.querySelector('._statusDDL').value = 2;
}
<select class="_statusDDL">
<option value="1" selected>A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
<button onclick="change()">Change</button>
If we want to find from the option name and then selected options with the jQuery please see below code:-
<div class="control">
<select name="country_id" id="country" class="required-entry" title="Country" data-validate="{'validate-select':true}" aria-required="true">
<option value=""> </option>
<option value="SA">Saudi Arabia</option>
<option value="AF">Afghanistan</option>
<option value="AR">Argentina</option>
<option value="AM">Armenia</option>
<option value="AW">Aruba</option>
<option value="AU">Australia</option>
<option value="AT">Austria</option>
<option value="IS">Iceland</option>
<option value="IN">India</option>
<option value="ID">Indonesia</option>
<option value="IR">Iran</option>
<option value="IQ">Iraq</option>
<option value="IE">Ireland</option>
<option value="IM">Isle of Man</option>
<option value="IL">Israel</option>
<option value="IT">Italy</option>
<option value="JM">Jamaica</option>
<option value="JP">Japan</option>
<option value="JE">Jersey</option>
<option value="JO">Jordan</option>
<option value="AE">United Arab Emirates</option>
<option value="GB">United Kingdom</option>
<option value="US" selected="selected">United States</option>
</select>
</div>
<script type='text/javascript'>
let countryRegion="India";
jQuery("#country option:selected").removeAttr("selected");
let cValue= jQuery("#country option:contains("+countryRegion+")").val();
jQuery("#country option[value='"+cValue +"']").attr('selected', 'selected');
</script>
I hope this will help!

Get rid of blank entry in select tag

I have a number of items that get their data from a Json object and populate it using angular.
<select ng-model="MyCtrl.cargoList">
<option ng-repeat="cargo in MyCtrl.cargoList">{{ cargo.name }}</option>
</select>
And whenever I load the form, I get something like this in my console:
<select ng-model="MyCtrl.cargoList">
<option value="? object:25 "?></option>
<option value="">Gloves</option>
<option value="">Jacket</option>
<option value="">Shoes</option>
</select>
I can get the values to appear just fine, but I can't seem to get rid of the very first option. I don't mind the select box showing the very first element in the list, but I don't want it to be a blank line. How do I get rid of it?
You need to select 1st option by default on ng-init="MyCtrl.selectedCargo=MyCtrl.cargoList[0].name" & ng-model name should not be same as that of your cargoList.
Markup
<select ng-model="MyCtrl.selectedCargo" ng-init="MyCtrl.selectedCargo=MyCtrl.cargoList[0].name">
<option ng-repeat="cargo in MyCtrl.cargoList" value="cargo.name">{{ cargo.name }}</option>
</select>
Demo Plunkr
Use ngOption <option>
The ngOptions attribute can be used to dynamically generate a list of <option> elements for the <select> element using the array or object obtained by evaluating the ngOptions comprehension expression.
I have used following expression
label for value in array
HTML
<select ng-model="MyCtrl.cargo" ng-options="cargo.name for cargo in MyCtrl.cargoList">
</select>
and In your controller set model value as first element of list
this.cargo = this.cargoList[0]
Also note: You can use MyCtrl.cargoList as model as well as array So you should use another variable to hold the model value.
Use ng-options instead of ng-repeat
<select ng-model="MyCtrl.selectedListItem" ng-options="cargo for cargo in MyCtrl.cargoList"></select>
You can fine tune the labels/values further if you like, check the documentation here - https://docs.angularjs.org/api/ng/directive/ngOptions
You can ng-init, or set the first value to defualt, something like
MyCtrl.selectedListItem = MyCtrl.cargoList[0]
So if you want a function to detect you have changed the value of the select you would use ng-change like so :
<select ng-model="MyCtrl.selectedListItem" ng-options="cargo for cargo in MyCtrl.cargoList" ng-change="selectChanged"></select>
In your controller
$scope.selectChanged = function(){
//apply your logic
};

Select latest selected value of a dropdown

Is there a way to select the latest user's selected value of a dropdown?
Eg:
<select id="data" name="data" class="data" multiple="multiple">
<option value="100">foo</option>
<option value="101">bar</option>
<option value="102">bat</option>
<option value="103">baz</option>
</select>
If I use something like the bellow example, what I get is the last index, but it's not what I want.
var latest_value = $("option:selected:last",this).val();
What I want is something like: if you select "bar", I get 101, if you select "foo" I get 101 instead of 100.
OBS: all my examples are considering that the user is selecting multiple values, not just one.
Use this simple js code:
var is_now_selected = document.getElementById('data').value;
// or with jQuery
var is_now_selected = $('#data').val()
Maybe you don't know that the option-value accually is the value of the select. If you click <option value="something"> which is inside a <select name="select_me">, then this select will have the value of the selected option - in this case - "select_me".
You can write this code. It may help you.
Please let me know if you have anymore problem.
$("#data").change(function () {
alert($("#data").val());
});

Dynamic select option list resetting to first value

I've got a dynamically populated <select> list, where the first option is created by HTML and PHP when the page first loads, but when you drop down, javascript populates a list of additional options. However, when I select an option and remove focus, it is reset to the original selected option. I'm pretty sure that what I'm doing is not getting saved, but I'm not sure how to fix it.
Here's the HTML, which works fine:
<select name="select1" id="select1" onfocus= "checkSelect(this.value)">
<option value ="XXX">XXX</option>
</select>
The checkSelect() function does a bunch of stuff, but then it ends as follows:
//do a bunch of stuff, ending in populating the 'legal' array.
document.input_form.select1.options.length=1;
//which I think is actually redundant
for (i=0; i < legal.length; i++)
{
document.input_form.select1.options[i+1]=new
Option(legal[i], legal[i], false, false);
}
Am I missing something necessary to make the option persist on the page?
The only reason I could think of such a behavior would be select1 wrapped into unclosed tag <label>, for example:
<label>label <!--may be missing </label> here -->
<select name="select1" id="select1" onfocus="checkSelect(this.value)">
<option value ="XXX">XXX</option>
</select> <!--may be missing </label> here -->

jQuery get specific option tag text

All right, say I have this:
<select id='list'>
<option value='1'>Option A</option>
<option value='2'>Option B</option>
<option value='3'>Option C</option>
</select>
What would the selector look like if I wanted to get "Option B" when I have the value '2'?
Please note that this is not asking how to get the selected text value, but just any one of them, whether selected or not, depending on the value attribute. I tried:
$("#list[value='2']").text();
But it is not working.
If you'd like to get the option with a value of 2, use
$("#list option[value='2']").text();
If you'd like to get whichever option is currently selected, use
$("#list option:selected").text();
It's looking for an element with id list which has a property value equal to 2.
What you want is the option child of the list:
$("#list option[value='2']").text()
This worked perfectly for me, I was looking for a way to send two different values with options generated by MySQL, and the following is generic and dynamic:
$(this).find("option:selected").text();
As mentioned in one of the comments. With this I was able to create a dynamic function that works with all my selection boxes that I want to get both values, the option value and the text.
Few days ago I noticed that when updating the jQuery from 1.6 to 1.9 of the site I used this code, this stop working... probably was a conflict with another piece of code... anyway, the solution was to remove option from the find() call:
$(this).find(":selected").text();
That was my solution... use it only if you have any problem after updating your jQuery.
Based on the original HTML posted by Paolo I came up with the following.
$("#list").change(function() {
alert($(this).find("option:selected").text()+' clicked!');
});
It has been tested to work on Internet Explorer and Firefox.
$("#list option:selected").each(function() {
alert($(this).text());
});
for multiple selected value in the #list element.
If there is only one select tag in on the page then you can specify select inside of id 'list'
jQuery("select option[value=2]").text();
To get selected text
jQuery("select option:selected").text();
Try the following:
$("#list option[value=2]").text();
The reason why your original snippet wasn't working is because your OPTION tags are children to your SELECT tag, which has the id list.
This is an old Question which has not been updated in some time the correct way to do this now would be to use
$("#action").on('change',function() {
alert($(this).find("option:selected").text()+' clicked!');
});
I hope this helps :-)
I wanted to get the selected label. This worked for me in jQuery 1.5.1.
$("#list :selected").text();
$(this).children(":selected").text()
You can get selected option text by using function .text();
you can call the function like this :
jQuery("select option:selected").text();
$("#list [value='2']").text();
leave a space after the id selector.
While "looping" through dynamically created select elements with a .each(function()...): $("option:selected").text(); and $(this + " option:selected").text() did not return the selected option text - instead it was null.
But Peter Mortensen's solution worked:
$(this).find("option:selected").text();
I do not know why the usual way does not succeed in a .each() (probably my own mistake), but thank you, Peter. I know that wasn't the original question, but am mentioning it "for newbies coming through Google."
I would have started with $('#list option:selected").each() except I needed to grab stuff from the select element as well.
Use:
function selected_state(){
jQuery("#list option").each(function(){
if(jQuery(this).val() == "2"){
jQuery(this).attr("selected","selected");
return false;
}else
jQuery(this).removeAttr("selected","selected"); // For toggle effect
});
}
jQuery(document).ready(function(){
selected_state();
});
I was looking for getting val by internal field name instead of ID and came from google to this post which help but did not find the solution I need, but I got the solution and here it is:
So this might help somebody looking for selected value with field internal name instead of using long id for SharePoint lists:
var e = $('select[title="IntenalFieldName"] option:selected').text();
A tip: you can use below code if your value is dynamic:
$("#list option[value='"+aDynamicValue+"']").text();
Or (better style)
$("#list option").filter(function() {
return this.value === aDynamicValue;
}).text();
As mentioned in jQuery get specific option tag text and placing dynamic variable to the value
I needed this answer as I was dealing with a dynamically cast object, and the other methods here did not seem to work:
element.options[element.selectedIndex].text
This of course uses the DOM object instead of parsing its HTML with nodeValue, childNodes, etc.
As an alternative solution, you can also use a context part of jQuery selector to find <option> element(s) with value="2" inside the dropdown list:
$("option[value='2']", "#list").text();
I wanted a dynamic version for select multiple that would display what is selected to the right (wish I'd read on and seen $(this).find... earlier):
<script type="text/javascript">
$(document).ready(function(){
$("select[showChoices]").each(function(){
$(this).after("<span id='spn"+$(this).attr('id')+"' style='border:1px solid black;width:100px;float:left;white-space:nowrap;'> </span>");
doShowSelected($(this).attr('id'));//shows initial selections
}).change(function(){
doShowSelected($(this).attr('id'));//as user makes new selections
});
});
function doShowSelected(inId){
var aryVals=$("#"+inId).val();
var selText="";
for(var i=0; i<aryVals.length; i++){
var o="#"+inId+" option[value='"+aryVals[i]+"']";
selText+=$(o).text()+"<br>";
}
$("#spn"+inId).html(selText);
}
</script>
<select style="float:left;" multiple="true" id="mySelect" name="mySelect" showChoices="true">
<option selected="selected" value=1>opt 1</option>
<option selected="selected" value=2>opt 2</option>
<option value=3>opt 3</option>
<option value=4>opt 4</option>
</select>
You can get one of following ways
$("#list").find('option').filter('[value=2]').text()
$("#list").find('option[value=2]').text()
$("#list").children('option[value=2]').text()
$("#list option[value='2']").text()
$(function(){
console.log($("#list").find('option').filter('[value=2]').text());
console.log($("#list").find('option[value=2]').text());
console.log($("#list").children('option[value=2]').text());
console.log($("#list option[value='2']").text());
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<select id='list'>
<option value='1'>Option A</option>
<option value='2'>Option B</option>
<option value='3'>Option C</option>
</select>
Try this:
jQuery("#list option[value='2']").text()
Try
[...list.options].find(o=> o.value=='2').text
let text = [...list.options].find(o=> o.value=='2').text;
console.log(text);
<select id='list'>
<option value='1'>Option A</option>
<option value='2'>Option B</option>
<option value='3'>Option C</option>
</select>

Categories

Resources