Making HTML5 datalist visible when focus event fires on input - javascript

As some might know already styling select element is a nightmare, literally impossible without some javascript trickery. The new datalist in HTML5 could serve the same purpose since the user is presented with a list of options and the value is recorded in an input text field.
The limitation here is the list does not appear until the user start typing something in the text field and even then is only shown possible matches based on their input. The behavior I want is that as soon as there is focus on the field the entire list of options become visible.
So I have this code - view on jsbin
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Input - Datalist</title>
</head>
<body>
<input list="categories">
<datalist id="categories">
<option value="Breakfast">Breakfast</option>
<option value="Brunch">Brunch</option>
<option value="Lunch">Lunch</option>
<option value="Dinner">Dinner</option>
<option value="Desserts">Desserts</option>
</datalist>
</body>
</html>
and I'm trying to get that to show with this Javascript:
var catVal = document.getElementsByTagName("input")[0],
cat = document.getElementById("categories");
catVal.style.fontSize = "1.3em";
catVal.addEventListener("focus", function(event){
cat.style.display = "block";
}, false);
Any help would be appreciated,
Cheers

I use the following code:
<input name="anrede"
list="anrede" value="Herr"
onmouseover="focus();old = value;"
onmousedown = "value = '';"
onmouseup="value = old;"/>
<datalist id="anrede">
<option value="Herr" selected></option>
<option value="Frau"></option>
<option value="Fraulein"></option>
</datalist>
mouseover:
Set focus and memorize old value in a -- g l o b a l -- variable
mousedown:
Delete value and show datalist (built in functionality)
mouseup:
Restore old value
Then select new value.
Find this an acceptable workaround towards a combobox.

I hope you like this solution:
I added a “temp” attribute to the input field for storage and once the mouse hovers over the input filed it will save its current value in temp and then delete the value so as to allow the datalist to open.
On mouseout it will restore the field’s value from the variable temp. This solution works great under Chromium that I tested.
As a bonus you can add a placeholder="Click to see all your options"
<input value="Classic" list="myDatalist" temp="" onmouseover="this.temp=this.value; this.value='';" onmouseout="this.value=this.temp;">
<datalist id="myDatalist" open="open">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>

In the "Ulrich Berth" response, when clicking on the input, the value in the input will be reset and it will not be possible to select the text inside. You can use this to avoid the problem:
<input id = "input" name="anrede"
list="anrede" value="Herr"
onmouseover="focus();old = value;"
onmousedown = "inputFocus();"
onmouseup="value = old;"/>
<datalist id="anrede">
<option value="Herr" selected></option>
<option value="Frau"></option>
<option value="Fraulein"></option>
</datalist>
function inputFocus(){
var input = document.getElementById("input");
if(input.value == ""){
value = '';
}else{
old = value = input.value;
}
}

Question is pretty old, but it's top search on google and there are no answers to be found so I'll add it here.
To expand datalist on first click you need to set
dataListElement.style.display = "block";
and immediately hide it in next line, so it does not appear as element in your DOM, but it will only expand it under input element.
dataListElement.style.display = "none";
As of today it's not expanded on first click only in Firefox.

HTML:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<meta charset=utf-8 />
<title>Input - Datalist</title>
</head>
<body>
<input list="categories" id="categories2" type="text">
<div id="result"></div>
<datalist id="categories">
<option value="Breakfast">Breakfast</option>
<option value="Brunch">Brunch</option>
<option value="Lunch">Lunch</option>
<option value="Dinner">Dinner</option>
<option value="Desserts">Desserts</option>
</datalist>
</body>
</html>
jQuery:
var result='';
$(document).ready(function(){
$('input[type=text]').focus(function(){
$('#categories option').each(function(){
result=result+" "+$(this).val();
});
$('#result').show().html(result);
$('input[type=text]').unbind('focus');
});
$('input[type=text]').blur(function(){
$('#result').hide();
$('input[type=text]').focus(function(){
$('#result').show();
});
});
});
Working JS bin
http://jsbin.com/urupit/4/watch

Related

Select-List displays Keys instead of values

