Updating Selectbox options - javascript

I have 2 Selectbox
Countrynames
Airports
And as I select a countryname in first selectbox an Ajax request will be sent and it returns a list of Airposts as options like
"
<option value='1'>abc
<option value='3'>lmn
<option value='2'>xyz
"
now i have to replace only the options of select tag.
i am trying to do something like
var country_select = document.getElementById("country_select");
country_select.options.length = 0;
country_select.options = response.responseText
but this assignment is not working how may i get it done!

Try
var country_select = document.getElementById("country_select");
country_select.innerHTML = response.responseText;

This is a little bit more tricky, you won't be able to do it using innerHTML or anything like that.
You will have to change the way your ajax is returning airport names. Instead of <option>abc</option><option>xyz</option> return a string of names seperated by for example || : abc||def||xyz . then explode the string into an array in JS, create an option elements from every element in array, and add it to dropdown. check that:
<html>
<head>
<script>
var ajaxResponse = "abs||def||xyz||test||blah";
function updateOptions( optionsString )
{
var options = optionsString.split("||");
for( var i=0; i< options.length; i++ )
{
AddItem( options[i], options[i] );
}
}
function AddItem(Text,Value)
{
var opt = document.createElement("option");
opt.text = Text;
opt.value = Value;
document.getElementById("mydropdown").options.add(opt);
}
function removeOptions()
{
document.getElementById('mydropdown').length = 0;
}
</script>
</head>
<body>
<input type="button" onclick="updateOptions(ajaxResponse)" value="update"></input>
<input type="button" onclick="removeOptions()" value="remove"></input>
<select id="mydropdown">
</select>
</body>
</html>

Related

How do I get javascript to see updated select value?

I have a page with about 100 dropdown menus that I need to pass to another. So, I've put everything in an array that I'm sending via javascript. However, I'm not sure how to get the javascript to see the changed values of the dropdowns before sending. I mocked up some code to give you an idea of the problem. It only sends the value of the dropdown box at the time the page is initialized. Any help would be appreciated.
<select id="mydropdown">
<option value="Milk">Fresh Milk</option>
<option value="Cheese">Old Cheese</option>
<option value="Bread">Hot Bread</option>
</select>
<script>
var data = new Array();
data[0] = document.getElementById("mydropdown").value;
</script>
<form name="data" method="POST" action="passdata1b.php">
<input type="hidden" name="data">
</form>
<script>
function sendData()
{
// Initialize packed or we get the word 'undefined'
var packed = "";
for (i = 0; (i < data.length); i++) {
if (i > 0) {
packed += ",";
}
packed += escape(data[i]);
}
document.data.data.value = packed;
document.data.submit();
}
</script>
<h1>This is what the array contains:</h1>
<ul>
<script>
for (i = 0; (i < data.length); i++) {
document.write("<li>" + data[i] + "</li>\n");
}
</script>
</ul>
Go to passdata1b.php
Sam's answer was good, except..
data[0] = document.getElementById("mydropdown").value;
..that won't work since it's a dropdown menu. Instead get the value of the selected option. Use this instead:
var zeData = document.getElementById("mydropdown");
data[0] = zeData.options[zeData.selectedIndex].value;
Why can't you put this logic:
var data = new Array();
data[0] = document.getElementById("mydropdown").value;
In your sendData() function?
Comment if you need an example, but this should be a pretty easy fix. That way, when you click the link and run sendData(), it will parse the mydropdown value..instead of doing it on page load.

Dynamically adding a new option value to a selectbox if it isn't already in there

