How to set selectedIndex of select element using display text? - javascript

How to set selectedIndex of select element using display text as reference?
Example:
<input id="AnimalToFind" type="text" />
<select id="Animals">
<option value="0">Chicken</option>
<option value="1">Crocodile</option>
<option value="2">Monkey</option>
</select>
<input type="button" onclick="SelectAnimal()" />
<script type="text/javascript">
function SelectAnimal()
{
//Set selected option of Animals based on AnimalToFind value...
}
</script>
Is there any other way to do this without a loop? You know, I'm thinking of a built-in JavaScript code or something. Also, I don't use jQuery...

Try this:
function SelectAnimal() {
var sel = document.getElementById('Animals');
var val = document.getElementById('AnimalToFind').value;
for(var i = 0, j = sel.options.length; i < j; ++i) {
if(sel.options[i].innerHTML === val) {
sel.selectedIndex = i;
break;
}
}
}

<script type="text/javascript">
function SelectAnimal(){
//Set selected option of Animals based on AnimalToFind value...
var animalTofind = document.getElementById('AnimalToFind');
var selection = document.getElementById('Animals');
// select element
for(var i=0;i<selection.options.length;i++){
if (selection.options[i].innerHTML == animalTofind.value) {
selection.selectedIndex = i;
break;
}
}
}
</script>
setting the selectedIndex property of the select tag will choose the correct item. it is a good idea of instead of comparing the two values (options innerHTML && animal value) you can use the indexOf() method or regular expression to select the correct option despite casing or presense of spaces
selection.options[i].innerHTML.indexOf(animalTofind.value) != -1;
or using .match(/regular expression/)

If you want this without loops or jquery you could use the following
This is straight up JavaScript. This works for current web browsers. Given the age of the question I am not sure if this would have worked back in 2011. Please note that using css style selectors is extremely powerful and can help shorten a lot of code.
// Please note that querySelectorAll will return a match for
// for the term...if there is more than one then you will
// have to loop through the returned object
var selectAnimal = function() {
var animals = document.getElementById('animal');
if (animals) {
var x = animals.querySelectorAll('option[value="frog"]');
if (x.length === 1) {
console.log(x[0].index);
animals.selectedIndex = x[0].index;
}
}
}
<html>
<head>
<title>Test without loop or jquery</title>
</head>
<body>
<label>Animal to select
<select id='animal'>
<option value='nothing'></option>
<option value='dog'>dog</option>
<option value='cat'>cat</option>
<option value='mouse'>mouse</option>
<option value='rat'>rat</option>
<option value='frog'>frog</option>
<option value='horse'>horse</option>
</select>
</label>
<button onclick="selectAnimal()">Click to select animal</button>
</body>
</html>
document.getElementById('Animal').querySelectorAll('option[value="searchterm"]');
in the index object you can now do the following:
x[0].index

Try this:
function SelectAnimal()
{
var animals = document.getElementById('Animals');
var animalsToFind = document.getElementById('AnimalToFind');
// get the options length
var len = animals.options.length;
for(i = 0; i < len; i++)
{
// check the current option's text if it's the same with the input box
if (animals.options[i].innerHTML == animalsToFind.value)
{
animals.selectedIndex = i;
break;
}
}
}

You can set the index by this code :
sel.selectedIndex = 0;
but remember a caution in this practice, You would not be able to call the server side onclick method if you select the previous value selected in the drop down..

Add name attribute to your option:
<option value="0" name="Chicken">Chicken</option>
With that you can use the HTMLOptionsCollection.namedItem("Chicken").value to set the value of your select element.

You can use the HTMLOptionsCollection.namedItem()
That means that you have to define your select options to have a name attribute and have the value of the displayed text.
e.g
California

Related

Alter an existing script that works

