How to capture the text of an Select option? - javascript

So I have this:
<select id="list">
<option value="1">This is Me</option>
<option value="2">This is You</option>
<option value="3">And this is Mr. Nukem</option>
</select>
How would I go about grabbing the 'text' of the options here? The problem is, it needs to be 'dynamic', in the sense I need the text for the currently selected option...
I know a manual, static way of getting the text...
document.getElementById('list').options[1].text
That will grab "This is You"... But how do I get it for the currently selected option? Since I can't simply use:
document.getElementById('list').value
As that will grab the number... :-(

var list = document.getElementById('list');
var text = list.options[list.selectedIndex].text;
See (for example) here https://developer.mozilla.org/en/DOM/HTMLSelectElement

If you can use jQuery, you can try something like this:
$("#list").change(function() {
alert($(this).find("option[value=" + $(this).val() + "]").text());
});
See http://jsfiddle.net/MWu9f/ for a working example.

$("#list option[value='2']").text()
You can use this jQuery line and it will solve your problem.
In this an element with id list which has a property value equal to 2. What you want is the option child of the list.

The jQuery solution is like this:
$("#list option:selected").text()

Related

Increasing data attribute on click

What I'm attempting seems simple enough, but I'm obviously missing something. I have a simple select menu. After selecting a country, the value is passed into a variable, prepended with a hash to change it modify it to the respected id. Using this id I'm attempting to increase the data-size by 1. The only issue is that nothing happens with the data-size.
Here's a FIDDLE.
Things should flow like this:
Select country
Select value turned into id tag
data-size of said id is increased by 1 in the HTML
EDIT/UPDATE
I need the actual data-size value to be updated in the HTML because I have specific CSS that deals with different values.
HTML
<select name="countryList" id="countryList" class="selectBox">
<option value="" disabled selected>SELECT</option>
<option value="austria">Austria</option>
<option value="brazil">Brazil</option>
<option value="canada">Canada</option>
</select>
<button class="cancel">cancel</button>
<button class="confirm">confirm</button>
<div class="dot" data-size="0" id="austria"></div>
<div class="dot" data-size="0" id="brazil"></div>
<div class="dot" data-size="0" id="canada"></div>
jQuery
var countryPicked = "";
$('.confirm').on(touchClick, function(){
countryPicked = $('#countryList').val();
countryPicked = ($('#' + countryPicked));
var i = countryPicked.data('size');
countryPicked.data('size', i + 1);
});
Try changing touchClick to "click"
The DOM will not be changed visibly, because it is stored internally.
use attr('data-size',i + 1) if you want the DOM to be updated
Demo
Try doing
countryPicked.attr('data-size', i+1);
There seems to be something wrong with .data(), it can only READ the property, not SET it.
First of all please modify the handler to:
$('.confirm').on(`click`, function(){
//code here
});
For multiple events, give comma separated value as event.
Also note that changes will not be reflected in console. However you can check them using alert or console.log
Working Demo
jQuery stores the data internally if they don't exist the first time you set them. If you really want to force it:
countryPicked.attr('data-size', i + 1);
This works for me:
Fiddle: http://jsfiddle.net/GtT3Q/13/
$('.confirm').click(function(){
var countryPicked = $('#countryList').val();
countryPicked = $('#' + countryPicked);
var i = parseInt(countryPicked.attr('data-size'));
countryPicked.attr('data-size', i + 1);
});

hide the text inside select control

How can I hide the part of the text written inside of the option?
I've tried the following:
<select name='what'>
<option value='some value'>Value to be shown <span class='hide'>value to be hidden</span></option>
....
</select>
And here is the CSS.
.hide{ visibility : hidden; }
But it doesn't seem to work. I've also tried display:none instead of visibility:hidden but that doesn't work either.
P.S: Why I want to do this? I want to do this because I want the hidden text to be included in the search.
UPDATE I am well aware that it may be achieved using the html5 meta tags, but unfortunately that I can't use here as I am using Jquery plugin called Chosen and it doesn't support the search over meta tags.
In order to add extra data to your option, e.g. for search, you may use the value or extra attributes of the option element.
For example,
<option value="value to be hidden" data-meta="value to be hidden">Value to be shown</option>
HTML
<select>
<option value="value to be hidden1" data-meta="value to be hidden11">Value to be shown1</option>
<option value="value to be hidden2" data-meta="value to be hidden22">Value to be shown2</option>
<option value="value to be hidden3" data-meta="value to be hidden33">Value to be shown3</option>
</select>
<div class='output'></div>
JS
$(document).ready(function(){
$('select').change(function(){
$('.output').html($('select option:selected').val()+'<br/>'+
$('select option:selected').data('meta'));
});
});
http://jsfiddle.net/uHY5P/
You may introduce as many attributes as you want with the prefix "data-" and retrieve them by calling jQuery.data('yourCustomAttr')
You can't do this. <option> tag cannot contain any other tags. Use Select2
It's been a while since you posted your question but it may help someone in the future. I went through exactly the same process in the past few days.
I needed to search for select options with or without special characters using jquery Chosen plugin (ver. 1.1.0).
I have a drop down with wine producers which includes names with foreign characters like Château Bénitey. In this case free text search should find the producer with "château bénitey" and "chateau benitey" keywords.
This is how I achieved it:
I used PHP to dynamically convert special characters to their equivalents eg. "â" => "a".
I created an extra attribute in <option> tags in html called data-search-text="Château Bénitey Chateau Benitey".
Then I patched Chosen plugin to read the data-search-text value instead of option text.
In SelectParser.prototype.add_option method I added a new property to store attribute values.
this.parsed.push({
array_index: this.parsed.length,
options_index: this.options_index,
value: option.value,
text: option.text,
html: option.innerHTML,
selected: option.selected,
disabled: group_disabled === true ? group_disabled : option.disabled,
group_array_index: group_position,
classes: option.className,
style: option.style.cssText, // extra comma ;)
searchTextAttribute: option.getAttribute('data-search-text') // this is the line I added
});
Then I modified AbstractChosen.prototype.winnow_results method:
Replace:
option.search_match = this.search_string_match(option.search_text,
regex);
With:
var textToSearch = option.search_text;
if (option.searchTextAttribute) {
textToSearch = option.searchTextAttribute;
}
option.search_match = this.search_string_match(textToSearch, regex);
I have multiple dropdowns in my advanced search so only the selects that have data-search-text attribute populated will behave that way.
I also had to remove the feature that highlights matched parts of option text as it was breaking it.
if (searchText.length) {
startpos = option.search_text.search(zregex);
text = option.search_text.substr(0, startpos + searchText.length) + '</em>' + option.search_text.substr(startpos + searchText.length);
option.search_text = text.substr(0, startpos) + '<em>' + text.substr(startpos);
}
Make sure you initialise the Chosen plugin with the following setting, otherwise it will search from the beginning of search only and the converted text won't be matched.
$('.your-select').chosen({search_contains: true});

jQuery .on not firing

I have the following code (reproduced in this jsFiddle) that is not working. There are three options in the Type select box. If the first (True/False) is selected I need the first div to be shown, and if the second or third options are chosen then the second div needs to be shown. What is wrong with this code?
HTML:
<form name="editform">
Selector: <select class="selectors" name="1-type" id="1-type">
<option value="tf" selected="selected">True/False</option>
<option value="rd">Radio Button</option>
<option value="chk">Checkboxes</option>
</select>
<div id="seldiv-1">
Good Value: <select name="1-good_value" id="1-good_value">
<option value="true">True</option>
<option value="false">False</option>
</select>
</div>
<div id="textdiv-1" style="display:none;" disabled="disabled">
Good Value:
<textarea name="1-good_value" id="1-good_value"></textarea>
</div>
</form>
Javascript:
$(document).ready(function(){
$('.selectors').on('change',function (){
var arr = $(this).name.split("-");
var id = arr[0];
var val = $(this).val();
if(val=="tf") {
$('#textdiv-'+id).hide();
$('#seldiv'+id).show();
//Make textarea disabled
//Make selection enabled
} else {
$('#textdiv-'+id).hide();
$('#seldiv'+id).show();
//Disable selection
//Enable textarea
}
});
});
Uncaught TypeError: Cannot call method 'split' of undefined.
Change $(this).name.split("-"); to this.name.split("-");
it is not the on but the split function is giving you error, you are trying to get the name method of jquery object which is not available...either you need to use attr() to get the name from jquery object..or use this DOM object to get name
try this
var arr = $(this).attr('name').split("-");
or
var arr=this.name.split('_');
NOTE both your codes inside if/else condition is same.. so you won't notice the difference..check it out in your fiddle
working fiddle example
It 100% does fire, you have an error with $(this).name being undefined. I think what you actually wanted to do there was this.name
jQuery objects don't act just like DOMElement objects, i.e they don't have the same properties (like .name). Next time, open your web console when trying to find out why something doesn't work and you will catch most of your problems there.
This line is your problem:
var arr = $(this).name.split("-");
on is working properly but the line above is throwing an exception.
var arr = $(this).attr("name").split("-");
There are a few ways you could fix this, above is one example.
your problem is when trying to access $(this) which is undefined.
Try just this instead
this.name.split("-");
The name is not a valid property. Rather use id or change the way you access it to var arr = $(this).attr('name').split("-");.

javascript and <option>

I do have the following JavaScript.
<form>
<select id="sel">
<option value="1">item_1</option>
<option value="2">item_2</option>
<option value="3">item_3</option>
</select>
<div id="show"></div>
</form>
<script type="text/javascript">
var sel = document.getElementById('sel');
sel.onchange = function() {
var show = document.getElementById('show');
show.innerHTML = this.value;
};
</script>
If I click onchange a new value (here: 1,2, or 3) is shown in the div "show". This is working fine. But my problem is that I want a different value to be shown but the value (1,2, or 3) should be submitted. The item has a unit like kg, pound, m, m², ....
I want something like that:
<option value="1" value2="kg">item_1</option>
I changed value to value2 in <script> but it didn't help.
show.innerHTML = this.value2;
How can I get it to work?
if you apply what #Simon said, you can try the following:
sel.onchange = function() {
var show = document.getElementById('show');
show.innerHTML = this.options[this.selectedIndex].getAttribute('value2');
}
Revised HTML:
<form>
<select id="sel">
<option value="1" data-unit="kg">item_1</option>
<option value="2" data-unit="kph">item_2</option>
<option value="3" data-unit="m2">item_3</option>
</select>
</form>
<div id="show"></div>
The revised HTML uses the custom, and in HTML5 valid, data-* attribute to store the units. I've also moved the div out of the form, but that's an entirely personal inclination, and one that you don't have to maintain (obviously...).
Amended JavaScript:
var sel = document.getElementById('sel');
sel.onchange = function() {
var show = document.getElementById('show');
show.innerHTML = this.value + this.options[this.selectedIndex].getAttribute('data-unit');
};
JS Fiddle demo.
The JavaScript looks for the option within the this node with the selectedIndex, and then uses getAttribute() to find the string contained within the data-unit attribute and concatenates that to the this.value string.
That should probably be:
show.innerHTML = this.options[this.selectedIndex].value;
If the list is not a dynamically generated one, why don't you use an "if else" construct or a "switch" construct on the populated values and display whatever you like?
Use the value attribute for the value you want submitted to the server since value is meant to contain a string that is meant to be interpreted by a computer as part of a form.
Use a different attribute to associate human readable text with the <option>. title and longdesc would be good choices.
I would recommend using jQuery if you can. If you're expecting to be able to use html5 compliant browsers, you can use the data attributes on your <option> elements. This way you'd be able to store whatever attributes you found useful.
jQuery data attributes usage
You can use .innerHTML instead of .value if you want to display the text from the drop down. If you want something completely different to be displayed, you'll need a lookup table or something similar - might be easier to use jQuery.

JQuery/Javascript Clear/Reset Drop down List to original values

Ok dokey, got a bit of jquery up and running, lovely stuff.
$(document).ready(function() {
$inputs = $("#tbxProdAC, #ddlBuyer, #txtbxHowMany, radTopx");
$.each($inputs, function() {
$(this).focus(function() {
$.each($inputs, function() {
$(this).val('');
$(this).attr('checked', false);
})
});
})
});
However, in my drop down list, I wish to retain the orignal value rather than clear it altogether.
Is there a way I can specify the individual values i.e. tbxProdAC ='', ddlBuyer = Original Value, txtbxHowMany='', radTopx =unchecked, etc?
have you tryed:
document.getElementById('formId').reset();
try it this way:
$(document).ready(function() {
$("#tbxProdAC, #ddlBuyer, #txtbxHowMany, radTopx").focus(function() {
document.getElementById('formId').reset();
});
});
You'll have to go through each one separately to do that.
i.e.
$('#tbxProcAC').val('');
$('#ddlBuyer').val($('#ddlBuyer')[0].defaultValue);
$('#txtbxHowMany').val('');
$('#radTopx').attr('checked',false);
Perhaps the second line there may be of most intrest to you - it shows how to access the original 'default' value.
Comment if you've any questions, good luck!
You can use the data function in JQuery - you can store all the existing values and call them again when you need them
in JQuery can select First Option <option value="0" > </option> first option value is zero and text is empty.
now
$('#DropDown').find('option:first').attr('selected', 'selected');
$('#DropDown')[0].selectedIndex = 0;
$('#DropDown') -> select dropdown
find('option:first') -> find first option
attr('selected', 'selected') -> set attribute selected.
Try this simple way
document.getElementById(‘drpFruits’).options.length=0;

Categories

Resources