I have a small bit of a delema.
I have the following static select box below, however, the database will compare its cell value to that of the select box and select it.
My question to you is how can I design a function that would dynamically add a new select option (at the end of the existing list) if it already isn't in the list?
This doesn't seem to be working for me?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function test() {
//document.getElementById('name').innerHTML = "test"
document.getElementById('name').text = "test"
}
</script>
</head>
<body>
<select id="name">
<option value=""></option>
<option value="John">John</option>
<option value="Patrick">Patrick</option>
<option value="Jean">Jean</option>
<option value="Jackie">Jackie</option>
<option value="Stephanie">Stephanie</option>
<option value="Nicole">Nicole</option>
<option value="Lucie">Lucie</option>
</select>
<input id="btn1" type="button" value="testme" onclick="test()" />
</body>
</html>
You'll have to check each one:
function test() {
var checkWhat = 'test'; // value to check for
var options = document.getElementById('name').getElementsByTagName('option'),
exists = false;
for (var i=options.length; i--;) {
if ( options[i].value == checkWhat ) {
exists = true; // an option with that value already exists
break;
}
}
if (!exists) {
var option = document.createElement('option');
option.value = 'test';
option.innerHTML = 'test';
document.getElementById('name').appendChild(option);
}
}
You could create a function which loops through all the options in the select element and if the option value doesn't already exist, append it to the select tag.
var addOption = function(value){
var select = document.getElementById('name'), // get the select tag
options = select.getElementsByTagName('option'), // get all option tags within that select
alreadyExists = false;
for(var i = 0, l = options.length; i < l; i++){ // loop through the existing options
if(options[i].value == value) // check if value already exists
alreadyExists = true;
}
if(!alreadyExists){ // if value doesn't already exist
var newOption = document.createElement('option');// create a new option and add it to the select
newOption.value = value;
newOption.innerHTML = value;
select.appendChild(newOption);
}
};
Demo: http://jsfiddle.net/2TZ45/

drop down list items taken from the java script

<select id="myList" onchange="favBrowser()">
<option> var x</option>
<option> var y</option>
</select>
<script>
var x="google"; var y="firefox";
</script>
my question is , how to take the option's values from javascript
i think he ment he want to fill the options by Script
this can be done by
<select id="myDropdown">
</select>
<script type="text/javascript">
function fillDropDown() {
var ddl = document.getElementById('myDropdown');
for (var i = 1; i < 50; i++) {
var myNewOption = new Option();
myNewOption.value = i;
myNewOption.text = "my " + i.toString() + " option...";
ddl.options.add(myNewOption);
}
}
fillDropDown();
</script>
Cheers.
You can get it by writing
function favBrowser(){
var sel = document.getElementById("myList");
var value =sel.options[sel.selectedIndex].value;
window.alert(value);
}
You need to supply more information about what it is you really want to do. If what you want is to take the selected value, then take a look at this question
Get selected value in dropdown list using JavaScript?

How to get focus for selected values when multiselect combo is used

I'm using a multiselect combobox, i select few values from the combobox and save the selected values to db. when i reopen the page, i need the focus to be placed on the values which was selected and saved.
function getSelectedValues() {
var from = document.getElementById("309127");
var to;
var v = from.options.length;
var selectedValues = "";
for (var i = 0; i < v; i++) {
if (from.options[i] && from.options[i].selected) {
var CVal = from.options[i].value;
var CText = from.options[i].text;
if (selectedValues == "") {
selectedValues = CVal;
}
else {
selectedValues = selectedValues + "~" + CVal;
}
}
}
return selectedValues;
}
this is the javascript function i used to save the selected values in db.
can anybody help me out on how to get the focus back on selected items ?
thank you
To set the focus with javascript you can use
document.getElementById("309127").focus();
For your question I'm assuming you send the values to a PHP page or something similar to update the database. If so your problem will be getting the selected values when you return to your page. Two suggestions:
Use ajax to update the database so you dont need to exit the page,
Pass the selected values back to your page through GET or similar and set the focus on page load.
EDIT: -------------
For example if you pass the values through GET like (www.example.com?param1=three)
You can use javascript to select that value on load:
<html>
<body onload="load()">
<select id="example">
<option value="one"> one </option>
<option value="two"> two </option>
<option value="three"> three </option>
</select>
</body>
<script>
function load(){
var param1 = getParameterByName("param1");
var selected = document.getElementById('example');
var opts = selected.options.length;
for (var i=0; i<opts; i++){
if (selected.options[i].value == param1){
selected.options[i].selected = true;
break;
}
}
}
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
</script>
</html>
try var from = document.getElementById("309127");from.focus();

How to set selectedIndex of select element using display text?

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

Categories