jQuery SELECT with Textarea - javascript

Just wondering if someone can help me on a problem, I don't fully undersand why it doesn't work.
I have this fiddle, http://jsfiddle.net/uomt99zp/
What it is doing:
When you select from the drop down box, insert that word into the textarea.
Which it DOES, when the textarea isn't "touched".
If you type something into the box, and then try to select an item, it doesn't work.
I'm not sure why this doesn't update the textarea. Perhaps someone can shed some light on this issue?
<textarea name="template" required="required" class="template form-control" rows="6"></textarea>
<select class="templatesAvailableFields">
<option>Select One</option>
<option>Test1</option>
<option>Test2</option>
<option>Test3</option>
</select>
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').append(text);
});

You need to set value using .val():
$('.template').val($('.template').val()+text);
Working Demo 1
Also .val() can have callback function which can be used for setting a new value:
function
Type: Function( Integer index, String value ) => String
A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.
$('.template').val(function(i,v){ return v+ text});
Working Demo 2

You can try val(function) with old value + new text to append,
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').val(function(ind,val){
return val+text;
});
});
Live Demo

To answer to the "why" it does not work, it's because, the contents of a textarea represent its default value. So, when you append an element to the textarea, you change the default value of this textarea.
So it changes the textarea as long as you did not type in. Once you typed in, the default value is no more used, even if you remove all the text of the textarea.

By using .append you are just concatinating your output string if you want only the dropdown element it would be better to use the .text() or .val() method

$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
var existing=$('.template').val();
$('.template').val(existing+text);
});
.append(), .html() and .text() methods do not work with form elements, for setting/getting value of a from element .val() method should be used instead:

Your code is working ...i tried it in visual studio .... Only change I had made is I kept the script under the option control... I am not sure about.for me its working fine.
<body >
<textarea name="template" required="required" class="template form-control" rows="6"></textarea>
<select class="templatesAvailableFields">
<option>Select One</option>
<option>Test1</option>
<option>Test2</option>
<option>Test3</option>
</select>
<script type="text/javascript">
$('.templatesAvailableFields').on('change', function () {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').append(text);
});
</script>
</body>

You should control input value's with val() method
// cache element
var $select = $('.templatesAvailableFields');
$select.change( function() {
$('.template').val($select[0].value);
});

just replace append with text
here is the updated fiddle
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').text($('.template').text() + text);
// $('.template').val(text); this won't work in IE <= 7
});
http://jsfiddle.net/rrehan/uomt99zp/2/

Related

How to show selected option in textbox in C# [duplicate]

