javascript select element - javascript

I have a select element like this
<select name ="cars">
<option value="frd"> Ford </option>
<option value="hdn"> Holden </option>
<option value="nsn"> Nissan </option>
</select>
I want to set selected to "Holden" with javascript without selected by value. how can I achieve this?
Thanks in advance

update after comment
Use the following to find the option by text and select it
var optionlist = document.getElementById('cars').options;
for (var option = 0; option < optionlist.length; option++ )
{
if (optionlist[option].text == 'Holden')
{
optionlist[option].selected = true;
break;
}
}
demo at http://jsfiddle.net/gaby/vQhfq/
original
When there is no value attribute specified for option elements, they assume the value to be the text.
I would suggest you use an id, so you can easily find the element.
Html
<select name ="cars" id="cars">
<option> Ford </option>
<option> Holden </option>
<option> Nissan </option>
</select>
javascript
document.getElementById('cars').value = 'Holden';
(make sure you run this code, after the select element is created)
demo at http://jsfiddle.net/gaby/Pwb5u/

To select the option by its text, get a reference to the select, iterate over the options looking for the one with text "Holden", then either set the select's selectedIndex property to the index of the option, or set the option's selected property to true. e.g.
function setSelectedByText(id, text) {
var select = document.getElementById(id);
var options = select && select.options;
var opt;
for (var i=0, iLen=options.length; i++) {
opt = options[i];
if (opt.text == text) {
opt.selected = true;
// or
select.selectedIndex = i;
}
}
}
For the record, the value of the select element is the value of the selected option, or, if the selected option has no value, it's text. However, IE gets it wrong and returns "" if the option has no value.
Also, if you don't want to use getElementById, you can use:
var select = document.formName.selectName;
Noting that the select element must have a name to be successful (i.e. for its value to be returned when the form it's in is submitted).

Related

Updating a form's select element's selectedIndex property, updates the value, but doesn't change the selected option in the page

Here is the code:
const formClubSelect: HTMLSelectElement | null = document.getElementsByTagName('select',)[1] as HTMLSelectElement;
if (formClubSelect) {
for (var i = 0; i < formClubSelect.options.length; i++) {
const option = formClubSelect.options[i];
if (option.value === clubId && option.text === clubName) {
formClubSelect.selectedIndex = option.index;
formClubSelect.options[option.index].selected = true;
}
}
}
The option's can sometimes have the same value, so I'm looping through them and checking the value/text based on some previous values. If the values match the option ones, I try to set the index on the select element, as well as set the selected property on the option to true. I've tried setting just the option selected property, but it doesn't seem to change anything.
I've also checked the index before and after the change and it does update, but the option doesn't appear on the select:
HTML:
<select name="__field_349914" id="45eafcb7-97d1-4889-bd09-2ceceb954508" required="" aria-required="true" data-f-datainput="" aria-describedby="__field_349914_desc" aria-invalid="false">
<option disabled="disabled" selected="selected" value="">-- Select an option --</option>
<option value="02847" data-f-datainput="">1</option>
<option value="02771" data-f-datainput="">2</option>
<option value="03181" data-f-datainput="">3</option>
<option value="02810" data-f-datainput="">4</option>
<option value="02832" data-f-datainput="">5</option>
</select>

How to change HTML select name based on option value

How can I get option value. I want to change the name="<value>" based on selected option value.
So that I can send name value to the spring controller along with onChange="".
I want to change select name="report/leavereport/weeklysummery" based on option selected value.
<select name="" onChange="document.getReportAll.submit()">
<option value="">Select Report Type</option>
<option value="report">TIME REPORT</option>
<option value="leavereport">LEAVE REPORT</option>
<option value="weeklysummery">TIME SUMMARY</option>
</select>
Thank you,
The shortest change, given that code and modern browsers, would be:
onChange="this.name = this.value; document.getReportAll.submit()"
...since within the attribute event handler, this refers to the select element and modern browsers reflect the option value as value in single-selects.
Set a id to the select.
<select id="select"...>...</select>
Then set the onchange event of the select element. It fires when a option is selected.
If the selector value is undefined, then the browser doesn't support it, so it's possible to get the selected element iterating the options and checking if the attribute selected is included. I'd not use querySelector because older browsers may not support it.
var selector = document.getElementById('select');
selector.onchange = function() {
var value = this.value;
if(!value) {
for(var i = 0, op; op = selector.children[i]; i ++) {
// Check if the attribute selected is valid
if(op.getAttribute('selected')) {
value = op.value;
break;
}
}
}
this.name = value;
};
Here is one possible (unobtrusive) solution using getAttribute and setAttribute.
The script listens for a click on any of the options and then updates the value of the name attribute of select, based on the value of the value attribute of the option.
var options = document.getElementsByTagName('option');
function changeName() {
var value = this.getAttribute('value');
window.alert('name = "' + value + '"');
this.parentNode.setAttribute('name',value);
}
for (var i = 0; i < options.length; i++) {
options[i].addEventListener('click',changeName,false);
}
<select name="">
<option value="">Select Report Type</option>
<option value="report">TIME REPORT</option>
<option value="leavereport">LEAVE REPORT</option>
<option value="weeklysummary">TIME SUMMARY</option>
</select>

Select box option not show selected

I'm trying to copy or move one select box item to another select box. The problem is that when one or more items are moved from the first box to the second, it should be selected. But it's not working.
My Code
function SelectMoveRows(SS1,SS2)
{
var SelID='';
var SelText='';
var SelText2='';
// Move rows from SS1 to SS2 from bottom to top
for (i=SS1.options.length - 1; i>=0; i--)
{
if (SS1.options[i].selected == true)
{
SelID=SS1.options[i].value;
SelText=SS1.options[i].text;
SelText2=SS1.options[i].attr("selected");
var newRow = new Option(SelText,SelID,SelText2);
SS2.options[SS2.length]=newRow;
SS1.options[i]=null;
}
}
SelectSort(SS2);
}
Then I use
SelText2=SS1.options[i].attr("selected");
But it's not working. If I use:
SelText2=SS1.options[i].select=true;
then option looks like:
<option value="3" selected="">Delivery</option>
But it should be:
<option value="3" selected="selected">Delivery</option>
In the option tag, the attribute selected doesn't need a value:
<option value="3" selected>Delivery</option>
is the same as
<option value="3" selected="selected">Delivery</option>
check it here:
http://jsfiddle.net/n99L2xhv/1/
you should use .prop not .attr
e.g.
SelText2=SS1.options[i].prop("selected", true);
for reference: .prop() vs .attr()
Update I would go about doing this as follows;
<select id="select1">
<option value="1">Option1</option>
<option value="2">Option2</option>
</select>
<select id="select2">
<option value="3">Option3</option>
</select>
$("#select1").change(function(){
$("#select1 option:selected").each(function() {
var option = $(this);
$("#select2").append(option);
$("#select1").remove(option);
});
});
This will shift the selected option from Select 1 to Select 2 when it is chosen.
As pointed out by David Thomas in the comments, .attr() is not a valid method on a select element; It is a method on a jQuery object, which you don't have.
You could just pass true as the parameter to the Option constructor, and the third parameter is really the defaultSelected property, while the fourth paramter is the selected property.
for (var i = SS1.options.length - 1; i >= 0; i--) {
var option = SS1.options[i];
if (option.selected) {
SS2.add(new Option(option.text, option.value, false, true));
SS1.remove(i);
}
}
You could use option.selected instead of true, but because of the if-statement, you know option.selected will always be true.
jsfiddle

Auto select pre and next option for html select tag

I have this select tag:
<select name="test">
<option value="stack">Stack</option>
<option value="overflow" selected>Overflow</option>
<option value="my">My</option>
<option value="question">Question</option>
</select>
For example I selected the overflow option. How can I auto select the prev option and next option of my selected option, with jquery?? I don't have to use the namo or the value, just select the previos or next option, whatever it is.
Thanks for help!!!
You can do it, if you add multiple attribute to the select
$('select').change(function () {
var i = $(this).find(":selected");
var arr = $(this).children();
i.next().prop('selected', true);
i.prev().prop('selected', true);
});
DEMO
I'm not sure I understand the use case, but here are two functions that will do what you want:
function selectPrev() {
// get the selected option
var $selected = $("select[name=test]").find('option:selected');
// remove the selected property
$selected.prop("selected", false);
// get previous option and add selected property
var $prev_option = $selected.prev().prop("selected", true);
}
function selectNext() {
// get the selected option
var $selected = $("select[name=test]").find('option:selected');
// remove the selected property
$selected.prop("selected", false);
// get next option and add selected property
var $next_option = $selected.next().prop("selected", true);
}

Is there any handler that can detect if a select field has any option selected without jQuery

When an option is selected that wasn't previously, the onChange handler can detect this. How can a preselected option be detected (i.e., whether a select field has any option selected)? Is this possible without jQuery? Is there a handler, such as onSelected (not the same as onSelect for highlighted text) for this event?
Example:
<select onSelected="FunctionRunIfOptionSelected()">
<option> ... </option>
...
</select>
The preselected option will have been selected on page load. i.e., with the HTML dynamically rendered:
<option selected> ... </option>
If I understand, the task is to tell if an option has the selected attribute hard-coded into the HTML? If so, this should work:
function test () {
var opts = document.getElementById("myselect").options;
var i, len = opts.length;
for(i = 0; i < len; i++) {
if (opts[i].getAttribute("selected" ) != null ) { // opts[i] has the selected attribute
change_other_select(i); // pass the option index to your other function
break;
}
}
}
window.onload = test;
The trick is to distinguish between the selected property and the selected attribute, and also between a null value and an empty string.
var myselect = document.getElementByid('selectid');
myselect.options[myselect.selectedIndex];
To test for selected option on page load, you'll need to catch these in the window.onload handler
One the page is loaded you'll need to continue to use the onChange handler, but use selectedIndex property to test if this is populated with an index within your option list.
Alternatively give your options values in the HTML and check the values themselves. This will allow deterministic behavior when expanding the option list.
Yes, using the .options[] and .selectedIndex methods you can handle this cleanly and unobtrusively like so:
HTML
<select name="select" id="select">
<option value="">...</option>
<option value="1">One</option>
<option value="2" selected="selected">Two</option>
</select>
JavaScript
window.onload = function(){
var select = document.getElementById("select"), selected = select.value;
select.onchange = function(){
var val = select.options[select.selectedIndex].value;
if(val != selected) {
alert("Another value " + val + " was selected, which is not the same as the default value of " + selected);
} else {
alert("Same value as the default of " + selected + " was selected");
}
};
};
From within the JS, you can check and manipulate the val variable as you like.
You can detect if the select field does not have the default value selected like this:
var selects = document.getElementsByTagName("select");
for (i=0;i<selects.length;i++) {
if (selects[i].selectedIndex != 0) {
eval(selects[i].getAttribute("onSelected"));
}
}

Categories

Resources