Auto select first option in datalist while typing - javascript

I have a datalist connected to an input
<input list='typesOfFruit' placeholder="Enter a fruit...">
<datalist id='typesOfFruit'>
<option>Apple</option>
<option>Orange</option>
<option>Banana</option>
</datalist>
As the user is typing Ap... How can I make it be already selecting the top suggestion "Apple" so if it is correct they can just hit Enter, rather than have to press the down arrow and then enter.
EDIT: Similar question but no one answered correctly: How to auto select the first item in datalist (html 5)?
I need to auto select the top suggestion WHILE typing, not select the first item in the list statically. So if I press B, Banana will be the top suggestion, and I'd like to know if its possible to have it autofocus on it so the user can hit ENTER instead of down arrow enter

You can do this by maintaining a custom query filter for datalist options.
Try the below code. You can reduce boiler plate if you already know the options data in place.
Hope this helps!
var input = document.querySelector("input");
var options = Array.from(document.querySelector("datalist").options).map(function(el){
return el.innerHTML;
}); //Optional if you have data
input.addEventListener('keypress', function(e){
if(e.keyCode == 13){
var relevantOptions = options.filter(function(option){
return option.toLowerCase().includes(input.value.toLowerCase());
}); // filtering the data list based on input query
if(relevantOptions.length > 0){
input.value = relevantOptions.shift(); //Taking the first
}
}
});
<input list='typesOfFruit' placeholder="Enter a fruit...">
<datalist id='typesOfFruit'>
<option>Apple</option>
<option>Orange</option>
<option>Banana</option>
</datalist>

$("form").on('keydown', 'input[list]', function(e){
if(e.keyCode == 9 || e.keyCode == 13){
const oInput = this;
const aOptions = $('#' +$(oInput).attr('list')+ ' option').map(function() {return this.text}).toArray();
var aRelOptions = aOptions.filter(function(sOption){
return new RegExp(oInput.value.replace(/\s+/, ".+"), "gi").test(sOption);
});
if(aRelOptions.length > 0){
this.value = aRelOptions.shift();
}
if(e.keyCode == 13) return false;
}
}).on("change", 'input[list]', function() {
$(this).attr("placeholder", this.value);
this.blur();
}).on('focus', 'input[list]', function() {
$(this).attr("placeholder", this.value);
this.value = "";
}).on('blur', 'input[list]', function() {
this.value = $(this).attr("placeholder");
});

Related

how to validate on blank input search box

how to get the search input to recognize that there is a string of input?
the code below works but even without entering any input it still does the search if I click search or enter. In other words even if the search input is blank it still searches. This is just a project, anyone has any ideas?
<input type="text" id="textInput" name="" class="query">
<script>
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function(){
let url = 'https://www.google.com/search?q='+query.value;
window.open(url,'_self');
}
</script>
<script>
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
</script>
Simply check for a (valid) length, either greather than zero or greater than maybe three characters for any meaningful results (depends on your searches).
<script>
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function(){
if(query.value.trim().length){ // maybe length>3 ?
let url = 'https://www.google.com/search?q='+query.value;
window.open(url,'_self');
}
}
</script>
<script>
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
</script>
You have to check if the value of input exists or it is not empty.
You can also check:
input.value.length
input.value !== ""
input.value
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function() {
let url = 'https://www.google.com/search?q=' + query.value;
window.open(url, '_self');
}
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13 && input.value) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
<input type="text" id="textInput" name="" class="query">
<button class="searchBtn">Search</button>
Working Fiddle
If you wrap your inputs in a <form></form> you can use HTML5's built in validation.
In my example:
pattern="[\S]+" means all characters except space are valid
required means the input length must be at least 1 valid character
Also, I'm toggling the button's disabled property based on the input's validity. In my opinion it makes for a better user experience letting the user know something is incorrect BEFORE clicking the button.
let button_search = document.querySelector('button.search');
let input_query = document.querySelector('input.query');
button_search.addEventListener('click', function() {
if (input_query.validity.valid) {
window.open('https://www.google.com/search?q=' + input_query.value, '_self');
}
});
input_query.addEventListener('keyup', function(event) {
button_search.disabled = !input_query.validity.valid; //visual indicator input is invalid
if (event.keyCode === 13) {
button_search.click();
}
});
<form>
<input class="query" pattern="[\S]+" required>
<button class="search" disabled>Search</button>
</form>
Last thought, unless there is a specific reason you need to run your code in separate scopes, you can put all of your code in a single <script></script>

