I'm new to HTML5 and I'm trying to test the <select> with the attribute multiple in forms on Google Chrome. I encounter two problems.
Firstly, the options list changes in an ugly rectangle
Whereas before it was "normal":
My second problem is that, it seems that when i want to get the values of the select (by clicking on the button and in the code using javascript), only one is given...
Here is my code:
<!DOCTYPE html>
<html>
<body>
How do you travel?
<form method="get" id=myForm" onsubmit="done();">
<select name="transport" multiple> <optgroup label="Ecological">
<option value="Feet" selected>By Foot</option>
<option value="Bike">By Bike</option> </optgroup>
<optgroup label="Non-ecological">
<option value="public transports">With public transports</option> <option value="motorbike">By motorbike</option> <option value="car">By car</option>
</optgroup> </select>
<button onclick="bdone();">button</button>
<script>
function bdone(){
var mesOptions=document.getElementsByTagName('select')[0];
alert(mesOptions.value);
}
</script>
</body>
</html>
Thank you for reading me!
The Styling Issue
Just a note: the multiple attribute of the select element is not specifically HTML5.
The styling is going to depend on the CSS styles that are being applied, both the user agent styles (the default browser styles), and the specific CSS on that page. Try putting it in a page by itself (or in a jsFiddle and see if you get the same styling.
The selection issue
The selectedOptions property of the select element you get will contain an array of HTMLOptionElements, all of which have the value property. See below:
jsFiddle
function bdone(){
var selectElem = document.getElementsByTagName('select')[0]
var mesOptions = selectElem.selectedOptions;
for(var a=0;a<mesOptions.length;a++) {
alert(mesOptions[a].value);
}
}
Related
I have three options in a dropdown in html.Now on selecting each one of the option in dropdown i want different input types to be created dynamically.
Firstly here are the options in dropdown :
<select name="choicetosearch">
<option value="None" style="display:none;">
---None---
</option>
<option value="searchName">
Notification Sender
</option>
<option value="searchType">
Notification Type
</option>
<option value="searchDate">
Notification Date
</option>
</select>
Now, on selecting Notification Sender I want a textbox to be displayed.
On selecting Notification Type I want that two checkboxes should be shown.
On selecting Notification Date I want two date type input fields to be shown.
How this can be done?Please help.
You really need to learn some javascript since you didn't even provide any attemts to solve this problem.
Anyway, you need to create the fields you want to show/hide depending on the select box in your html markup and hide them via css. Afterwards you have to use an on change js event on your selectbox and check for the selected option. you now can hide/show the boxes you need.
Check this Example
JS:
$('.search-select').on('change', function(){
$('.search-inputs').children().hide();
var classn =$(this).find(":selected").val();
$('.'+classn).show();
})
HTML:
<select class="search-select" name="choicetosearch">
<option value="None">
---None---
</option>
<option value="searchName">
Notification Sender
</option>
<option value="searchType">
Notification Type
</option>
<option value="searchDate">
Notification Date
</option>
</select>
<div class="search-inputs">
<input class="searchName" type="text"></input>
<input class="searchType" type="checkbox"></input>
<input class="searchDate" type="text"></input>
</div>
Please make sure you refactor the classnames and values since I made this quickly.
In onchange event of select create the elements dynamically using
var dynElem = document.createElement('input');
dynElem.type = 'text';
dynElem.value = 'welcome';
then append the dynElem to Div using Javascript or Jquery like appendChild(dynElem) in javascript or append(dynElem) in jquery
Use 'onchange' attribute of 'select' element to track change of elements in dropDown. To add an element, first generate it some thing like this -
var elem = '<b> hey</b>;
Then you can use 'append(elem)' function in jQuery or 'appendChild(elem)' in javascript.
I am not giving you the code so that you can try it, but if it still doesn't work, ping me, and I will share the code.
Here's a demo -
http://jsfiddle.net/RcfNL/2/
Adding to it, you can get the selected value of the drop down using this -
var city_name = $('#city option:selected').text();
Based on the value, you can perform the required action.
Please you can use this code snippet to your code block or test it first then use it.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<style type="text/css">
.searchName, .searchType, .searchDate{
display:none;
}
</style>
<script src="jquery-1.7.1.js"></script>
<script type="text/javascript">
function createElement123(val){
$('.search-inputs').children().hide();
$('.' + val).show();
}
</script>
</head>
<body>
<select class="search-select" name="choicetosearch" onchange="createElement123(this.value)">
<option value="None">---None---</option>
<option value="searchName">Notification Sender</option>
<option value="searchType">Notification Type</option>
<option value="searchDate">Notification Date</option>
</select>
<div class="search-inputs">
<input class="searchName" type="text" />
<input class="searchType" type="checkbox" />
<input class="searchDate" type="date" />
</div>
</body>
</html>
Hope that it will help to solve your problem. #Cheers
The onchange event works great and populates my input (textbox) just fine, but when the onchange event is applied to the drop down box with only 1 single option in it, it does not work. How can I get the onchange to fire even if, there is one or multiple items?
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
</style>
<script type="text/javascript">
function test(x) {
var x = document.getElementById(x).options[document.getElementById(x).selectedIndex].text
document.getElementById('output').value = x
}//end of function
</script>
</head>
<body>
<select id="drop1" onchange="test(this.id)">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br><br>
<select id="drop2" onchange="test(this.id)">
<option value="volvo">Volvo</option>
</select>
<br><br>
<input type="text" id="output">
</body>
</html>
You could add an empty option at the top of every select box, or perhaps an option that just says -Select-. Then, if necessary, alter your script to ignore the empty selection.
If there is only one item, it never will change. Try onblur instead. Or maybe onclick, depending on what you are actually trying to do.
I am answering this question in case it can help somebody in 2020. I had the same problem populating data from the database into the form where there was a single data and I was able to solve this way. In the example am gonna use jquery for illustrations.
First you have to empty the select element using .empty() function.
$('#drop2').empty();
Secondly add an empty value into the select using .append()
$('#drop2').append("<option value='0'>Select</option>");
After that now you can go ahead to add your data into the select element because they are going to be two options, one empty while the other carries the data.
Finally populate your data from server this way using ajax in success function
success:function(response){
$('#drop2').empty().append("<option value='0'>Select</option>");
response.forEach((item)=>{
$('#drop2').append("<option value='"+item[]+"'>"+item[1]</option>");
});
I have used the arrow function .forEach()
If you've come here in 2022 then this is the answer you are looking for:
The easiest solution is to simply put hidden in a 'placeholder' option tag.
<select>
<option hidden value="dontselect">Spinny wheely bois</option>
<option value="volvo">Volvo</option>
</select>
This means that there will always be 2 or more options in the select but the placeholder option does not show in the drop-down list (so won't be able to be selected). The placeholder should be the first option tag inside select just to make your life easier.
But it does mean that when you click the one actual option you'll trigger onChange as internally the select is changing value.
I have a select with some values in it. each value loads a different webpage.
I want the default value that always shows to be "Select page".
How can I highlight the option for the current page when the user clicks on the dropdown?
By highlight i mean either have it selected or change its background colour or something.
HTML:
<select id="siteId" name="siteId" onchange=".....">
<option value="">Select a page</option>
<option row="1" value="68067">MAIN SITE</option>
<option row="2" value="88616">A</option>
<option row="3" value="88617">B</option>
</select>
EDIT: this select is created dynamically. I can only edit it with java-script after the page renders
If you are looking for jQuery solution then :eq() and attribute selector will be your best bet to look for. I have done something: http://jsbin.com/ojexuh/1/edit
first with :eq()
$('select option:eq(2)').css({"background":"green", "color":"white"});
and attribute selector like this one:
$('select option[row="1"]').css({"background":"red", "color":"yellow"});
option does support background colors within a select. I just set up a simple class to highlight it, as seen via here.
You can add a class like this
$('current page selector').addClass('current');
You could also just manually set it with the css function
$('current page selector').css('background-color', 'red');
You don't really have enough information for me to help you determine how to find the current page. I recommend having some way to tell from the value of the option that you can compare to the current window.location.
There's a lot of variability in browser+OS support for this. Taking Chrome as an example, the dropdown doesn't appear to accept any styling on OS X, but on Windows, background colors can be assigned both in a stylesheet and inline style attribute:
<style type='text/css'>
.highlighted {
background-color: yellow;
}
</style>
<select name='whatever'>
<option value='1'>one</option>
<option value='2'>two</option>
<option value='3' style='background-color: green;'>three</option>
<option value='4' class='highlighted'>four</option>
</select>
Again, both methods work on windows, neither on OS X.
If you want a solution that works everywhere, you need to build your own dropdown control.
Set selected="selected" for the option you want to be the default.
<option row="3" value="88617" selected="selected">B</option>
I just saw the following:
http://www.w3schools.com/jsref/prop_option_value.asp
And wonder if there's something wrong with selectObject.value. Why not a simple approach:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function displayResult(){
alert(document.getElementById("mySelect").value);
}
</script>
</head>
<body>
<form>
Select your favorite fruit:
<select id="mySelect">
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="pineapple">Pineapple</option>
<option value="banana">Banana</option>
</select>
</form>
<button type="button" onclick="displayResult()">
Display value of selected fruit
</button>
</body>
</html>
It seems to be working with no problem.
Thanks in advance!
Mike
Your method, document.getElementById("mySelect").value is returning the value of the select object - which sets itsself to the value of the currently selected option. The way w3Schools is doing it is finding the actual option tag, then you're getting the value of the option tag. So, as long as you are accessing the currently selected option tag, they return the exact same thing. However, the w3schools way allows you to actually set the value of the option tag instead of changing which option is selected when setting the value property (although that's probably not what you want).
Example:
<select id='select'>
<option value=1>one</option>
<option value=2>two</option>
</select>
x=document.getElementById("mySelect").selectedIndex;
So, document.getElementById('select').value; returns the value of the select element.
And document.getElementsByTagName("option")[x].value; returns the value of the selected option element.
Meaning that document.getElementById('select').value=2 changes which option is selected, while document.getElementsByTagName("option")[x].value=2 changes the value of the selected option element.
TLDR: When getting the value there is no difference, when setting the value there is.
I tried using $('.className').show(); and $('.className').hide(); but it doesn't seem to work in IE. Is there another way to group options by class in a drop down list? I found this question but the answer is looking for the value "a" or "c".
//if 2 is selected remove C
case 2 : $('#theOptions2').find('option:contains(c)').remove();break;
//if 3 is selected remove A
case 3 : $('#theOptions2').find('option:contains(a)').remove();break;
How do I look for the actual class?
EDIT
<select id="theOptions2">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
I've never seen anyone try to call hide/show on option elements before, and I imagine IE just doesn't allow you to do that. The selection is probably matching just fine, but IE is not hiding the elements. The selection for removing would be the same as for calling show hide...
$('.className').remove();
or
$('option.className').remove();
or
$('#theSelect option.className').remove();
You can add the disabled attribute to the options you don't want to use:
http://jsfiddle.net/sadmicrowave/Fnvqb/
$('select[class~="cactus"]')
$('option[class~="cactus"]')
javascript:(function(){
var out = "hi\n";
out += $('*[class~="cactus"]').html2string() ;
alert( out );
})()
For future reference, instead of describing in words the html ... show actual html
This demonstration code shows one way of how you can achieve option filtering... it would need modification to determine which candidate items are removed as I just hardcoded for purpose of demonstration, but it shows you what you need to consider - when you remove the items, you need to consider the ordering by which they're added back. The easiest way to bypass this problem is to keep a copy of the original list and then when you unfilter, just remove the remaining items, replacing them with what was originally there - otherwise you have to worry about keeping sort data.
So here's my drop down definition:
<select id="mySelector">
<option class="group1">Item 1</option>
<option class="group2">Item 2</option>
<option class="group1">Item 3</option>
<option class="group2">Item 4</option>
<option class="group1">Item 5</option>
</select>
<input type="button" id="removeItems" value="Remove candidate items" />
<input type="button" id="addItems" value="Add them back" />
And the jquery to filter/restore the items:
$(function () {
var originalOptionData;
$("#removeItems").bind('click', function () {
/* store original copy for rollback */
originalOptionData = $("#mySelector option");
$("#mySelector option.group2").remove();
});
$("#addItems").bind('click', function () {
var selector = $("#mySelector");
selector.children().remove();
selector.append(originalOptionData);
});
});
This could be turned into a select filter jquery plugin relatively simply I suppose, but I didn't go that far...