Using react I can grab the value of the selected element via target.value
however in my current case I want both the value as its an ID of sorts and the face value of the option. How do I grab that with react? Is that plausible?
By face value I mean the Words in between <option value='123'> TEXT </option>
I want to be able to get the "TEXT"
I would just give this select box an id and grab this value using normal JavaScript function attached to your click handler or whatever function you want to execute within your React component.
// regular javascript way
var yourElement = document.getElementById(elementId);
if (yourElement.selectedIndex == -1)
return null;
return yourElement.options[yourElement.selectedIndex].text;
event.target gives you the HTMLSelectElement, from there you have access to a few other things such as HTMLSelectElement.selectedOptions.
From MDN:
HTMLSelectElement.selectedOptions (Read only)
Returns a live HTMLCollection containing the set of options that are selected.
So from there you can get the HTMLOptionElement and the text
Put it all together and you'll have something like this:
var selectedOption = e.target.selectedOptions[0];
console.log(selectedOption.value); // 123
console.log(selectedOption.text); // TEXT
Related
I have this html part code :
<p><label>Taxe </label>
<select id="id_taxe" name="id_taxe" style="width: 100px;" onchange="taxselection(this);"></select>
<input id="taxe" name="taxe" class="fiche" width="150px" readonly="readonly" />%
</p>
Javascript method :
function taxselection(cat)
{
var tax = cat.value;
alert(tax);
$("#taxe").val(tax);
}
I'd like to set the value of taxe input to the selected value from the dropdownlist.It works fine only where the dropdownlist contains more than one element.
I try onselect instead of onchange but I get the same problem.
So How can I fix this issue when the list contains only one element?
This works:
$('#id_taxe').change(function(){
var thisVal = $(this).val();
var curVal = $('#taxe').val();
if(thisVal != curVal)
$('#taxe').val(thisVal);
$('#select option:selected').removeAttr('selected');
$(this).attr('selected','selected');
});
Use the change method which is very efficient for select boxes. Simply check the item selected isn't currently selected then if not, set the value of the input to the selected value. Lastly you want to remove any option's attr's that are "selected=selected" and set the current one to selected.
Just include this inside a $(document).ready() wrapper at the end of your HTML and the change event will be anchored to the select field.
Hope this helps.
http://jsbin.com/populo
Either always give an empty option, or in your code that outputs the select, check the amount of options, and set the input value straight away if there's only 1 option.
A select with just 1 option has no events, since the option will be selected by default, so there's no changes, and no events.
As DrunkWolf mentioned add an empty option always or you can try onblur or onclick event instead, depending on what you are actually trying to do.
Ok, just to stay close to your code, do it like this: http://jsfiddle.net/z2uao1un/1/
function taxselection(cat) {
var tax = cat.value;
alert(tax);
$("#taxe").val(tax);
}
taxselection(document.getElementById('id_taxe'));
This will call the function onload and get value of the element. You can additionally add an onchange eventhandler to the element. I highly recommend not doing that in the HTML! Good luck.
I am trying to create a summary page where I grab all content form the main page and show it in a overlapping div sort of like images are displayed these days.
Now problem that I get I lose input and select values once I past it into a summary / print wrap.
jQuery
$(".header").clone().appendTo('.page');
$(".task").clone().appendTo('.page');
$(".options").clone().appendTo('.page');
.header and .task are just plain text input. And that works just fine. However with in the .options I have many controls like textarea, input, and select ... I get all the elements into .page however I lose all the selected values and text.
Any suggestion?
Thanks
The value of the inputs are not stored in the attribute tag value. This means that the copy will not have the value set. So before you copy them set the value attr.
function CopyStuffToPage() {
// Doing this will change the HTML for all the input elements
$('input').each(function(index,element) {
$(element).attr('value',$(element).val());
});
$('textarea').each(function(index,element) {
$(element).html($(element).val());
});
$('select').each(function(index,element) {
var value = $(element).val();
$(element).children('option').removeAttr('selected');
$(element).children('option[value='+value+']').attr('selected','selected');
});
// Then you can do this
$(".header").clone().appendTo('.page');
$(".task").clone().appendTo('.page');
$(".options").clone().appendTo('.page');
}
For selects you will have to add the attribute 'selected' to the option for which the select has selected.
I had this same issue when I wanted to save the contents of a div through PHP I had to set the attribute tags then send the HTML.
Edit: To Clerify the values of the elements you are copying are not stored as
<input value='this value'/>
they are stored in the DOM thus cloning them only clones the html not the value.
You can use localstorage for a quick patch to your problem.
Store the values within the textbox and textarea as,
//retrieving value from textbox and text area,
var textbox = $("#id-of-textbox").val();
var textarea = $("#id-of-textarea").val();
//retrieving the selected value for 'select'
var selectedValue = $('#id-of-select').val();
//storing the value in localstorage
localstorage.setItem("textbox", textbox);
localstorage.setItem("textarea", textarea);
localstorage.setItem("select", selectedValue);
//You can retrieve the above stored values anywhere you want as,
var newtextbox = localstorage.getItem("textbox");
var newtextarea = localstorage.getItem("textarea");
var newselect = localstorage.getItem("select");
//It is advisable to remove the store data after it's use,
localstorage.removeItem("textbox");
localstorage.removeItem("textarea");
localstorage.removeItem("select");
Advantage of using localstorage is that the data is stored within user's browser so you can access it on any page just like session data.
hi everyone i have a problem.
i have a multiple selection and i want to select something and put it into an input through a button i hope i have been clear :
i manage to get the select item with this jquery code :
var chosen= $('#droite option:selected').val();
droite is an id for the multiple selection
and i want to put it into the input wich has an id : chosen item here is my jquery code:
$("#chosenitem").prepend(chosen);
and it won't work do you have any idea why .?
You need to call val() on the select itself, not the options it contains:
var chosen = $('#droite').val();
Similarly, to set the value of the #chosenitem input, use val() with a parameter:
$("#chosenitem").val(chosen);
Note that if multiple options are selected in the #droite element, the value returned will be a comma delimited string, eg. foo,bar,baz.
You should call val() to set the value of #chosenitem
$("#chosenitem").val(chosen);
I have the following code
<select id="part">
<option>noun</option>
<option>verb</option>
<option>adjective</option>
</select>
In the above code, I don't have any value attribute each option tag.
there is only text node.
when I access the option tag
$("#part").val(); I get what is selected in dropdown box. ie, "noun"
but when I access $("#part").text(), there is empty string.
but when I create, option tags dynamically in jquery for
<select id="part"></select>
using
var names=["noun","adjective","verb"];
for (var i =0;i<names.length;i++) {
var option=$("<option>",{
value:names[i],
text:names[i]});
$("#part").append(option);
}
Here the value is attribute is needed to get the option selected.
without value attribute, $("#part") is undefined.
can somebody explain the discrepancy here? of if my understanding is not correct. Thanks
Check here DEMO http://jsfiddle.net/yeyene/yH4Fb/
You need to get only the selected option text coz there are three options,
when you get $("#part").val(); you directly get the selected value (only one selected value). But when you get $("#part").text().. you are getting the text of the whole select text where you have three options and three types of text.
JQUERY
$(document).ready(function(){
var names=["noun","adjective","verb"];
for (var i =0;i<names.length;i++) {
var option=$("<option>",{
value:names[i],
text:names[i]});
$("#part").append(option);
}
$("#part").on('change', function() {
alert('Value is '+$(this).val());
var text = $("#part option:selected").text();
alert('Text is '+text);
});
});
$("#part").text() doesn't return nothing but it won't return what you expect (see this fiddle).
Explanation: text returns the text of the object strips out the html (see jQuery docs examples), so what you will be getting is the inner contents of the select after the html was stripped out.
If you want the text of the selected value, include the selected option in your jquery selector: i.e. $('#part option:selected').text() which uses the jQuery psuedo-selector (also in my fiddle).
I am filling a drop down based on the value selected in the first drop down.Data being sent back from server is in JSON format and using JQuery to parse and fill the second select tag
<select name="abc" id="jobName">
<option value="-1">Please select a Job</option>
</select>
This is my Jquery code
var selectedGroup = document.getElementById(groupDropDownId);
var groupdata = selectedGroup.options[selectedGroup.selectedIndex].value;
var formInput='group='+groupdata;
$.getJSON('search/getSchedulerJobListForGroup',formInput,function(data) {
$('.result').html('' + data.jobList + '');
$.each(data.jobList,function(index, value){
var jobId = document.getElementById(resetDropDownId);
var option=new Option(value,value);
try{
jobId.add(option);
}
catch(e){
jobId.appendChild(option);
}
});
});
$("#jobName")[0].selectedIndex = 1;
// $("#jobName").val($("#triggerjobName option:first").val());
in above code groupDropDownId is ID of the drop down based on whose value, second drop down will be filled.resetDropDownId is ID of second drop down which i am trying to fill from JSON data getting from the server.
Upon filling the drop down, its also creating an empty option tag and it is getting select by default.
I am not sure if i can add some default value to that empty option so that i can select that default option value like "please select bla bla."
also i tried to select first element from the drop down but nothing seems working for me.I am wondering what i am doing wrong here?
Based on your question, it looks like you want to know how to change the value and text of an element within a dynamically populated select list.
Currently, you have this statement $("#jobName")[0].selectedIndex = 1; sitting outside of your getJSON request. If you move this inside of the getJSON function, it will work as expected.
If you want to set the value and text of that object, you'll want to use ->
$('#jobId option:first').val("Some Value").text("other stuff");
You can see a working JS Fiddle using dynamically populated select list from a JSON object.
Fiddle