I do not want to use JQuery. Here is a simple piece of javascript that works that allows you to search a dropdown menu list:
<HTML><HEAD><SCRIPT type="text/javascript">
function searchSel() {
var input=document.getElementById('realtxt').value.toLowerCase();
var output=document.getElementById('realitems').options;
for(var i=0;i<output.length;i++) {
if(output[i].value.indexOf(input)==0){
output[i].selected=true;
}
if(document.getElementById('realtxt').value==''){
output[0].selected=true;
}
}
}
</SCRIPT></HEAD><BODY>
<FORM>
Search <input type="text" id="realtxt" onkeyup="searchSel()">
<SELECT id="realitems">
<OPTION value="">Select...
<OPTION value="afghanistan">Afghanistan
<OPTION value="albania">Albania
<OPTION value="algeria">Algeria
<OPTION value="andorra">Andorra
<OPTION value="angola">Angola
</SELECT>
</FORM></BODY></HTML>
The problem is that in order for it to work, the value of each option has to have the text. I tried changing the "value" fields in the javascript code to "name" so that it would search the name only, but no go. My option fields have numbers, and I cannot easily convert them to names. Is there a way to tweak this javascript to work with names or better yet search within the option tags?
You will need to change two things in the line
if(output[i].value.indexOf(input)==0){
use the .text property instead of .value at your <option> elements.
make it lowercase to match the lowercased input. With lowercase value attributes and numbers you did not have this problem.
This script would be the result:
function searchSel() {
var input = document.getElementById('realtxt').value.toLowerCase(),
len = input.length,
output = document.getElementById('realitems').options;
for(var i=0; i<output.length; i++)
if (output[i].text.toLowerCase().slice(0, len) == input)
output[i].selected = true;
if (input == '')
output[0].selected = true;
}
I also have used an improved startswith check.
This line:
var input=document.getElementById('realtxt').value.toLowerCase();
makes input a string.
<OPTION value=1>text
value is an integer.String will never == integer.
Change
if(output[i].value.indexOf(input)==0) to
to
if((output[i].value.indexOf(input)==0) || (output[i].value.indexOf(parseInt(input)))
use this code, i have replaced "value" with "innerHTML"
function searchSel() {
var input = document.getElementById('realtxt').value.toLowerCase();
var output = document.getElementById('realitems').options;
for (var i = 0; i < output.length; i++) {
if (output[i].innerHTML.indexOf(input) == 0) {
output[i].selected = true;
}
if (document.getElementById('realtxt').value == '') {
output[0].selected = true;
}
}
}

Replace option code with another code by using option index

I have a dropdown list
<select name="answers[0][]">
<option value="0" >Beredskap</option>
<option value="1" >Förbundsledning</option>
<option value="2" >Förbundsledning stab</option>
<option value="3" >Ekonomiavdelningen</option>
</select>
What i am seeking for is to get the value getElementsByTagName('select')[1] and then replace it with
<option value="1" disabled >Förbundsledning</option>
the reason for it is that the list is auto generated so i need to modify the html output instead.
what i have sofar that does not work is :
document.getElementsByTagName('select')[0]
.innerHTML.replace('<option value="1" disabled>apple</option>')
The option with the value 1 happens to be at index 1 in your code, should that always be the case other answers than this one will apply.
In the case where you don't know the order of the generated options and thus don't know the index of the option you want to change, it depends on whether you want to change the text based on the value or the original text.
You could do this:
var options = document.getElementsByTagName("option");
for(var e = 0; e < options.length; e++) {
//change by text
if (options[e].text == "Apple") {
options[e].text = "Förbundsledning";
}
//change by value
if (options[e].value == "1") {
options[e].text = "Förbundsledning";
}
}
you could use jQuery and selectors to find your list box $('#myListBox').val();
you can easily change the value by $('#myListBox').val("new value");
You can also easily iterate over the list of options and do whatever you wish.
$("#id option").each(function()
{
// add $(this).val() to your list
});
How about this ?
var sel = document.getElementsByTagName('select')[0];
sel.innerHTML = sel.innerHTML.replace('Förbundsledning', 'apple');
http://jsfiddle.net/VxhvF/
use function ;
function select_text_replace(option_text, replace_text) {
var el = document.getElementsByTagName('select')[0];
el.innerHTML = el.innerHTML.replace(option_text, replace_text);
};
select_text_replace("Förbundsledning", "apple");
select_text_replace("Ekonomiavdelningen", "apple2");
see sample: http://jsfiddle.net/sm94N/
document.getElementsByTagName('select')[0].options[1].text="apple"
[1] is index of your options item. 0 = Beredskap, 1 = Förbundsledning.

Change Select tag value using JavaScript

I'm trying to change a value from a select tag using JavaScript. Let's say that I have this textbox, and if that textbox is null, no changes will be done and the value of the select tag options will be as is. But if that textbox is filled, then I have to assign a different value aside from the ones in the select tag options.
Here's what I'm trying to do:
HTML:
<input type="text" id="txtTest" />
<select name="rdoSelect" id="rdoSelect">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
JavaScript:
if (document.getElementById('txtTest').value===null)
{
document.getElementById('rdoSelect').value;
}
else
{
document.getElementById('rdoSelect').value = "option 3";
}
I can't make it work. I've tried pointing it to an element/variable rather than to a value and it still doesn't work:
var test = document.getElementById('rdoSelect');
test.value = "option 3";
I need help, please. Thanks!
Try using SelectIndex method. Please refer the below code.
I added OnChange event to input text to test this sample.
<html>
<head>
<script language="javascript">
function test()
{
if (document.getElementById('txtTest').value=='')
{
document.getElementById("rdoSelect").selectedIndex = 0;
}
else
{
document.getElementById("rdoSelect").selectedIndex = 1;
}
}
</script>
</head>
<body>
<input type="text" id="txtTest" onchange="test();" />
<select name="rdoSelect" id="rdoSelect">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
</body>
</html>
HTMLSelectElement doesn't let you set the value directly. It's possible to have many or zero <option>s with a particular value, so it's not a straightforward 1:1 mapping.
To select an option you can either set its selected property to true, or set the selectedIndex property of the select to the option number.
There is no option 3 in your select—are you trying to add a new option?
eg
function setOrCreateSelectValue(select, value) {
for (var i= select.options.length; i-->0;) {
if (select.options[i].value==value) {
select.selectedIndex= i;
return;
}
}
select.options[select.options.length]= new Option(value, value, true, true);
}
Is this happening on button click or onkeyup? Either way in the function you can add value to dropdownlist using this:
dropdownlist.append(
$("<option selected='selected'></option>").val(sValId).html(sVal)
);
Or you colud try this
var optn = document.createElement("OPTION");
optn.text = "--Select--";
optn.value = "0";
baseCurve.options.add(optn);`
if (document.getElementById('txtTest').value===null)
{
document.getElementById('rdoSelect').value;
}
else
{
var val = document.getElementById('txtTest').value
for(var i, j = 0; i = rdoSelect.options[j]; j++) {
if(i.value == val) {
rdoSelect.selectedIndex = j;
break;
}
}
}
Take a look at this jsfiddle, it's using jquery, which
is probably the most common solution. Hope it helps.
http://jsfiddle.net/GkLsZ/
$(function() {
$('#btnChange').on('click', function() {
var value = $.trim($('#txtTest').val());
if (!!value) {
$('#rdoSelect')
.append($("<option></option>")
.attr("value", value)
.attr("selected", "selected")
.text(value));
}
});
});

How would I dynamically create input boxes on the fly?

I want to use the value of a HTML dropdown box and create that number of input boxes underneath. I'm hoping I can achieve this on the fly. Also if the value changes it should add or remove appropriately.
What programming language would I need to do this in? I'm using PHP for the overall website.
Here is an example that uses jQuery to achieve your goals:
Assume you have following html:
<div>
<select id="input_count">
<option value="1">1 input</option>
<option value="2">2 inputs</option>
<option value="3">3 inputs</option>
</select>
<div>
<div id="inputs"> </div>
And this is the js code for your task:
$('#input_count').change(function() {
var selectObj = $(this);
var selectedOption = selectObj.find(":selected");
var selectedValue = selectedOption.val();
var targetDiv = $("#inputs");
targetDiv.html("");
for(var i = 0; i < selectedValue; i++) {
targetDiv.append($("<input />"));
}
});
You can simplify this code as follows:
$('#input_count').change(function() {
var selectedValue = $(this).val();
var targetDiv = $("#inputs").html("");
for(var i = 0; i < selectedValue; i++) {
targetDiv.append($("<input />"));
}
});
Here is a working fiddle example: http://jsfiddle.net/melih/VnRBm/
You can read more about jQuery: http://jquery.com/
I would go for jQuery.
To start with look at change(), empty() and append()
http://api.jquery.com/change/
http://api.jquery.com/empty/
http://api.jquery.com/append/
Doing it in javascript is quite easy. Assuming you've got a number and an html element where to insert. You can obtain the parent html element by using document.getElementById or other similar methods. The method assumes the only children of the parentElement is going to be these input boxes. Here's some sample code:
function addInput = function( number, parentElement ) {
// clear all previous children
parentElement.innerHtml = "";
for (var i = 0; i < number; i++) {
var inputEl = document.createElement('input');
inputEl['type'] = 'text';
// set other styles here
parentElement.appendChild(inputEl);
}
}
for the select change event, look here: javascript select input event
you would most likely use javascript(which is what jquery is), here is an example to show you how it can be done to get you on your way
<select name="s" onchange="addTxtInputs(this)" onkeyup="addTxtInputs(this)">
<option value="0">Add</option>
<option value="1">1</option>
<option value="3">3</option>
<option value="7">7</option>
</select>
<div id="inputPlaceHolder"></div>
javascript to dynamically create a selected number of inputs on the fly, based on Mutahhir answer
<script>
function addTxtInputs(o){
var n = o.value; // holds the value from the selected option (dropdown)
var p = document.getElementById("inputPlaceHolder"); // this is to get the placeholder element
p.innerHTML = ""; // clears the contents of the place holder each time the select option is chosen.
// loop to create the number of inputs based apon `n`(selected value)
for (var i=0; i < n; i++) {
var odiv = document.createElement("div"); //create a div so each input can have there own line
var inpt = document.createElement("input");
inpt['type'] = "text"; // the input type is text
inpt['id'] = "someInputId_" + i; // set a id for optional reference
inpt['name'] = "someInputName_" + i; // an unique name for each of the inputs
odiv.appendChild(inpt); // append the each input to a div
p.appendChild(odiv); // append the div and inputs to the placeholder (inputPlaceHolder)
}
}
</script>

Search a dropdown

I have this HTML dropdown:
<form>
<input type="text" id="realtxt" onkeyup="searchSel()">
<select id="select" name="basic-combo" size="1">
<option value="2821">Something </option>
<option value="2825"> Something </option>
<option value="2842"> Something </option>
<option value="2843"> _Something </option>
<option value="15999"> _Something </option>
</select>
</form>
I need to search trough it using javascript.
This is what I have now:
function searchSel() {
var input=document.getElementById('realtxt').value.toLowerCase();
var output=document.getElementById('basic-combo').options;
for(var i=0;i<output.length;i++) {
var outputvalue = output[i].value;
var output = outputvalue.replace(/^(\s| )+|(\s| )+$/g,"");
if(output.indexOf(input)==0){
output[i].selected=true;
}
if(document.forms[0].realtxt.value==''){
output[0].selected=true;
}
}
}
The code doesn't work, and it's probably not the best.
Can anyone show me how I can search trough the dropdown items and when i hit enter find the one i want, and if i hit enter again give me the next result, using plain javascript?
Here's the fixed code. It searches for the first occurrence only:
function searchSel() {
var input = document.getElementById('realtxt').value;
var list = document.getElementById('select');
var listItems = list.options;
if(input === '')
{
listItems[0].selected = true;
return;
}
for(var i=0;i<list.length;i++) {
var val = list[i].value.toLowerCase();
if(val.indexOf(input) == 0) {
list.selectedIndex = i;
return;
}
}
}
You should not check for empty text outside the for loop.
Also, this code will do partial match i.e. if you type 'A', it will select the option 'Artikkelarkiv' option.
Right of the bat, your code won't work as you're selecting the dropdown wrong:
document.getElementById("basic-combo")
is wrong, as the id is select, while "basic-combo" is the name attribute.
And another thing to note, is that you have two variable named output. Even though they're in different scopes, it might become confusing.
For stuff like this, I'd suggest you use a JavaScript library like jQuery (http://jquery.com) to make DOM interaction easier and cross-browser compatible.
Then, you can select and traverse all the elements from your select like this:
$("#select").each(function() {
var $this = $(this); // Just a shortcut
var value = $this.val(); // The value of the option element
var content = $this.html(); // The text content of the option element
// Process as you wish
});

Categories