I have a stange phenomenon where I'm stuck at the moment as I don't know where the error comes from.
My code is like this:
<input id="selectClassInput" name="selectClass" list="selectClass" type="text" >
<datalist id="selectClass">
<option value="DUMMY1">0</option>
<option value="s">24</option>
<option value="d">25</option>
</datalist>
My problem is with displaying the datalist. If I click on the arrow I'm getting only the numbers like here:
After selecting for example '25' I'm getting the value 'd'. That is correct BUT I don't want to display the numbers. Instead I want to display the value of this datalist in this drop-down field.
If I do something like this:
<input id="selectClassInput" name="selectClass" list="selectClass" type="text" >
<datalist id="selectClass">
<option value="DUMMY1">DUMMY1</option>
<option value="s">s</option>
<option value="d">d</option>
</datalist>
I'd naturally get the correct display, but I would like to add the ID, so that I can bind the click event with the ID of the selection and not the label.
You can make use of data attribute to find the id of option clicked from the list and keep value as labels,
see below code
$(function(){
$('#selectClassInput').on('change', function(e){
var val = $(this).val();
var id = $('#selectClass').find('option[value="' + val + '"]').data('id');
console.log(id);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input id="selectClassInput" name="selectClass" list="selectClass" type="text" >
<datalist id="selectClass">
<option value="DUMMY1" data-id="0">DUMMY1</option>
<option value="s" data-id="24">s</option>
<option value="d" data-id="25">d</option>
</datalist>

How to submit textbox value instead of "Other" to database

The following html code is part of a form, which sends the information to a java servlet and updates sql database. It is a dropdown menu. When the user selects "Other", javascript makes a textbox appear so that the user can specify more detail. However, when user presses submit button, in the database, it simply says "Other" instead of what the user entered in the text box. Help is appreciated, thanks!
<script type="text/javascript">
function showfield(name){
if (name == 'Other')
document.getElementById('div1').innerHTML = 'Please Specify: <input type="text" name="other" />';
else
document.getElementById('div1').innerHTML = '';
}
</script>
<select id="description" name="description" onchange="showfield(this.options[this.selectedIndex].value)" required>
<option disabled selected value> ---Select--- </option>
<option value="Accommodation">Accommodation</option>
<option value="Travel">Travel</option>
<option value="Meal Allowanced">Meal Allowances</option>
<option value="Flat Rate">Flat Rate Expenses</option>
<option value="Other">Other</option>
</select>
<div id="div1"></div>
I think the field you're checking on the server is "description" which is the name of your select. Which is indeed set to "Other" (this is the value of the selected option).
I would have written it a bit differently but with the current code you need to name the input with some other name and check that one on your server, or change the selected option value.
Example change for client code:
<select id="description" name="description" required>
<option disabled selected value> ---Select--- </option>
<option value="Accommodation">Accommodation</option>
<option value="Travel">Travel</option>
<option value="Meal Allowanced">Meal Allowances</option>
<option value="Flat Rate">Flat Rate Expenses</option>
<option value="Other">Other</option>
</select>
<div id="div1">
Please Specify: <input type="text" name="otherDescription" />
</div>
<script>
document.querySelector('#description').addEventListener('change', function (evt) {
var inputWrapper = document.getElementById('div1'),
input = inputWrapper.querySelector('input);
if (evt.target.value == 'Other') {
document.getElementById('div1').style.display = '';
} else {
document.getElementById('div1').style.display = 'none';
input.value = '';
}
});
</script>
The you need to check 'otherDescription' on the server.
Hope it helps
Assuming that all of this markup is contained within a <form> element that will be submitted to the server, you should be able to simply check to see if the value posted for description is "Other" and then read the posted value for other.
The code will vary depending on your server-side implementation.

Create drop down on the fly

I have looked all over for an answer to this, but cant seem to find a definitive answer.
I want to be able to display a dropdown, populated from MySQL with PHP and have next to it a '+' or something that will, when clicked on, create another dropdown with the same data as the first.
In this way, the user can add as many dropdowns as they want. There will be around 25 items in each dropdown. I'm open to JS,JQuery etc. - just need to get it done!
I'd appreciate any and all help.
Rob
Edit
Had a night sleep - so let's try again!
Based on #adeno code I cam up with this:
?>
<!doctype html>
<html lang="en">
<head>
<title>Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<form action = 'testselectprocess.php' method='POST'>
<div>
<select id='test' name='test0'>
<option name='first' value = '1'>option 1</option>
<option name='second' value = '2'>option 2</option>
<option name='third' value = '3'> option 3</option>
</select>
<select id='counting' name='count0'>
<option name='first' value = '1'>1</option>
<option name='second' value = '2'>2</option>
<option name='third' value = '3'>3</option>
</select>
</div>
<button type='button' class="more">Add another...</button>
<script>
var c=0;
$('.more').on('click', function() {
//alert(c);
$(this).before( $(this).prev().clone());
$('#test').attr('name', 'test'+ c)
$('#counting').attr('name', 'count'+ c)
c++;
});
</script>
<input type="submit" value="Add this." name="what">
</form>
</body>
</html>
Trouble is - after the first 'Add another...' press, the id numbers don't increment. Looking at it with IEs DOM explorer the id increments once only. Wish I knew how to cut and paste in the DOM explorer but I only seem to be able to copy one element.
Depends on the markup, but in principle it's pretty straight forward, you create a button that when clicked clones the select and inserts the clone
$('.more').on('click', function() {
$(this).before( $(this).prev().clone() )
});
FIDDLE

Populating the form bases on a dropdown box

I am building a tool which on a selection of a value from a dropdown box populates the other fields.So if suppose (a) is selected fileds 2 3 and 4 are displayed in a form but if(b) is selected fields 2 3 4 as well as additional fields 5 and 6 are added as well.Right now I am working around a way to have two forms one with fields 2 3 and 4 and other with 2 3 4 5 and 6.Depending on selection of values from dropdown list(a or b) either forms are shown/hidden.
But it doesn't do as expected.
The html is
<html>
<head>
<title>My Page</title>
</head>
<body>
<center><h1>URL Builder</h1></center>
<div align="center">
<select id ="Type1" name="Aoldropdown">
<option value="Fixed">Fixed Ad Units</option>
<option value="Scrolled">Scrolled Ad Units</option>
<option value="Custom">Custom Ad Units</option>
</select>
<form name="Aolform" id ="aol1" action="/URLBuilder/URLRetriever" method="GET">
<select name="Sizedropdown">
<option value="300x1050">300x1050</option>
<option value="300x600">300x600</option>
<option value="300x250">300x250</option>
<option value="728x90">728x90</option>
<option value="970x250">970x250</option>
<option value="320x50">320x50</option>
<option value="768x90">768x90</option>
<option value="1024x90">1024x90</option>
</select>
<br></br>
Base URL:<input type="text" name="baseURL"><br>
Title Number:<input type="text" name="titleNo"><br>
Placement ID: <input type="text" name="placementId"><br>
Flight ID: <input type="text" name="flightId"><br>
<input type="submit" value="Retrieve URL">
<!-- input type = "submit" Value ="Select URL Type"-->
</div>
</form>
<form name="Aolform2" id ="aol2" action="/URLBuilder/URLRetriever" method="GET">
<select name="Sizedropdown">
<option value="300x1050">300x1050</option>
<option value="300x600">300x600</option>
<option value="300x250">300x250</option>
<option value="728x90">728x90</option>
<option value="970x250">970x250</option>
<option value="320x50">320x50</option>
<option value="768x90">768x90</option>
<option value="1024x90">1024x90</option>
</select>
<br></br>
Placement ID: <input type="text" name="placementId"><br>
Flight ID: <input type="text" name="flightId"><br>
<input type="submit" value="Retrieve URL">
<!-- input type = "submit" Value ="Select URL Type"-->
</div>
</form>
<script type ="text/javascript">
var forms = document.forms['Aolform'];
//console.log(forms);
//console.log(forms.elements);
document.getElementById("Type1").addEventListener("onchange",onDropDownChange,true);
if(document.getElementById("Type1").value =='Custom'){
document.getElementById('aol1').style.visiblity='visible';
document.getElementById('aol2').style.visibility='hidden';
}
else
{
document.getElementById('aol2').style.visibility='visible';
document.getElementById('aol1').style.visibility='hidden';
}
</script>
</body>
</html>
Please help me fix this.
IS THERE ANY OTHER WAY I CAN DO IT.
Thanks
Swaraj
Check out this fiddle. I made a few changes, first instead of onchange just use change. Also you are referencing a non-existent function onDropDownChange(), so I have put your condition inside of that:
function onDropDownChange() {
if (document.getElementById("Type1").value == 'Custom') {
document.getElementById('aol1').style.display = 'none';
document.getElementById('aol2').style.display = 'block';
} else {
document.getElementById('aol2').style.display = 'none';
document.getElementById('aol1').style.display = 'block';
}
}
I also changed the function to use style.display instead of style.visibility so that you don't have a gap above the second form when it displays.
Yes, there are lots of ways to do what you want, but I'm going to give you a straight answer based on what you have done so far. Your script is incorrect because the conditional is not triggered by the event OnChange. Try it like this:
document.getElementById("Type1").onchange = function() {
if(document.getElementById("Type1").value =='Custom'){
document.getElementById('aol1').style.visiblity='visible';
document.getElementById('aol2').style.visibility='hidden';
}
else
{
document.getElementById('aol2').style.visibility='visible';
document.getElementById('aol1').style.visibility='hidden';
}
}
But you should check the behaviour of your "if" condition to see if that's what you really want to do.

Syncing 2 multiple choice lists in javascript

I'm trying to figure out how to sync two multiple choice lists in javascript. Here's the code which works:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
</head>
<script language="JavaScript">
<!--
function SelectEmail(name)
{
var listboxEmails = document.getElementById('emails');
for (var i=0;i<listboxEmails.length;i++)
{
listboxname = listboxEmails[i].innerHTML
if (listboxname == name)
{
listboxEmails.selectedIndex = i;
break;
}
}//end for
}//end function SelectEmail
// -->
</script>
<body>
<select id='names' name ='names' style = "width: 100" multiple="multiple" onClick="SelectEmail(this.value);">
<option value ="joe">joe</option>
<option value ="albert">albert</option>
<option value ="gary">gary</option>
<option value ="ace">ace</option>
</select>
<select id="emails" name ="emails" style = "width: 100;" multiple="multiple">
<option value ="joe#asds.com">joe</option>
<option value ="albert#asds.com">albert</option>
<option value ="gary#asds.com">gary</option>
<option value ="ace#asds.com">ace</option>
</SELECT>
</body>
</html>
However I want to make it show multiple choices. So for example if I choose albert and gary on the left list, I want the right list to select albert and gary as well. Please help me with this. Cheers.
Your function SelectEmail() can't work because it sets selectedIndex of your select, which selects one option and deselects the rest. Also, you are using the text content of the options in #emails in order to map them with the values of #names. That's not a good practice, because text nodes are supposed to show text and not to enable the identification of elements in your script.
Instead, you can access the selected attribute separately for each option you want to select. By adding an additional attribute to your #emails element's options, it could look like:
<select id="emails" name="emails" style="width: 100;" multiple="multiple">
<option value="joe#asds.com" data-name="joe">joe</option>
<option value="albert#asds.com" data-name="albert">albert</option>
<option value="gary#asds.com" data-name="gary">gary</option>
<option value="ace#asds.com" data-name="ace">ace</option>
</select>
You can now use the data-name attribute to map the options, for example in the following way:
function selectEmail() {
// deselect all
$('#emails option').removeAttr('selected');
var names = $('#names').val();
if (names == null) {
// none selected
return;
}
$.each(names, function (i, name) {
var selector = 'option[data-name="' + name + '"]';
$('#emails ' + selector).attr('selected', true);
});
}
Here's a working fiddle (you will notice that I also used the onchange event instead of onclick:
http://jsfiddle.net/H9hNH/2/

Categories

Resources