HTML <select> with element list - html

The following form works exactly as expected, and provides a dropdown list to select an option from:
<select id="f-heroes" class="c-form-select__dropdown">
<option value="" disabled selected>Heroes</option>
<option value="captainAmerica">Captain America</option>
<option value="ironMan">Iron Man</option>
<option value="blackWidow">Black Widow</option>
<option value="thor">Thor</option>
</select>
What I am trying to do is this:
<select id="f-heroes" class="c-form-select__dropdown">
<option value=""><?echo getElement('hero');?></option>
</select>
This gets the 'hero' list but displays it below and out of the option window, and leaves me no option to select a value.
I may be missing something really simple here, but can't seem to get this to work, any help much appreciated.

It looks like your mixing PHP and JavaScript here. From my understanding of your question, you're wanting to create a loop that keeps creating 's for each of your superheroes.
If that's correct, you could use PHP and do something like the below:
<select id="f-heroes" class="c-form-select__dropdown">
<option value="" disabled selected>Heroes</option>
<?php
$superHeroes = array('Captain America','Iron Man','Black Widow','Thor');
$i = 0;
while ($i < count($superHeroes)) {
$name = $superHeroes[$i];
echo "<option value='".$name."'>".$name."</option>";
$i++;
}?>
</select>

Related

Opening files in html

<form>
<p><b>Room Number:</b></p>
<form action="action_page.php">
<select name="rooms">
<option value="select">Select a Room</option>
<option value="room 1">Room 0001</option>
<option value="room 2">Room 0002</option>
<option value="room 3">Room 0003</option>
<option value="room 4">Room 0004</option>
</select>
</form>
How can I implement that by opening a text file and getting the values "room 0001-0004 and not writing them at the html code?
This question is incredibly generic. But a language like PHP is ideally designed to be a web development language, and it suited to this application. Assuming that the file extension was changed to .phtml and an appropriate server had been set up please see this link (note I don't normally use w3 schools, but I think its appropriate here). It would be possible to modify the now phtml file as so:
<?php
$fileHandle = fopen("filename.csv", "r");
$csvArray = fgetcsv($fileHandle);
?>
/** Normal HTML headers and the like! **/
<p><b>Room Number:</b></p>
<form action="action_page.php">
<select name="rooms">
<option value="select">Select a Room</option>
<option value="room 1">Room 0001</option>
<option value="room 2">Room 0002</option>
<option value="room 3">Room 0003</option>
<option value="room 4">Room 0004</option>
<?php for ($i = 0; $i < count($csvArray); $i++): ?>
<option value="<?=$csvArray[$i];?>" >Room 000<?=$i;?></option>
</select>
</form>
As a javascript alternative could easily be done, but there are many considerations to be made in terms of format and location.
I'm almost positive that you're trying to ask if this can be done using purely HTML. I don't believe thats possible. Perhaps using PHP (as above), javascript and an XHR call (but you'd still need somewhere to put the file) this is possible. But I don't believe in pure HTML this can be done.
I did this, and worked... Just in case anyone ever need it :P
<p><b>Room Number:</b></p>
<form>
<select name="rooms">
<option value="select">Select a Room</option>
<?php $i = 0;
label:
?>
<option value="<?=$csvArray[$i];?>" ><?=$csvArray[$i];?></option>
<?php
if($i<count($csvArray)-1){
$i++;
goto label;
}
?>
</select>
</form>

Remember selection from Dropdown menu in Webmatrix

I am trying to keep the value selected by the user in the following Dropdown menu:
<form method="post">
<p><label for="ProjectManager">Project Manager:</label>
<select name="ProjectManager">
<option value="" selected>Select...</option>
<option selected=#(Request["ProjectManager"] == "One") value="One">One</option>
<option selected=#(Request["ProjectManager"] == "Two") value="Two">Two</option>
<option selected=#(Request["ProjectManager"] == "Three") value="Three">Three</option>
<option selected=#(Request["ProjectManager"] == "Four") value="Four">Four</option>
<option selected=#(Request["ProjectManager"] == "Five") value="Five">Five</option>
<option selected=#(Request["ProjectManager"] == "Six") value="Six">Six</option>
</select>
</p>
<p><input type="submit" name="ButtonConfirm" value="Confirm" /></p>
</form>
Just for your reference, here is what happens to the database in the background:
#{
var ProjectManager = "";
if(IsPost){
ProjectManager = Request.Form["ProjectManager"];
db = Database.Open("ControlPoints");
var InsertCommand = "INSERT INTO ControlPointName ([Project_Manager]) VALUES(#0)";
db.Execute(InsertCommand, ProjectManager);
}
}
My code works fine, it just won't remember the value selected. As you can see, I have been trying to implement selected=#(Request["ProjectManager"] == "One") with no luck so far. What am I doing wrong here?
Thanks in advance.
UPDATE:
In the following link http://forums.asp.net/t/1899268.aspx?Remembering+Dropdown+Box+selection+in+WebMatrix a very similar issue is solved. The difference is that the form method is 'get' rather than 'post' as in my case.
Your first option has selected hard-coded into it. Remove that.
I figured it out. It is the strangest thing, in one of my comments I had the following <!--The user's input.....--> After I removed the ' from the word user's, everything worked as needed.

