I am trying to get the selected option from a dropdown and populate another item with that text, as follows. IE is barking up a storm and it doesn\'t work in Firefox:
<Try this:
$('#ddlCodes').change(function() {
var option = this.options[this.selectedIndex];
$('#txtEntry2').text($(option).text());
});
To know number of selected elements use
$("select option:selected").length
To Get the value of all selected elements use
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
With less jQuery:
<select name="ddlCodes"
onchange="$('#txtEntry2').text(this.options[this.selectedIndex].value);">
this.options[this.selectedIndex].value
is plain JavaScript.
(Source: German SelfHTML)
Here's a short version:
$('#ddlCodes').change(function() {
$('#txtEntry2').text($(this).find(":selected").text());
});
karim79 made a good catch, judging by your element name txtEntry2
may be a textbox, if it's any kind of input, you'll need to use .val()
instead or .text()
like this:
$('#txtEntry2').val($(this).find(":selected").text());
For the "what's wrong?" part of the question: .text()
doesn't take a selector, it takes text you want it set to, or nothing to return the text already there. So you need to fetch the text you want, then put it in the .text(string)
method on the object you want to set, like I have above.
The first part is to get the element from the drop down menu which may look like this:
<select id="cycles_list"> <option value="10">10</option> <option value="100">100</option> <option value="1000">1000</option> <option value="10000">10000</option> </select>
To capture via jQuery you can do something like so:
$('#cycles_list').change(function() { var mylist = document.getElementById("cycles_list"); iterations = mylist.options[mylist.selectedIndex].text; });
Once you have stored the value in your variable, the next step would be to send the information stored in the variable to the form field or HTML element of your choosing. It may be a div p or custom element.
i.e.
<p></p> OR <div></div>
You would use:
$('p').html(iterations); OR $('div').html(iterations);
If you wish to populate a text field such as:
<input type="text" name="textform" id="textform"></input>
You would use:
$('#textform').text = iterations;
Of course you can do all of the above in less steps, I just believe it helps people to learn when you break it all down into easy to understand steps... Hope this helps!
This worked for me:
$("#SelectedCountryId_option_selected")[0].textContent