Hi is there anyway to return the index of an option by it's text? (without jquery or any lib)
<select>
<option>I</option> //0
<option>Love</option> //1
<option>my</option> //2
<option>granny<option> //3
</select>
say for example I'll pass a string "granny" it'll return 3
If you have a select element that looks like this:
<select id="ddlViewBy">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
Running this code:
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;
Sorry for being inactive for few days, here's the one I made, It'll return the index of an option based on the needed string, not the value. I just thought there's an easy function to do the process but I think there's none. just in case, this will do.
HTML
<select id = "myDropDown">
<option>I</option> //0
<option>Love</option> //1
<option>my</option> //2
<option>granny<option> //3
</select>
Javascript
var dropDownList = document.getElementById("myDropDown");
var str = "granny";
var i =0;
for(i=0;i<dropDownList.length;i++){
if(dropDownList.options[i].text == str){
console.log("index: " + i);
}
}
<select>
<option value="0">I</option> //0
<option value="1">Love</option> //1
<option value="2">my</option> //2
<option value="3">granny<option> //3
</select>
Getting the index
Fiddle
Javascript code
function findIndex() {
var e = document.getElementById("select1");
alert(e.selectedIndex);
}
HTML
<select id="select1" onchange="findIndex()">
<option>I</option>
<option>Love</option>
<option>my</option>
<option>granny</option>
</select>
I think you want to retrieve the selected Index on change event of Select so you can try the following Code.
jsFiddle
HTML
<select id="select1">
<option>I</option>
<option>Love</option>
<option>my</option>
<option>granny</option>
</select>
JavaScript
var select1=document.getElementById("select1");
select1.onchange=function(){
var s=document.getElementById("select1").selectedIndex;
alert(s);
}
yes and example here from w3chools
http://www.w3schools.com/jsref/prop_option_value.asp
Related
I am tring to set selected values in a dropdown from a comma seperated string,here i want to set text1,text2,text3,text4 as selected in the dropdown.
Thanks..
var string='text1,text2,text3,text4';
<select id="dropdown">
<option value="0">text1</option>
<option value="1">text2</option>
<option value="2">text3</option>
<option value="3">text4</option>
<option value="4">text5</option>
<option value="5">text6</option>
<option value="6">text7</option>
</select>
Here we go, you can make selected values like following:
var string='text1,text2,text3,text4';
var opts = string.split(",");
function selectOptions() {
var obj = $('#dropdown');
for (var i in opts) {
obj.find('option[value=' + i + ']').prop('selected', true);
}
}
selectOptions();
Fiddle Demo
Hope this will work!
I think you can use string.split(',')
Here is my code
I have ddlvehicle like below
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
ddl=Ctrl("ddlvehicle");
$("#ddltrVehicle").empty();
for(var i=2;i<=ddl.options.length;i++)
{
$("#ddltrVehicle").append("<option value="+ddl.options[i-1].value+">"+ddl.options[i-1].value+"</option>");
}
I want to assign the ddlvehicle to ddltrvehicle , my code only results like the below
I have ddltrVehicle like below
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
please help to get the ddltrVehicle like ddlvehicle.
Thanks in advance.
Try to use text like,
var ddl=$("#ddlvehicle")[0];
$("#ddltrVehicle").empty();
for(var i=2;i<=ddl.options.length;i++)
{
$opt="<option value="+ddl.options[i-1].value+">"+ddl.options[i-1].text+"</option>";
// ---------------------------------------- ^ Use text here
$("#ddltrVehicle").append($opt);
}
Demo
Let try this:
for(var i = 0; i < $('#ddlvehicle').children().length; i++){
$('#ddltrvehicle').append($('#ddlvehicle').children().eq(i));
}
I din't understand question well, but if you want to copy all options of ddlvehicle to ddltrvehicle -
Try this:
$('#ddltrVehicle').html($('#ddlvehicle').html().trim());
In jsfiddle
try something like this
$(function(){
$('#ddltrvehicle').html('');
var option = '';
$('#ddlvehicle option').each(function(){
option += '<option value="'+this.value+'">'+this.value+'</option>';
})
$('#ddltrvehicle').html(option);
})
Following my code:
<select>
<option value="1">Test</option>
<option value="2">Test2</option>
</select>
How to change with pure javascript cross browser the first "Test" and the second "Test2"?
Use the options from the select element (I gave your select an ID of someSelect for this demo:
function alterSelect() {
var select = document.getElementById("someSelect");
for (var i = 0; i < select.options.length; i++) {
select.options[i].text = "New stuff " + i;
}
}
This will replace each option text with: New stuff number -- where number is the iteration number of the for-loop. See demo at: http://jsfiddle.net/4PyGC/
You can solve the problem like this:
HTML
<select id="myOptions">
<option value="1">Test</option>
<option value="2">Test2</option>
</select>
Javascript
function change() {
document.getElementById('myOptions').options[0].innerHTML = "New Text";
document.getElementById('myOptions').options[1].innerHTML = "New Text 2";
}
change();
Also, here's a demo you use to verify:
DEMO
http://jsfiddle.net/kBd79/
You can just change the innerHTML of the <option> tag
In my HTML, I have a <select> with three <option> elements. I want to use jQuery to check each option's value against a Javascript var. If one matches, I want to set the selected attribute of that option. How would I do that?
Vanilla JavaScript
Using plain old JavaScript:
var val = "Fish";
var sel = document.getElementById('sel');
document.getElementById('btn').onclick = function() {
var opts = sel.options;
for (var opt, j = 0; opt = opts[j]; j++) {
if (opt.value == val) {
sel.selectedIndex = j;
break;
}
}
}
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<button id="btn">Select Fish</button>
jQuery
But if you really want to use jQuery:
var val = 'Fish';
$('#btn').on('click', function() {
$('#sel').val(val);
});
var val = 'Fish';
$('#btn').on('click', function() {
$('#sel').val(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<button id="btn">Select Fish</button>
jQuery - Using Value Attributes
In case your options have value attributes which differ from their text content and you want to select via text content:
<select id="sel">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
<script>
var val = 'Fish';
$('#sel option:contains(' + val + ')').prop({selected: true});
</script>
Demo
But if you do have the above set up and want to select by value using jQuery, you can do as before:
var val = 3;
$('#sel').val(val);
Modern DOM
For the browsers that support document.querySelector and the HTMLOptionElement::selected property, this is a more succinct way of accomplishing this task:
var val = 3;
document.querySelector('#sel [value="' + val + '"]').selected = true;
Demo
Knockout.js
<select data-bind="value: val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
<script>
var viewModel = {
val: ko.observable()
};
ko.applyBindings(viewModel);
viewModel.val(3);
</script>
Demo
Polymer
<template id="template" is="dom-bind">
<select value="{{ val }}">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</template>
<script>
template.val = 3;
</script>
Demo
Angular 2
Note: this has not been updated for the final stable release.
<app id="app">
<select [value]="val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</app>
<script>
var App = ng.Component({selector: 'app'})
.View({template: app.innerHTML})
.Class({constructor: function() {}});
ng.bootstrap(App).then(function(app) {
app._hostComponent.instance.val = 3;
});
</script>
Demo
Vue 2
<div id="app">
<select v-model="val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
val: null,
},
mounted: function() {
this.val = 3;
}
});
</script>
Demo
None of the examples using jquery in here are actually correct as they will leave the select displaying the first entry even though value has been changed.
The right way to select Alaska and have the select show the right item as selected using:
<select id="state">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
</select>
With jquery would be:
$('#state').val('AK').change();
You can change the value of the select element, which changes the selected option to the one with that value, using JavaScript:
document.getElementById('sel').value = 'bike';
DEMO
Markup
<select id="my_select">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
jQuery
var my_value = 2;
$('#my_select option').each(function(){
var $this = $(this); // cache this jQuery object to avoid overhead
if ($this.val() == my_value) { // if this option's value is equal to our value
$this.prop('selected', true); // select this option
return false; // break the loop, no need to look further
}
});
Demo
I want to change the select element's selected option's both value & textContent (what we see) to 'Mango'.
Simplest code that worked is below:
var newValue1 = 'Mango'
var selectElement = document.getElementById('myselectid');
selectElement.options[selectElement.selectedIndex].value = newValue1;
selectElement.options[selectElement.selectedIndex].textContent = newValue1;
Hope that helps someone. Best of luck.
Up vote if this helped you.
I used almost all of the answers posted here but not comfortable with that so i dig one step furter and found easy solution that fits my need and feel worth sharing with you guys.
Instead of iteration all over the options or using JQuery you can do using core JS in simple steps:
Example
<select id="org_list">
<option value="23">IBM</option>
<option value="33">DELL</option>
<option value="25">SONY</option>
<option value="29">HP</option>
</select>
So you must know the value of the option to select.
function selectOrganization(id){
org_list=document.getElementById('org_list');
org_list.selectedIndex=org_list.querySelector('option[value="'+id+'"]').index;
}
How to Use?
selectOrganization(25); //this will select SONY from option List
Your comments are welcome. :) AzmatHunzai.
Test this Demo
Selecting Option based on its value
var vals = [2,'c'];
$('option').each(function(){
var $t = $(this);
for (var n=vals.length; n--; )
if ($t.val() == vals[n]){
$t.prop('selected', true);
return;
}
});
Selecting Option based on its text
var vals = ['Two','CCC']; // what we're looking for is different
$('option').each(function(){
var $t = $(this);
for (var n=vals.length; n--; )
if ($t.text() == vals[n]){ // method used is different
$t.prop('selected', true);
return;
}
});
Supporting HTML
<select>
<option value=""></option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select>
<option value=""></option>
<option value="a">AAA</option>
<option value="b">BBB</option>
<option value="c">CCC</option>
</select>
Excellent answers - here's the D3 version for anyone looking:
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<script>
d3.select('#sel').property('value', 'Fish');
</script>
After a lot of searching I tried #kzh on select list where I only know option inner text not value attribute,
this code based on select answer I used it to change select option according to current page urlon this format
http://www.example.com/index.php?u=Steve
<select id="sel">
<option>Joe</option>
<option>Steve</option>
<option>Jack</option>
</select>
<script>
var val = window.location.href.split('u=')[1]; // to filter ?u= query
var sel = document.getElementById('sel');
var opts = sel.options;
for(var opt, j = 0; opt = opts[j]; j++) {
// search are based on text inside option Attr
if(opt.text == val) {
sel.selectedIndex = j;
break;
}
}
</script>
This will keeps url parameters shown as selected to make it more user friendly and the visitor knows what page or profile he is currently viewing .
You just write the code
var theVal = 1;
$('#variable_id').val(theVal).trigger('change');
I used this after updating a register and changed the state of request via ajax, then I do a query with the new state in the same script and put it in the select tag element new state to update the view.
var objSel = document.getElementById("selectObj");
objSel.selectedIndex = elementSelected;
I hope this is useful.
selectElement is a html <select> element.
Increment the value:
selectElement.selectedIndex++
Decrement the value:
selectElement.selectedIndex--
var accHos = document.getElementById("accHos");
function showName(obj) {
accHos.selectedIndex = obj.selectedIndex;
}
div {
color: coral;
}
select {
margin-left: 20px;
margin-bottom: 8px;
min-width: 120px;
}
<div>Select Account Number:</div>
<select id="accNos" name="" onchange="showName(this);">
<option value="">Select Account</option>
<option value="">1052021</option>
<option value="">2052021</option>
<option value="">3052021</option>
<option value="">4052021</option>
<option value="">5052021</option>
</select>
<div>Account Holder Name:</div>
<select id="accHos" name="" disabled>
<option value="">--Name--</option>
<option value="">Suhan</option>
<option value="">Cesur</option>
<option value="">Hopper</option>
<option value="">Rachel</option>
<option value="">Arya</option>
</select>
<!-- Just for my referece -->
Slightly neater Vanilla.JS version. Assuming you've already fixed nodeList missing .forEach():
NodeList.prototype.forEach = Array.prototype.forEach
Just:
var requiredValue = 'i-50332a31',
selectBox = document.querySelector('select')
selectBox.childNodes.forEach(function(element, index){
if ( element.value === requiredValue ) {
selectBox.selectedIndex = index
}
})
I have a select element wrapped by a span element. I am not allowed to use the select id but I am allowed to use the span id.
I am trying to write a javascript/jquery function in which the input is a number i, which is one of the values of the select's options. The function will turn the relevant option to selected.
<span id="span_id">
<select id="h273yrjdfhgsfyiruwyiywer" multiple="multiple">
<option value="1">cleaning</option>
<option value="2">food-2</option>
<option value="3">toilet</option>
<option value="4">baby</option>
<option value="6">knick-knacks</option>
<option value="9">junk-2</option>
<option value="10">cosmetics</option>
</select>
</span>
I wrote something as follows (this does not completely work, which is why I am posting this question):
function select_option(i) {
options = $('#span_id').children('select').children('option');
//alert(options.length); //7
//alert(options[0]); //[object HTMLOptionElement]
//alert(options[0].val()); //not a jquery element
//alert(options[0].value); //1
//the following does not seem to work since the elements of options are DOM ones not jquery's
option = options.find("[value='" + i + "']");
//alert(option.attr("value")); //undefined
option.attr('selected', 'selected');
}
Thanks!
Here's the simplest solution with a clear selector:
function select_option(i) {
return $('span#span_id select option[value="' + i + '"]').html();
}
With jQuery > 1.6.1 should be better to use this syntax:
$('#span_id select option[value="' + some_value + '"]').prop('selected', true);
Just wrap your option in $(option) to make it act the way you want it to. You can also make the code shorter by doing
$('#span_id > select > option[value="input your i here"]').attr("selected", "selected")
options = $("#span_id>select>option[value='"+i+"']");
option = options.text();
alert(option);
here is the fiddle http://jsfiddle.net/hRFYF/
You can use .val() to select the value, like the following:
function select_option(i) {
$("#span_id select").val(i);
}
Here is a jsfiddle: https://jsfiddle.net/tweissin/uscq42xh/8/
To get the value just use this:
<select id ="ari_select" onchange = "getvalue()">
<option value = "1"></option>
<option value = "2"></option>
<option value = "3"></option>
<option value = "4"></option>
</select>
<script>
function getvalue()
{
alert($("#ari_select option:selected").val());
}
</script>
this will fetch the values
function select_option(index)
{
var optwewant;
for (opts in $('#span_id').children('select'))
{
if (opts.value() = index)
{
optwewant = opts;
break;
}
}
alert (optwewant);
}
You can change with simple javascript
document.querySelector('#h273yrjdfhgsfyiruwyiywer').value='4'
<span id="span_id">
<select id="h273yrjdfhgsfyiruwyiywer" multiple="multiple">
<option value="1">cleaning</option>
<option value="2">food-2</option>
<option value="3">toilet</option>
<option value="4">baby</option>
<option value="6">knick-knacks</option>
<option value="9">junk-2</option>
<option value="10">cosmetics</option>
</select>
</span>
$("#h273yrjdfhgsfyiruwyiywer").children('[value="' + i + '"]').prop("selected", true);