Below code suppose to match the dropdown list with the div content. If "Pineapple" is found, then select this option. I couldn't seem to find the error.
<head>
<script>
function displayResult(){
var myObject=document.getElementById("mySelect");
var myValue = $('#myContent').text();
for(var i=0; i<myObject.length; i++){
if(myObject.options[i].text == myValue){
myObject.options[i].selected = true;
(also tried - myObject.options[i].selectedIndex = i;)
break;
}
}
}
</script>
</head>
<body>
<div id="myContent">Pineapple</div>
<form>
Select your favorite fruit:
<select id="mySelect" size="4">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
</form>
<button type="button" onclick="displayResult()">Highlight Pineapple Option</button>
</body>
Note:
I want the option to be highlighted. Missing the closing bracket was a typo, corrected. Tried .selectedIndex=i, didn't seem to do the trick.
You are missing a } at the end of the function.
And you should either include jQuery library or change
var myValue = $('#myContent').text();
to
var myValue = document.getElementById('myContent').innerHTML;
A simpler trick to use, though, is (not a good trick afterall...see #RobG's comment)
function displayResult() {
var myObject = document.getElementById("mySelect");
var myValue = document.getElementById('myContent').innerHTML;
myObject.value = myValue;
}
but for IE the options will need to include the value attribute
<option value="Pineapple">Pineapple</option>
You're missing the closing bracket to displayResult.
Instead of:
> myObject.options[i].selected = true;
use
myObject.selectedIndex = i;
Setting the selected property to true doesn't necessarily make the option selected (it varies between browsers).
Oh, and you have a syntax error:
<script>
function displayResult(){
var myObject=document.getElementById("mySelect");
var myValue = $('#myContent').text();
for(var i=0; i<myObject.length; i++){
...
}
// missing closing } for function body
</script>
Related
I have a script like this
<script type="text/javascript">
function showSelected(val){
document.getElementById
('selectedResult').innerHTML = "The selected number is - "
+ val;
}
</script>
<div id='selectedResult'></div>
<select name='test' onChange='showSelected(this.value)'>
<option value='1'>one</option>
<option value='2'>two</option>
</select>
The output is shown with
<div id='selectedResult'></div>
So, I want to use this a variable
Actually, I want to get drop down box value with out submit. This script make it, but I can use another suggestions
Thanks
I'm not sure I really understand the question, but if you want to get what's stored in the DIV, use:
var stuff = document.getElementById('selectedResult').innherHTML;
I can suggest you another alternative i think is more useful and you can use it in different way # your project.
In this example you click the options you one and insert them to option list, you can send them from your select name=test if you want, you just need to change it.
DEMO
This is the script you can catch item,links,images,attributes and add them to select box:
$(document).ready(function(){
$('li').on('click',function(){
$('#theSelect').append('<option SELECTED>'+$(this).find('img').attr('value')+'</option>');
var seen = {};
$('option').each(function() {
var txt = $(this).text();
if (seen[txt])
$(this).remove();
else
seen[txt] = true;
});
});
})
$('#del').click(function() {
var $list = $('#theSelect option');
var d = $list.length;
var b=($list.length-1);
$('#theSelect option:eq('+b+')').remove();
});
I am trying to create a function to run when a select option is changed. In my select menu i have;
<form id="frame">
<select id="frame_color" onchange="fChange()">
<option value="0">Polished Black</option>
<option value="1">Grey</option>
</select>
</form>
The only thing that I want the fChange() function to do is update the variable that is holding the options value with the onchange value. So, the variable in the function fChange starts off by holding the value "0", and when I change it to "Grey" I want the variable to update to "1". I am having a hard time figuring out how to code the function properly. Any suggestions?
following get the selected option value ...
function fChange()
{
var val = $("#frame_color").val();
}
fChange = function(){
var value = document.getElementById("frame_color").value;
alert(value);
}
try this, which is jQuery
<script type="text/javascript">
$(document).ready(function () {
$('#frame_color').change(function(){
// your code should be here
});
});
</script>
on jQuery:
$(function(){
$('#frame_color').on('change',function(){
your_variable = $(this).val()
});
});
for non-jQuery, a quick way to do it is:
document.getElementById('frame_color').onchange = function(e){
your_variable = e.target.value;
}
also, you might want to look at addEventListener for standards-compliant browsers, and attachEvent for IE6-8
var variable = 0;
function fChange()
{
var val = document.getElementById("frame_color").value;
variable = val;
}
<form id="frame">
<select id="frame_color" onchange="fChange()">
<option value="0">Polished Black</option>
<option value="1">Grey</option>
</select>
</form>
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>
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
Ok here's the deal, I'm trying to have a switch statement redirect to another page depending on what option is selected in a select box. Below is a sample i'm working with and trying to figure out, any help at all would be greatly apreciated.
<html>
<body>
<form name="form1">
<select name="select1">
<option value="p1">p1</option>
<option value="p2">p2</optino>
</select>
</form>
<script type="text/javascript">
<!--
var sel = document.form1.select1;
var txt = sel.options[sel.selectedIndex].text;
var opt = sel.options[sel.selectedIndex].value;
switch (sel)
{
case 'p1': window.location = 'http://www.yahoo.com'
break;
case 'p2': window.location = 'http://www.google..com'
break;
}
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
I recommend you avoid switch-statements. How about this?
<select name="select1">
<option data-url="http://www.yahoo.com" value="p1">p1</option>
<option data-url="http://www.google.com" value="p2">p2</option>
</select>
And:
document.getElementById("select1").onchange = function () {
var url = this.options[this.selectedIndex].getAttribute("data-url");
window.location = url;
};
Edit: I changed the example to use html 5 data attributes (not to worry, they are 100% supported in all browsers), since you need the value attribute for something else.
You need to bind an event handler
Your switch was using the wrong value
See http://www.jsfiddle.net/vDFpZ/
<html>
<body>
<form name="form1">
<select name="select1">
<option value="p1">p1</option>
<option value="p2">p2</option>
</select>
</form>
<script type="text/javascript">
window.onload = function () {
document.getElementsByName("select1")[0].onchange = function () {
var sel = this.options[this.selectedIndex];
var text = sel.text;
var val = sel.value;
switch (val)
{
case 'p1': window.location = 'http://www.yahoo.com'
break;
case 'p2': window.location = 'http://www.google..com'
break;
}
}
}
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
i noticed that you did not bind an change handler to the select, so when the user selects a value nothing happens.
You've got some typos, your second "/option" and your "google.com".
And the switch statement has nothing to do with your error.
You have no event listener/onchange handler and you aren't switching with the value from the select option
https://developer.mozilla.org/en/DOM/element.onchange
https://developer.mozilla.org/en/DOM/element.addEventListener