How to alert the selected option using javascript or jquery? - javascript

I am using a select tag in my code, here is my code,
<select onchange="test(this);">
<option value="0">Select</option>
<option value="1">Select1</option>
<option value="2">Select2</option>
<option value="3">Select3</option>
</select>
and javascript code is here,
<script>
function test(obj)
{
alert($(obj).val());
}
</script>
I want to alert the selected text here, If I use the above code the value of the selected option is coming, but I want to alert the text of the selected option can anyone tell to achive this one.
I want to alert it without using any class or id.
I want to alert it only through the obj.
I am waiting for your help.
Thanks In advance

This should do the trick...
alert($(obj).find("option:selected").text());
That uses the jQuery object $(obj), like you already had, but does a find() which searches the child elements, in this case the selected option.
jQuery find()
:selected pseudo-selector

Try this..
alert($(obj).find("option:selected").text());

you can try this:
alert($(obj).find('option').eq(obj.value).text());
Working jsFiddle

<select id="someid" onchange="test();">
<option value="0">Select</option>
<option value="1">Select1</option>
<option value="2">Select2</option>
<option value="3">Select3</option>
</select>
javascript>
function test(){
var elem = document.getElementById("someid"),
var selectedNode = elem.options[elem.selectedIndex].text;
alert(selectedNode );
}
jQuery>
$("#someid").change(){
alert($(this).find("option:selected").text());
}

Related

JQuery set select using .prop('selectedIndex', #) not working

I'm using the following line to set a option from a select menu:
$('select').prop('selectedIndex', 2)
Using the following site as a example:
http://shoebaloo.nl/michael-by-michael-kors-chelsea-skate-leo-bruin-dessin-285000097-women-sneakers.html
I am indeed seeing the select option going to the second option but it wont have the same effect as actually clicking on the second option.
Can someone help me so the page actually recognises me "clicking" on a option?
You need to select the option with a selector.
$('select option:eq(2)').prop('selected', true)
If you're looking to manually trigger a click or change event, you could use the .trigger('click') or .trigger('change') methods.
http://jsfiddle.net/j5v6tp7t/4/
All you should have to do is use .val() to set the value.
For example:
$('select').val('2')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select>
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
<option value="4">d</option>
</select>
Your expression was right but the correct syntax is :
$('select').get(0).selectedIndex = 2;
http://jsfiddle.net/f4s762cq/

Change Selected Value in a Select HTML Element with DOM Button Click in select2.js

I have a problem with changing selected value directly with a button click.
First, when I use these codes below without select2.js it works just fine.
<select id="mySelect">
<option value="1">Ana</option>
<option value="2">Lisa</option>
<option value="3">Jeremy</option>
<option value="4">August</option>
</select>
<button type="button" onclick="changeValue()">Chose August</button>
<script>
function changeValue() {
document.getElementById("mySelect").value = "4";
}
</script>
As you know, that button makes "August" as the selected value. But when I use select2.js, it doesn't work. I use select2.js to change other dropdowns options.
Please help. Thanks for advance.
You need to use val method of select2.js
$('#mySelect').select2("val", 4)

Alert when a particular value from dropdown is selected

I have a Dropdown(select) in a website that is not controlled by me.But it can be modified by javascript,html,jquery..etc(they have provided web applet for doing so)
This dropdown can be identified an ID 'Zdd_1'. All i want if the user selects "Yes" in the dropdown then only then an alert should come. W hen the user navigates to the page. the dropdown might be Yes or some other value, but i dont care then.
I need this alert only when the state of the drop down changes from any value to "YES". I am not much into jquery and ajax, so if this can be done done simply( mean just using javascript)it would be great.
It can be easly done with the help of jQuery.
$('#Zdd_1').change(function(){
if($(this).val() === 'yes')
alert("Hi, I'm alert!");
});
where Zdd_1 be the id for the select element.
If you want, of course you can use only javascript.
Javascript:
function selectChange(element) {
if (element.options[element.selectedIndex].value == 'Yes')
alert("Hi, I'm alert!");
}
Html:
<select id="Zdd_1" onchange="selectChange(this)">
<option value="Maybe">Maybe</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
Try this
var dropdown = document.getElementById("Zdd_1");
dropdown.onchange = function(event){
if(dropdown.value=="Yes"){
alert("Your message")
}
}
or check here working demo
On change of dropdown, you can check whether the changed value is "Yes" or not, if it is Yes then alert the text you want.
Try this
Html
<select onchange="changeddl(this)">
<option value="Maybe">Maybe</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
javascript
function changeddl($this)
{
if($this.value=="Yes")
{
alert("Whatever you want to alert!");
}
}
You can check the fiddle here
Try something like this:
Demo
You can also call a function on onchange event.

Using getSelected in MooTools

I'm new to JS and Mootools and I've been having a really funny error using getSelected() with Mootools 1.3.2. I've looked at other posts that have similar code, but I haven't been successful. I'm using getSelected to try and get the value of an option and for some reason, my browser simply isn't calling it.
Here's the HTML
<select id="id_method" name="method">
<option selected="selected" value="">---------</option>
<option value="Au">Auction (Best Price Wins)</option>
<option value="Fi">Fixed Price</option>
<option value="Fr">Free Item/Donation</option>
<option value="Mu">Multiple Items and Prices</option>
<option value="No">No Price Displayed</option>
<option value="Tr">Trade</option>
</select>
Here's the JS
window.addEvent('domready', function() {
...
$('id_method').addEvent('change', function() {
alert(this.getSelected().selection[0].value);
});
});
Here's my attempt at putting in in jsfiddle: http://jsfiddle.net/jNYud/
I know this is probably a really silly question, but I'd appreciate some help. Thanks!
The result of calling getSelected() returns an array, pure and simple. So you just need to look at the first element of that array. So replace your alert with this one:
alert(this.getSelected()[0].value);

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