How to get Javascript Select box's selected text - javascript

This things works perfectly
<select name="selectbox" onchange="alert(this.value)">
But I want to select the text. I tried in this way
<select name="selectbox" onchange="alert(this.text)">
It shows undefined.
I found how to use DOM to get text. But I want to do this in this way, I means like using just this.value.

this.options[this.selectedIndex].innerHTML
should provide you with the "displayed" text of the selected item. this.value, like you said, merely provides the value of the value attribute.

In order to get the value of the selected item you can do the following:
this.options[this.selectedIndex].text
Here the different options of the select are accessed, and the SelectedIndex is used to choose the selected one, then its text is being accessed.
Read more about the select DOM here.

Please try this code:
$("#YourSelect>option:selected").html()

Just use
$('#SelectBoxId option:selected').text(); For Getting text as listed
$('#SelectBoxId').val(); For Getting selected Index value

I know no-one is asking for a jQuery solution here, but might be worth mentioning that with jQuery you can just ask for:$('#selectorid').val()

If you want to get the value, you can use this code for a select element with the id="selectBox"
let myValue = document.querySelector("#selectBox").value;
If you want to get the text, you can use this code
var sel = document.getElementById("selectBox");
var text= sel.options[sel.selectedIndex].text;

The question was not for the value but for the text.
Imagine you have something like :
<select name="select">
<option value="1">0.5</option
<option value="2">0.7</option
</select>
And you need to catch the text.
So for me I have tried with html (php), and
this.options[this.selectedIndex].text
(from Delan Azabani) doesn't work but
this.options[selectedIndex].text
work, like this on HTML
<select ... onChange="upTVA(this.options[selectedIndex].text);">
It is still surprising that for a select this.text does not work while this.value works

Related

How to get the value in a select change event in angular2