How do I create a macro or snippet for a repetitive HTML tag?

I'm writing some HTML code and I'm having trouble on trying to "summarize" if that's the right words multiple lines of code. Basically I have a select tag that I want to put many times in the HTML code but I don't want to re-writ eover and over again. What is the name for this action? Is it a macro? A snippet? An HTML function?
Basically:
<select>
<option value="default">-Select an Attribute-</option>
<option value="animal">animal</option>
<option value="person">person/human</option>
<option value="cat">cat</option>
<option value="dog">dog</option>
<option value="open">open space</option>
<option value="closed">closed space </option>
<option value="natural">natural</option>
<option value="artificial">artificial</option>
<option value="explicit">explicit</option>
<option value="sexual">sexual</option>
<option value="innocent">innocent</option>
<option value="fearful">fearful</option>
<option value="religious">religious</option>
</select>
Can I define a shortcut or a macro everytime I want to use that select tag code snippet? What's this process called in the HTML lingo, so I can have it in mind for future references?
Can't I do something like:
<select id="snippet">
</select>
that saves me the lines of code after doing a first definition?
Thats not possible in plain HTML. You'd either need Javascript to do it client side, or a server-side script that did this for you using PHP, Python, Perl, etc...
As an example of how to do this client-side using Javascript check out this code: (See it in action at this JSFiddle: http://jsfiddle.net/TZ2gV/)
options = {
'default':'Select an Attribute',
'animal':'animal',
'person':'person/human'
};
$.each(options, function(key, value) {
$('#mySelect')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
With this HTML:
<form>
Select: <select id="mySelect">
</select>
</form>
Alternatively with this server-side PHP code you get the same result (You can see it in action here: http://codepad.org/O5zZ65tZ)
<form>
Select: <select id="mySelect">
<?php
$options = array(
'default'=>'Select an Attribute',
'animal'=>'animal',
'person'=>'person/human'
);
foreach ($options as $key => $value) {
echo "<option value='".$key."'>".$value."</option>\n";
}
?>
</select>
</form>
But in both cases you aren't saving your self many keystrokes over just making the HTML yourself. You'd be best to ask a new question explaining your actual scenario and what you are trying to do.
As Lego says, you can't do this in pure HTML. If you use JavaScript there are a few template libraries that could help. A couple I would suggest are:
http://mustache.github.io/ - which is all about templates
http://underscorejs.org/ - which has a simple to use template function
This post may help How to use underscore.js as a template engine?

doesn't show select option in chrome

I have a problem with my site. I have a select menu and 3 options: images, video and audio. When I click one of the options it should display a button to pick out the image/video/audio to upload, but this doesn't display in Google Chrome. In Firefox there is no problem with this. Does anyone have a solution for this?
Thanks very much!
EDIT:
This is the code
<select name="service_id">
<option value="video" onClick="showSection('video',['image','audio']);" <?=count($videos)?'selected="selected"':''?>>Video</option>
<option value="image" onClick="showSection('image',['video','audio']);" <?=count($images)?'selected="selected"':''?>>Imagini</option>
<option value="audio" onClick="showSection('audio',['video','image']);" <?=count($audios)?'selected="selected"':''?>>Audio</option>
</select>
things i modified:
the second parameter is now a class name, each value separated by a "|"
used onChange() to trigger a selection (but does not trigger unless the value changes)
used this to pass a reference to the select rather than passing values (you can do more this way)
demo here
<select name="service_id" onChange="showSection(this)">
<option value="video" class='image|audio'>Video</option>
<option value="image" class='video|audio'>Imagini</option>
<option value="audio" class='video|image'>Audio</option>
</select>
<script type="text/javascript">
function showSection(el){
//modified to get the first and second parameters of showSection()
//get the value
var firstParam = el.value;
//get the class name of the selected element, and split it
var secondparam = el.options[el.selectedIndex].className.split('|');
console.log(firstParam);
console.log(secondparam);
}
</script>​
Call the function on select not in options:
<select onClick='showSection(this.value,"a")'>
<option value="video" >Video</option>
<option value="image">Imagini</option>
<option value="audio">Audio</option>
</select>
i have tested this in chrome its working alright.
one suggestion is if you are using dropdown then use onchange event rather then using onClick
<?php
$videos=0;
$images=0;
$audios=0;
?>
<select name="service_id">
<option value="video" onClick="showSection('video',['image','audio']);" <?=count($videos)?'selected="selected"':''?>>Video</option>
<option value="image" onClick="showSection('image',['video','audio']);" <?=count($images)?'selected="selected"':''?>>Imagini</option>
<option value="audio" onClick="showSection('audio',['video','image']);" <?=count($audios)?'selected="selected"':''?>>Audio</option>
</select>

How can I set the default value for an HTML <select> element?

I thought that adding a "value" attribute set on the <select> element below would cause the <option> containing my provided "value" to be selected by default:
<select name="hall" id="hall" value="3">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
However, this did not work as I had expected. How can I set which <option> element is selected by default?
Set selected="selected" for the option you want to be the default.
<option selected="selected">
3
</option>
In case you want to have a default text as a sort of placeholder/hint but not considered a valid value (something like "complete here", "select your nation" ecc.) you can do something like this:
<select>
<option value="" selected disabled hidden>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
Complete example:
<select name="hall" id="hall">
<option>1</option>
<option>2</option>
<option selected>3</option>
<option>4</option>
<option>5</option>
</select>
I came across this question, but the accepted and highly upvoted answer didn't work for me. It turns out that if you are using React, then setting selected doesn't work.
Instead you have to set a value in the <select> tag directly as shown below:
<select value="B">
<option value="A">Apple</option>
<option value="B">Banana</option>
<option value="C">Cranberry</option>
</select>
Read more about why here on the React page.
You can do it like this:
<select name="hall" id="hall">
<option> 1 </option>
<option> 2 </option>
<option selected> 3 </option>
<option> 4 </option>
<option> 5 </option>
</select>
Provide "selected" keyword inside the option tag, which you want to appear by default in your drop down list.
Or you can also provide attribute to the option tag i.e.
<option selected="selected">3</option>
if you want to use the values from a Form and keep it dynamic try this with php
<form action="../<SamePage>/" method="post">
<?php
$selected = $_POST['select'];
?>
<select name="select" size="1">
<option <?php if($selected == '1'){echo("selected");}?>>1</option>
<option <?php if($selected == '2'){echo("selected");}?>>2</option>
</select>
</form>
Best way in my opinion:
<select>
<option value="" selected="selected" hidden="hidden">Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
Why not disabled?
When you use disabled attribute together with <button type="reset">Reset</button> value is not reset to original placeholder. Instead browser choose first not disabled option which may cause user mistakes.
Default empty value
Every production form has validation, then empty value should not be a problem. This way we may have empty not required select.
XHTML syntax attributes
selected="selected" syntax is the only way to be compatible with both XHTML and HTML 5. It is correct XML syntax and some editors may be happy about this. It is more backward compatible. If XML compliance is important you should follow the full syntax.
I prefer this:
<select>
<option selected hidden>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
'Choose here' disappears after an option has been selected.
An improvement for nobita's answer. Also you can improve the visual view of the drop down list, by hiding the element 'Choose here'.
<select>
<option selected disabled hidden>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
Another example; using JavaScript to set a selected option.
(You could use this example to for loop an array of values into a drop down component)
<select id="yourDropDownElementId"><select/>
// Get the select element
var select = document.getElementById("yourDropDownElementId");
// Create a new option element
var el = document.createElement("option");
// Add our value to the option
el.textContent = "Example Value";
el.value = "Example Value";
// Set the option to selected
el.selected = true;
// Add the new option element to the select element
select.appendChild(el);
The selected attribute is a boolean attribute.
When present, it specifies that an option should be pre-selected when the page loads.
The pre-selected option will be displayed first in the drop-down list.
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="vw">VW</option>
<option value="audi" selected>Audi</option>
</select>
If you are in react you can use defaultValue as attribute instead of value in the select tag.
If you are using select with angular 1, then you need to use ng-init, otherwise, second option will not be selected since, ng-model overrides the defaul selected value
<select ng-model="sortVar" ng-init='sortVar="stargazers_count"'>
<option value="name">Name</option>
<option selected="selected" value="stargazers_count">Stars</option>
<option value="language">Language</option>
</select>
I would just simply make the first select option value the default and just hide that value in the dropdown with HTML5's new "hidden" feature. Like this:
<select name="" id="">
<option hidden value="default">Select An Option</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
</select>
value attribute of tag is missing, so it doesn't show as u desired selected. By default first option show on dropdown page load, if value attribute is set on tag.... I got solved my problem this way
This example has been tested to work with multiple <select> elements on the page, and can also work with normal text elements. It has not been tested for setting the value to more than one selection when <select multiple="true">, however you can probably modify this sample to support that.
Add an attribute data-selected to each <select> element and set the value(s) to the value of the option you wish to have selected.
Use javascript's querySelectorAll() to select all elements that have the custom attribute you just added.
In the following example, when run, the first <select> should show option with the value user as selected, and the second <select> should show the option with the value admin as selected.
document.querySelectorAll('[data-selected]').forEach(e => {
e.value = e.dataset.selected
});
<select data-selected="user" class="form-control" name="role">
<option value="public">
Pubblica
</option>
<option value="user">
Utenti
</option>
<option value="admin">
Admin
</option>
</select>
<select data-selected="admin" class="form-control" name="role2">
<option value="public">
Pubblica
</option>
<option value="user">
Utenti
</option>
<option value="admin">
Admin
</option>
</select>
I used this php function to generate the options, and insert it into my HTML
<?php
# code to output a set of options for a numeric drop down list
# parameters: (start, end, step, format, default)
function numericoptions($start, $end, $step, $formatstring, $default)
{
$retstring = "";
for($i = $start; $i <= $end; $i = $i + $step)
{
$retstring = $retstring . '<OPTION ';
$retstring = $retstring . 'value="' . sprintf($formatstring,$i) . '"';
if($default == $i)
{
$retstring = $retstring . ' selected="selected"';
}
$retstring = $retstring . '>' . sprintf($formatstring,$i) . '</OPTION> ';
}
return $retstring;
}
?>
And then in my webpage code I use it as below;
<select id="endmin" name="endmin">
<?php echo numericoptions(0,55,5,'%02d',$endmin); ?>
</select>
If $endmin is created from a _POST variable every time the page is loaded (and this code is inside a form which posts) then the previously selected value is selected by default.
This code sets the default value for the HTML select element with PHP.
<select name="hall" id="hall">
<?php
$default = 3;
$nr = 1;
while($nr < 10){
if($nr == $default){
echo "<option selected=\"selected\">". $nr ."</option>";
}
else{
echo "<option>". $nr ."</option>";
}
$nr++;
}
?>
</select>
You can use:
<option value="someValue" selected>Some Value</option>
instead of,
<option value="someValue" selected = "selected">Some Value</option>
both are equally correct.
Set selected="selected" where is option value is 3
please see below example
<option selected="selected" value="3" >3</option>
I myself use it
<select selected=''>
<option value=''></option>
<option value='1'>ccc</option>
<option value='2'>xxx</option>
<option value='3'>zzz</option>
<option value='4'>aaa</option>
<option value='5'>qqq</option>
<option value='6'>wwww</option>
</select>
You just need to put attribute "selected" on a particular option instead direct to select element.
Here is snippet for same and multiple working example with different values.
Select Option 3 :-
<select name="hall" id="hall">
<option>1</option>
<option>2</option>
<option selected="selected">3</option>
<option>4</option>
<option>5</option>
</select>
<br/>
<br/>
<br/>
Select Option 5 :-
<select name="hall" id="hall">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option selected="selected">5</option>
</select>
<br/>
<br/>
<br/>
Select Option 2 :-
<select name="hall" id="hall">
<option>1</option>
<option selected="selected">2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
Default selected value is Option-4
<html:select property="status" value="OPTION_4" styleClass="form-control">
<html:option value="">Select</html:option>
<html:option value="OPTION_1" >Option-1</html:option>
<html:option value="OPTION_2" >Option-2</html:option>
<html:option value="OPTION_3" >Option-3</html:option>
<html:option value="OPTION_4" >Option-4</html:option>
<html:option value="OPTION_5" >Option-5</html:option>
</html:select>
You will need an "id" attribute in each option for this solution to work:
<script>
function select_option (id,value_selected) {
var select;
select = document.getElementById(id);
if (select == null) return 0;
var option;
option = select.options.namedItem(value_selected);
if (option == null) return 0;
option.selected = "selected";
return true;
}
</script>
<select name="hall" id="hall">
<option id="1">1</option>
<option id="2">2</option>
<option id="3">3</option>
<option id="4">4</option>
<option id="5">5</option>
</select>
<script>select_option ("hall","3");</script>
The function first tries to find the <select> with the id, then it will search for the value_selected in the <select> options and if it finds it, it will set the selected attribute returning true. False otherwise
The problem with <select> is, it's sometimes disconnected with the state of what's currently rendered and unless something has changed in the option list, no change value is returned. This can be a problem when trying to select the first option from a list. The following code can get the first-option the first-time selected, but onchange="changeFontSize(this)" by its self would not. There are methods described above using a dummy option to force a user to make a change value to pickup the actual first value, such as starting the list with an empty value. Note: onclick would call the function twice, the following code does not, but solves the first-time problem.
<label>Font Size</label>
<select name="fontSize" id="fontSize" onfocus="changeFontSize(this)" onchange="changeFontSize(this)">
<option value="small">Small</option>
<option value="medium">Medium</option>
<option value="large">Large</option>
<option value="extraLarge">Extra large</option>
</select>
<script>
function changeFontSize(x){
body=document.getElementById('body');
if (x.value=="extraLarge") {
body.style.fontSize="25px";
} else {
body.style.fontSize=x.value;
}
}
</script>
I use Angular and i set the default option by
HTML Template
<select #selectConnection [(ngModel)]="selectedVal" class="form-control col-sm-6 " max-width="100px" title="Select"
data-size="10">
<option >test1</option>
<option >test2</option>
</select>
Script:
sselectedVal:any="test1";
You can try like this
<select name="hall" id="hall">
<option>1</option>
<option>2</option>
<option selected="selected">3</option>
<option>4</option>
<option>5</option>
</select>
To set the default using PHP and JavaScript:
State: <select id="State">
<option value="" selected disabled hidden></option>
<option value="Andhra Pradesh">Andhra Pradesh</option>
<option value="Andaman and Nicobar Islands">Andaman and Nicobar Islands</option>
.
.
<option value="West Bengal">West Bengal</option>
</select>
<?php
if(isset($_GET['State'])){
echo <<<heredoc
<script>
document.getElementById("State").querySelector('option[value="{$_GET['State']}"]').selected = true;
</script>
heredoc;
}
?>
This is simple method to make default option selected.
Can be used for multiple selects on an HTML page.
The method:
Find every select
Read the id and value of that select
Make the option selected
Note:
Every select must have ID to avoid conflict
$(document).ready(function() {
// Loop for every select in page
$('select').each(function(index, id) {
// Get the value
var theValue = $(this).attr('value');
// Get the ID
var theID = $(this).attr('id');
// Make option selected
$('select#' + theID + ' option[value=' + theValue + ']').attr('selected', true);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select id="sport" name="sport" class="autoselect" value="golf">
<option value="basket">Basket Ball</option>
<option value="tennis">Tennis</option>
<option value="golf">Golf</option>
<option value="bowling">Bowling</option>
</select>
<hr>
<select id="tools" name="tools" class="autoselect" value="saw">
<option value="hammer">Hammer</option>
<option value="drill">Drill</option>
<option value="screwdriver">Screwdriver</option>
<option value="saw">Saw</option>
<option value="wrench">Wrench</option>
</select>
I was having some troubles with it because I need some way to choose the option dynamically accordingly to the value that I have in the database. The script bellow works like a charm to me:
<?php
//pick the value of database
$selected_sexo = $query['s_sexo'];
?>
<select name="s_sexo" id="s_sexo" required>
<option <?php if($selected_sexo == 'M'){echo("selected");}?> value="M">M</option>
<option <?php if($selected_sexo == 'F'){echo("selected");}?> value="F">F</option>
</select>