How can I get the selected text (not the selected value) from a drop-down list in jQuery?
$("#yourdropdownid option:selected").text();
Try this:
$("#myselect :selected").text();
For an ASP.NET dropdown you can use the following selector:
$("[id*='MyDropDownId'] :selected")
The answers posted here, for example,
$('#yourdropdownid option:selected').text();
didn't work for me, but this did:
$('#yourdropdownid').find('option:selected').text();
It is possibly an older version of jQuery.
If you already have the dropdownlist available in a variable, this is what works for me:
$("option:selected", myVar).text()
The other answers on this question helped me, but ultimately the jQuery forum thread $(this + "option:selected").attr("rel") option selected is not working in IE helped the most.
Update: fixed the above link
This works for me
$("#dropdownid").change(function() {
alert($(this).find("option:selected").text());
});
If the element created dynamically
$(document).on("change", "#dropdownid", function() {
alert($(this).find("option:selected").text());
});
$("option:selected", $("#TipoRecorde")).text()
$("#DropDownID").val() will give the selected index value.
This works for me:
$('#yourdropdownid').find('option:selected').text();
jQuery version: 1.9.1
For the text of the selected item, use:
$('select[name="thegivenname"] option:selected').text();
For the value of the selected item, use:
$('select[name="thegivenname"] option:selected').val();
Use this
const select = document.getElementById("yourSelectId");
const selectedIndex = select.selectedIndex;
const selectedValue = select.value;
const selectedText = select.options[selectedIndex].text;
Then you get your selected value and text inside selectedValue and selectedText.
Various ways
1. $("#myselect option:selected").text();
2. $("#myselect :selected").text();
3. $("#myselect").children(":selected").text();
4. $("#myselect").find(":selected").text();
$("#dropdownID").change(function(){
alert($('option:selected', $(this)).text());
});
var someName = "Test";
$("#<%= ddltest.ClientID %>").each(function () {
$('option', this).each(function () {
if ($(this).text().toLowerCase() == someName) {
$(this).attr('selected', 'selected')
};
});
});
That will help you to get right direction. Above code is fully tested if you need further help let me know.
For those who are using SharePoint lists and don't want to use the long generated id, this will work:
var e = $('select[title="IntenalFieldName"] option:selected').text();
$("#selectID option:selected").text();
Instead of #selectID you can use any jQuery selector, like .selectClass using class.
As mentioned in the documentation here.
The :selected selector works for <option> elements. It does not work for checkboxes or radio inputs; use :checked for them.
.text() As per the documentation here.
Get the combined text contents of each element in the set of matched elements, including their descendants.
So you can take text from any HTML element using the .text() method.
Refer the documentation for a deeper explanation.
This code worked for me.
$("#yourdropdownid").children("option").filter(":selected").text();
$("select[id=yourDropdownid] option:selected").text()
This works fine
$('#id').find('option:selected').text();
For getting selected value use
$('#dropDownId').val();
and for getting selected item text use this line:
$("#dropDownId option:selected").text();
Select Text and selected value on dropdown/select change event in jQuery
$("#yourdropdownid").change(function() {
console.log($("option:selected", this).text()); //text
console.log($(this).val()); //value
})
Try:
$var = jQuery("#dropdownid option:selected").val();
alert ($var);
Or to get the text of the option, use text():
$var = jQuery("#dropdownid option:selected").text();
alert ($var);
More Info:
http://api.jquery.com/val/
http://api.jquery.com/text/
Simply try the following code.
var text= $('#yourslectbox').find(":selected").text();
it returns the text of the selected option.
var e = document.getElementById("dropDownId");
var div = e.options[e.selectedIndex].text;
$("#dropdown").find(":selected").text();
$("#dropdown :selected").text();
$("#dropdown option:selected").text();
$("#dropdown").children(":selected").text();
Use:
('#yourdropdownid').find(':selected').text();
the following worked for me:
$.trim($('#dropdownId option:selected').html())
This work for me:
$("#city :selected").text();
I'm using jQuery 1.10.2
In sibling case
<a class="uibutton confirm addClient" href="javascript:void(0);">ADD Client</a>
<input type="text" placeholder="Enter client name" style="margin: 5px;float: right" class="clientsearch large" />
<select class="mychzn-select clientList">
<option value="">Select Client name....</option>
<option value="1">abc</option>
</select>
/*jQuery*/
$(this).siblings('select').children(':selected').text()
$(function () {
alert('.val() = ' + $('#selectnumber').val() + ' AND html() = ' + $('#selectnumber option:selected').html() + ' AND .text() = ' + $('#selectnumber option:selected').text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<select id="selectnumber">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
</div>
</form>
</body>
</html>
Try
dropdown.selectedOptions[0].text
function read() {
console.log( dropdown.selectedOptions[0].text );
}
<select id="dropdown">
<option value="1">First</option>
<option value="2">Second</option>
</select>
<button onclick="read()">read</button>

Getting a Select Value after appending

This is for javascript and jquery.
I have in my body...
<select id="option1_select" name="courseCodeSelectName">
<option></option>
<option>Word1</option>
<option>Word2</option>
</select>
<script>
$("select").change(function () {
functionLoadOpt2() }).trigger("change" );
</script>
<select id="option2_select" name="courseNumSelectName">
<option></option>
</select>
<button onclick="changePage()">Load Textbook Page!</button>
As we see above, the web page has 2 select boxes and a button. Depending on what you select in the first select box loads what is in the second one, using the functionLoadOpt2 function locating higher up in my code.
if (result == "Word1") {
$("#option2_select").append('<option>Letter1</option>');
...
There is more but it follows the same code different values.
Result is the following, above the if statement(just a row up),
var result = (document.getElementById('option1_select').value);
now on the button click, the function changePage() runs,
and all I want is ...
var result = (document.getElementById('option1_select').value);
var result2= (document.getElementById('option2_select').value);
Assume they selected and option for both. Result2 doesnt work. I'd imagine because I'm appending it but how would I work around this. So that when I click changePage() I get the selected value of option1_select and option2_select.
functionLoadOpt2:
function functionLoadOpt2(){
var opt1Val = (document.getElementById('option1_select').value);
$("#option2_select").find('option').remove().end().append('<option></option>');
if (opt1Val == "Word1") {
$("#option2_select").append('<option>Letter1</option>');
$("#option2_select").append('<option>Letter2</option>');
$("#option2_select").append('<option>Letter3</option>');
$("#option2_select").append('<option>Letter4</option>');
$("#option2_select").append('<option>Letter5</option>');
}else if (opt1Val == "Word2") {
$("#option2_select").append('<option>Letter3</option>');//they have similar ones in some cases
$("#option2_select").append('<option>Letter6</option>');
$("#option2_select").append('<option>Letter7</option>');
$("#option2_select").append('<option>Letter8</option>');
$("#option2_select").append('<option>Letter9</option>');
$("#option2_select").append('<option>Letter10</option>');
$("#option2_select").append('<option>Letter11</option>');
$("#option2_select").append('<option>Letter12</option>');
$("#option2_select").append('<option>Letter13</option>');
$("#option2_select").append('<option>Letter14</option>');
$("#option2_select").append('<option>Letter15</option>');
$("#option2_select").append('<option>Letter16</option>');
$("#option2_select").append('<option>Letter17</option>');
//this works
}
}
use jQuery to get and set the value of <select> with .val()
Both your select elements have the same id, fix it the it should be fine
<select id="option1_select" name="courseCodeSelectName">
<option></option>
<option>Word1</option>
<option>Word2</option>
</select>
<select id="option2_select" name="courseNumSelectName">
<option></option>
</select>
<button onclick="changePage()">Load Textbook Page!</button>
Demo: Fiddle
Note: You can improve the script a lot by using proper jQuery constructs, like this

Get attributes values from select2 selected option

I'm using the Select2 plugin from http://ivaynberg.github.io/select2/select2-latest.html what works fine but i'm having a problem to get the values from the options attributes.
I've got a select menu like this:
<select name="invoice_line[0][vat]" class="vat">
<option value="20440" data-value="21.00" data-name="20440" selected="selected">21%</option>
<option value="20441" data-value="6.00" data-name="20441">6%</option>
<option value="20442" data-value="0.00" data-name="20442">0%</option>
</select>
How can I get the values of the attributes 'data-value', 'data-name' and 'value' of the selected option?
obj = $("#dropdown").select2("data")
in obj variable i will get all the data of the selected node.
This was answered in another SO question
There is no direct method with select2, you can use a combinaison of select2 data and jQuery :
$("#example").select2().find(":selected").data("id");
First you get the select2 data then you find your selected option with jQuery and finally the data-attribute.
We can use a combination of select2 data and jQuery :
$("#example").select2('data').element[0].attributes['data-name'].value
Following worked for me. Idea is to use "change" function as follows
<select class="drop-down">
<option value="0">A</option>
<option value="1">B</option>
</select>
$('.drop-down').select2().on("change", function(e) {
var obj = $(".drop-down").select2("data");
console.log("change val=" + obj[0].id); // 0 or 1 on change
});
var return_option = $("#your-select-input-id").select2().find(":selected")[0];
above given statement will return select option and then put that return result as given below:
var name_of_attribute = $( return_option ).attr('name-of-attribute');
This will return the attribute value.
No idea about the pluggin, and without checking if the code works i imagine it would be something like this:
$('.vat li').each(function(){
var me = $(this),
mevalue = me.attr('value'),
datavalue = me.data('value'),
dataname = me.data('name');
//do what you want with the data?
});
Put select2 into tagging mode , it will help you.
Or
Try below similar code, it may work for you ...
$("$id").select2("val", option);
$("$id").attr("data-name");
I know that this is an old post, but I was struggling with this same problem. This is the solution that me and my good friend Thys finally got to work:
<script type="text/javascript">
$(document).ready(function ()
{
$("#e1").select2();
$("#e1").change(function () {
var theID = $("#e1").val();
$('#staffNr').val(theID);
$('#staffNr').val();
//var theID = $(test).select2('data').id;
var theSelection = $(test).select2('data').text;
$('#selectedID').text(theID);
$('#selectedText').text(theSelection);
});
});
#Html.Hidden("fieldName","staffNr");
This worked in my MVC 4 view with the last line in my html form where it is correctly added to the model. Don't forget to up-vote if you use my answer please :) I haven't got much of a reputation...
I hope you solved the issue. Here we dont use select2(), if we use select2() it will not work all other functions like formatNoMatches, on-change....
$("#example").find(":selected").data("id");
el = document.getElementsByName("invoice_line[0][vat]")
el.options[[el.selectedIndex]].attributes["data-id"].value
The params.data.element object of the selected item holds the data you're looking for.
Where .foo is the select element I'm calling, and the data attribute within the options I want to access is data-bar="some value" The following works for me:
var $fooSelect = $('.foo');
$fooSelect.on(function (e) {
console.log($(e.params.data.element).data('bar'));
});
You can access to attributes looking in DOM structure:
<select id="select_name">
<option value="20440" data-value="21.00">21%</option>
<option value="20441" data-value="6.00">6%</option>
<option value="20442" data-value="0.00">0%</option>
</select>
$('#select_name option').each(function (index) {
console.log($(this).attr("data-value"));
});
set an id for your select element and this would work
$('select#your-id').find('option[value="'+$('#your-id').val()+'"]').attr('data-attribute');
You haveto do it with on("change"... because of this is a dynamicly generated option list.
$('.select_class').on("change",function(){
var selected_value= $('.hakemler').val();
var wanted= $('.select_class').find('option[value="'+selected_value+'"]').attr('data-foo');
alert(selected_value+" "+wanted);
});

How to get the selected option in an html using jquery

I want to retrieve the id of my option that I selected. Over here you can see my HTML.
<select name="zaal" id="zaal">
<DIV CONTENTEDITABLE="FALSE" ID="MACONTAINER" MACONSTRAINT="" MAPARAMETER="ZALEN">
<DIV CONTENTEDITABLE="TRUE" ID="MAITEM">
<option value="~#ITEM.ID~" id="ZAALNAME">~ITEM.ID~, ~ITEM.NAME~</option>
</DIV>
</DIV>
</select>
I am doing it like this.
var selectVal = $("#zaal :selected").val();
var id = selectVal.substring(1);
console.log("id is: " + selectVal);
But for some reason it won't work.
Can anybody help?
EDIT
Ok the divs are the problem. But I need those to get my values from my database.So I think I need to find another solution than a select.
$("#zaal option:selected").attr('value'); // will return you ~#ITEM.ID~
To get the id
$("#zaal option:selected").attr('id'); // will return you ZAALNAME
To get id on selection change try this:
$('#zaal').on('change', function() {
// To get id
$('option:selected', this).attr('id');
$('option:selected', this).attr('value'); // return the value of selected option
// To get the select box value
var value = this.value;
});
Maybe try:
$("#zaal option:selected").val();
Also, try moving the divs outside of the select element.
Look at this question:
<div> and <select> tags
You can only put <option> or <optgroup> inside a <select>. If you want to put anything else in there you have to make some kind of list yourself.
Why would you like to put any div inside a select anyway?
If I put the HTML you gave me (with edited strings) inside Google Chome, this is what is made of your code:
<select name="zaal" id="zaal">
<option value="x" id="ZAALNAME">X, Y</option>
</select>
$("#zaal option[value='0']").text()
Try this:
var selectVal = $("#zaal option:selected").val();
var id = selectVal.substring(1);
console.log("id is: " + selectVal);
The html should be
<select name="zaal" id="zaal">
<option value="~#ITEM.ID~" id="ZAALNAME">~ITEM.ID~, ~ITEM.NAME~</option>
</select>
$('#zaal').change(function(){
alert($($(this)+':selected').attr('id'));
});
Fiddle http://jsfiddle.net/cBaZ7/1/
val() will retrieve the value of the selected option. It is not the id
So try this:
$("#zaal option:selected").attr("id")

jQuery Select list, selected text value rather than the value

building on my last question jQuery getting values from multiple selects together
I have the select list like:
<select name="access" class="change" id="staff_off" runat="server">
<option value="8192">Off</option>
<option value="8192">On</option>
</select>
And I basically want to add or subtract the value of the options if it's off, subtract if it's on add it. It's going to be stored in a cookie (it uses bitwise)
The jquery I have is:
<script>
$(document).ready(function(){
var currentAccess = $.cookie("access");
})
$("select").change(function () {
var currentText = $(this).text()
var value = $(this).val()
$.cookie("access", value, { expires: 24 });
alert(currentText);
alert( $.cookie("access") );
})
</script>
I'll do the addition in the change function. The thing I can't work out is how to get the text of the select to do an if statement (so if it's yes, add the value, if it's no, subtract the value)
Tom
If you're looking for the inner text of the selected <option> element, you can use the :selected selector to match it, then call the text() method:
var currentText = $(this).find(":selected").text();
Or, alternatively:
var currentText = $(":selected", this).text();
To get the text of the selected item:
var value = $("#staff_off :selected").text();
I'd also suggest (if you're using HTML5) that using the data-x attribute to store the flag whether to add or subtract the value would be more semantic. Like this:
<select name="access" class="change" id="staff_off" runat="server">
<option value="8192" data-factor="-1">Off</option>
<option value="8192" data-factor="1">On</option>
</select>
Then to get your final value to apply to the total you simply multiply the value by the data-factor attribute.
You can use this $("#staff_off").find("option:selected").html();

Categories

Resources