I want to navigate useing a dynamically generated select drop down.
It doesn't appear I can do that directly, so I'd simply like to make a function call when the select changes.
To do that, I have this:
---In the template---
<select (change)="navSelected($event)">
<option *ngFor="let button of navButtons;"
value="button.route" >{{button.label}}</option>
</select>
suffice it to say that 'navButtons' is an array of objects that have a 'label' field.
---In the class---
navSelected(navName) {
console.log(navName + " Clicked!");
}
This actually works fine.
I got to this point from the great help of Mark Rajcok and his answer in this older question:
How can I get new selection in "select" in Angular 2?
That said, I'd like to be able to pass the selected value in the navSelected() function call. I'm unsure how to do that.
I have tried adding [ngValue]="button" on a wild guess from other searches to the option tag and then referencing the button variable in the (change) event handler (so: (change)="navSelected(button.label)" and other combos, to no avail. I've seen a lot of references to ngModel but they seem old and I'm not entirely sure they apply anymore (and I couldn't get them to work anyway in RC4).
I could probably pull some jquery or whatever out to find the select and get it's value, but that seems very rinky-dink compared to simply being able to call the function correctly.
The value you are looking for is on the $event.target and you can get it with $event.target.value, see my example below.
navSelected($event) {
console.log($event.target.value + " Clicked!");
}
If you are looking to get the selected text of the option you can do this
navSelected($event) {
let selectElement = $event.target;
var optionIndex = selectElement.selectedIndex;
var optionText = selectElement.options[optionIndex];
console.log(optionText + " Clicked!");
}
As a shortcut for #eltonkamami 's answer, you can pass your object like this:
<select (change)="navSelected(navButtons[$event.target.selectedIndex])">
<option *ngFor="let button of navButtons;">{{button.label}}</option>
</select>
And capture it like this:
navSelected(button: [type of navButtons]){
console.log(button);
}
Instead of $event. Try using the below typecast function.
$any($event.target).value
Which will stop the type checking in the template.

jQuery Autopopulate Multiple Select uses text instead of value

I've got a multiple select like this configured to auto-populate:
<select id="multiple-select-box" class="selectivity-input" data-placeholder="Type to search condos" multiple>
<option id="Alabama Grove Terrace" value="Alabama Grove" >Alabama Grove Terrace</option>
<option id="Alden Pines" value="Alden Pines" >Alden</option>
</select>
Upon select I realized the script is submitting the visible Text for each option instead of the value="" for each option chosen.
I tried to change var t=$(this).text(); to var t=$(this).value(); thinking that would grab the value instead of the option text but had the same results. What am I missing?
<script>
$(document).ready(function() {
$("#bySub").submit(function(){
$(".selectivity-multiple-selected-item").each(function(){
var t=$(this).text();
//if()
$(".ml").append("<option selected='selected'>"+t+"</option>");
});
})
$('#multiple-select-box').selectivity();
});
</script>
Ok, so I went to check this selectivity plugin you're using and it converts your select into a series of divs as
<div class="selectivity-results-container">
<div class="selectivity-result-item highlight" data-item-id="Alabama Grove">Alabama Grove Terrace</div>
<div class="selectivity-result-item" data-item-id="Alden Pines">Alden</div>
</div>
you have to change your submit function to get the data-item-id property which corresponds to your original select value like
$("#bySub").submit(function(){
$(".selectivity-multiple-selected-item").each(function(){
var t=$(this).data("item-id");
$(".ml").append("<option selected='selected'>"+t+"</option>");
});
edit
fiddle example
In this line, you are appending options to the select, but you have set no value attribute:
$(".ml").append("<option selected='selected'>"+t+"</option>");
As stated in the comments, the "fetch value" method of a form element in jQuery is:
$(this).val()
You might be confusing it with the JavaScript property:
this.value
...which also works. Both return an array of strings if something is selected and set to "multiple"
To follow up on your comment, I don't see your markup for the selected element with class="ml" thus it's almost impossible to debug why your form isn't submitting the values without seeing the bigger picture (i.e. it may be outside the form element). You could try adding the value property to the select element however jQuery should be able to pick up selected options missing the value property by using the text value instead.

Inserting select box text into database

I know this has been asked before, however I cannot find a solution to my problem.
I have a select box with three options and three values, these values are used to perform some calculations using JS so I cannot change these to match the option text. This is to work out the amount of V.A.T.
My select looks like this:
<select name="tax" id="tax" class="select">
<option value="20">Standard 20%</option>
<option value="0">Zero 0%</option>
<option value="0">Exempt 0%</option>
</select>
Which is fine, however I need to insert the text into the database and not the values, as it needs to be viewed in the backend. I have tried a javascript function to add a hidden input to the select box targeting the option that is selected but that was a bit buggy, and didn't seem right. i was thinking of displaying the text next to the value when it is retrieved from the database, however I wouldn't be able to distinguish from the two 0 amounts.
Could someone please offer some further solutions, best approaches to this.
Many Thanks
You can get the text of the selected option with jQuery as follows:
$("#tax option:selected").text();
You could easily use this within your AJAX request to send the correct value to the database, just assign it to a variable:
var the_text = $("#tax option:selected").text();
Failing that, why not just do the lookup in the JS calculations - it'd make your life so much easier:
<select name="tax" id="tax" class="select">
<option value="standard">Standard 20%</option>
<option value="zero">Zero 0%</option>
<option value="exempt">Exempt 0%</option>
</select>
And your JS could look something like this:
var vat_amount = ($('#tax').val() == 'standard') ? 20 : 0;
You can retrieve the text by JS using the html() function. Or, if you are just using a POST to send the data to the server, try adding both values to the value attribute of the option and split it server side to get the right data.

Jquery Mulitple select field error

I have multiple select field each with multiple options.
So, by using jquery to get the respective selected options content, I would be able to get the selected option content. However, this work for the first select field. But, does not work for others. Others keep referencing the first select field selected options content, instead of it owns. Please guide me! Thanks!
My Select fields
<select id="resource_dd" name="resource_dd">
<option selected="selected" value="nil1">No resources.</option>
<option value="1">Week1</option>
<option value="2">Resource1</option>
</select>
<select id="module_dd" name="module_dd">
<option selected="selected" value="nil2">No restriction.</option>
<option value="1">IT1234</option>
<option value="2">IT2345</option>
</select>
Jquery to retrieve the selected content.
$("#module_dd").change(function ( event ) {
var option = $("this").children();
var module_id = $(option+":selected").val(); //module_id get 'nil1' as content instead of nil2
});
Just try this, it will give you the selected value.
$("#module_dd").change(function ( event ) {
var module_id = $(this).val();
});
First of all, you should be saying $(this) instead of $("this").
Second, $(event.target) is probably more appropriate here.
Third, using .children as in $(event.target).children(":selected") will get you what you want.
This is happening because you are referencing $("#module_dd").
You need to add another function and change that to $("#resource_dd") to get the other select field.
Problem code
var option = $("this").children();
var module_id = $(option+":selected").val();
You can't concat a selector string to a jQ collection object. You need to filter the option collection for those which are selected either by:
var option = $( this ).children(":selected");
Or
var option = $( this ).children();
var module_id = option.filter(":selected").val();
Please see Eli Courtwright's answer, but in addition to that, you should do something like $("select") or $("#module_dd, #resource_dd") to target both select fields.

Determining selected option using jQuery after using get() to retrieve the select

I have used get() to retrieve the first select drop down on the page like so:
styleSelect = jQuery('select').get(0);
And I can do normal things like
jQuery(styleSelect).remove();
To remove the select, but I'm having trouble finding the correct syntax to get the currently selected option's text. I've tried:
jQuery(styleSelect, ':selected').text();
and several variations of this, I think I'm just missing something dumb here.
jQuery('select').val()
should return the value of the currently selected element.
although, this does return the value. It is rare to return the text.
you could do it with something like the following:
jQuery('#test').change(function() {
//get text(), change to .val() to get value
var value = jQuery(':selected', this).text();
//insert value
jQuery('h2 span').html(value);
});
http://jsfiddle.net/pCsF9/
accompying html
<select name="test" id="test">
<option value="AA">AA</option>
<option value="MA">MA</option>
<option value="LA">LA</option>
<option value="GO">TEST</option>
</select>
<h2>selected:<span></span> </h2>
NOTE change .text() to .val() and select the last option to see the difference between selecting the value and text. the .text() should return TEST, where .val() will return GO
Here's the old-skool non-jQuery version that works in all scriptable browsers:
var option = styleSelect.options[styleSelect.selectedIndex];
alert("Value: " + option.value + ", text: " + option.text);
Use first the selector, then the context:
jQuery(':selected',styleSelect).text();
matchew's suggestion will work too but only when you didn't set the value-attributes of the <option>'s
(If you set the value-attributes you will get the value of the selected option instead of the text)
var styleSelect = $('select option:selected');
console.log(styleSelect.val());
Will give you the value of the option currently selected

Categories

Resources