Dropdown menu with user input text field and multiple selections

I'm looking to do a dropdown menu with user input, but I want the user to be able to add multiple options.
I was trying to do a datalist with this, but when it came time for multiple inputs then I read that datalist can only do that with email and files.
Here's an example of my current code:
HTML:
<input type="text" name="users" id="users" list="allowedUsers">
<datalist id="editUsers">
<option value="bob"></option>
</datalist>
JS:
$('#users').keypress(function(event){
var keyCode = (event.keyCode ? event.keyCode : event.which)
if(keyCode == '13') {
var inputVal = $(this).val();
$(#editUsers).append('<option value="'+inputVal+'">'+inputVal+'</option>')
}
});
The user can then click on a value and if they click on another either add that one in or when they do a comma then they can click to add. Not sure what would be easiest.
Thanks!
Chek this: https://selectize.github.io/selectize.js/
And in mid time maybe you could get away with something like this:
1 example:
It works by clicking the items, input is readonly...
$('#users').focus(function(){
$('#editUsers').show();
});
$('#editUsers').change(function() {
var val = $("#editUsers option:selected").text();
var inpoutVal = $('#users').val();
if (inpoutVal!=="") {
$('#users').val(inpoutVal+","+val)
}else{
$('#users').val(val)
}
});
#editUsers {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="users" id="users" readonly>
<select id="editUsers" multiple>
<option>Bob</option>
<option>Jhon</option>
<option>Yoda</option>
</select>
2nd example:
this is just something i trued to cook up, but it got out of hand, anyway try to pres some starting letter like B, or Y, then add cooma , . Anyway it does not definlty work as it should but maybe will someone get inspired by this failed attempt. ;)
Its late here cant work on it anymore...
$('#users').focus(function() {
$('#editUsers').show();
});
$("#users").bind('input', function() {
console.clear();
var inputVal = $("#users").val();
var inputVal2 = inputVal.split(",");
var last = inputVal2[inputVal2.length - 1];
$('#editUsers option').each(function() {
var selVal = $(this).val();
if (selVal.indexOf(last) > -1 && inputVal.indexOf(",") <= 0) {
$("#users").val(selVal + ",")
} else if (selVal.indexOf(last) > -1 && inputVal.indexOf(",") > -1) {
var newval = $("#users").val();
var newval2 = newval.split(",");
newval2.pop()
newval2
$("#users").val(newval2 + "," + selVal)
}
});
});
#editUsers {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="users" id="users">
<select id="editUsers" multiple>
<option>Bob</option>
<option>Jhon</option>
<option>Yoda</option>
</select>

Preventing form submit based on entering the same numbers in the box input

I have an input box here
<input type="text" size="9" maxlength="9" id="my_account" name="my_account" value="" >
and here I am disallowing users to enter the same numbers in the box, but what I really want is to prevent the form submit instead
var inputNode = document.getElementById('my_account');
inputNode.addEventListener('keydown', (event) => {
var inputValue = event.key;
var inputNodeValue = inputNode.value;
var length = inputNodeValue.length;
if (length === 3 && inputNodeValue[0] === inputValue) {
event.preventDefault();
}
});
this is my form prevent default
$("form#customer-summary").submit(function(e){
e.preventDefault();
alert("prevent submit");
});
How can I combine these two parts so I dont allow users to submit same numbers in the box ?
var inputNode = document.getElementById('my_account');
var customer_summary = document.getElementById('customer-summary');
customer_summary.addEventListener('submit',function(e){
if(!is_unique(inputNode.value)){
e.preventDefault();
alert("prevent submit");
}
});
function is_unique(val){
for(var i=0;i<val.length;i++){
if(val.indexOf(val.charAt(i)) != val.lastIndexOf(val.charAt(i))){
return false;
}
}
return true;
}
I think this should do the trick. Working jsfiddle: https://jsfiddle.net/m31h1zhg/2/.

Return false if no value is selected (other than heading) from select box

I have a HTML form having select box. On selection of first drop down, next drop down should be auto filled using AJAX.
On Download Records (id="getCsv") button click event a CSV file is generated. Problem is, I want to make all the fields mandatory. Here is the jquery code
var teacher_name = $("#sel_teacher option:selected").text();
var unittest_name = $("#sel_test1 option:selected").text();
var class_name = $("#sel_class1 option:selected").text();
var class_id = $('#sel_class1').val();
var division_name = $("#sel_div1 option:selected").text();
var division_id = $('#sel_div1').val();
var subject_name = $("#sel_sub1 option:selected").text();
if (teacher_name == "") {
alert('Please Select Teacher Name.');
return false;
} else if(class_name == "") {
alert('Please Select Class Name.');
return false;
} else if(division_name == "") {
alert('Please Select Division Name.');
return false;
} else if(subject_name == "") {
alert('Please Select Subject Name.');
return false;
} else if(unittest_name == "") {
alert('Please Select Unit Test Name.');
return false;
} else {
var myObject = new Object();
myObject.class_name = class_name;
myObject.class_id = class_id;
myObject.division_name = division_name;
myObject.division_id = division_id;
myObject.subject_name = subject_name;
myObject.test_name = unittest_name;
var formData = JSON.stringify(myObject);
$('#getCsv').attr('href','csv_generator.php?data=' + formData);
}
The problem is that when I click Download Records, even though the first select box is empty directly alert box for second select box pops up. I tried to solve this problem using the below, but no luck.
if ($("#sel_teacher").attr("selectedIndex") == 0) {
alert("You haven't selected anything!");
return false;
}
Can anybody please help me with this? Any help is appreciated.
selectedIndex is a property, use prop:
$("#sel_teacher").prop("selectedIndex")
Also, you can simplify your code by retrieving the selected value using just $("#sel_teacher").val() and compare to empty string (assuming the value of that option is empty).
var teacher_name = $("#sel_teacher").val();
// get other <select /> values here...
if (teacher_name == '') {
alert("You haven't selected anything!");
return false;
}
// test other values here...
It might be because of the default value that you have given for the first text-box.Just change the value to "" onclick or on blur on that text-box.
Or you can simply handle this matter via HTML5 attribute required and adding onchange() Event Listener .
<select name="sel_teacher" onchange="get_value();" id="sel_teacher" required>
<option>--Select Teacher Name--</option>
</select>
<script>
function get_value() {
var teacher_name = $("#sel_teacher").val();
// get other <select /> values here...
if (teacher_name == '') {
alert("You haven't selected anything!");
return false;
} else {
// write code when teacher_name is selected
}
}
</script>

Want to prevent a textbox from becoming empty with javascript

So i already have a textbox in which you can only enter numbers and they have to be within a certain range.The textbox defaults to 1,and i want to stop the user from being able to make it blank.Any ideas guys?Cheers
<SCRIPT language=Javascript>
window.addEventListener("load", function () {
document.getElementById("quantity").addEventListener("keyup", function (evt) {
var target = evt.target;
target.value = target.value.replace(/[^\d]/, "");
if (parseInt(target.value, 10) > <%=dvd5.getQuantityInStock()%>) {
target.value = target.value.slice(0, target.value.length - 1);
}
}, false);
});
<form action="RegServlet" method="post"><p>Enter quantity you would like to purchase :
<input name="quantity" id="quantity" size=15 type="text" value="1" />
You could use your onkeyup listener to check if the input's value is empty. Something along the lines of:
if(target.value == null || target.value === "")
target.value = 1;
}
You could add a function to validate the form when the text box loses focus. I ported the following code at http://forums.asp.net/t/1660697.aspx/1, but it hasn't been tested:
document.getELementById("quantity").onblur = function validate() {
if (document.getElementById("quantity").value == "") {
alert("Quantity can not be blank");
document.getElementById("quantity").focus();
return false;
}
return true;
}
save the text when keydown
check empty when keyup, if empty, restore the saved text, otherwise update the saved text.
And you could try the new type="number" to enforce only number input
See this jsfiddle

Categories

Resources