Showing suggestion box when typing in input box - javascript

I'm trying to get some sort of suggestion box in my application. The basic idea is that, when typing in an input box, 5 options show up below the input box with possible entries.
The problem I am facing is that, while there is nothing entered in the input box, the box which gives the possible suggestions already shows (see Screenshot). Of course, I only want it to show up when I enter something in the input box.
Any help?
Wout
CSS-code:
#suggestions {
-moz-box-sizing: border-box;
box-sizing: border-box;
border: 1px solid black;
position: absolute;
left: 310px;
top: 5px;
background-color: white;
font-size: 12px;
}
JavaScript: --> option1, option2,... get a value in function "giveSuggestion()"
<form id = "suggestions">
<input type = "text"
id = "insertText"
autocomplete="off"
onkeyup = "if (event.keyCode == 13) {SearchAddress(option1.text)}
else {giveSuggestion()}"/>
<option id = "option1" onclick = "searchAddress(option1.text)"></option>
<option id = "option2" onclick = "searchAddress(option2.text)"></option>
<option id = "option3" onclick = "searchAddress(option3.text)"></option>
<option id = "option4" onclick = "searchAddress(option4.text)"></option>
<option id = "option5" onclick = "searchAddress(option5.text)"></option>
</form>

There is a standard way of doing that. HTML5 <datalist> tag! And the global browser support for it 74.5%. You may use the above fiddle as a fallback support. Watch this

Check this out:
https://jsfiddle.net/gnph4evm/1/
I have added a new class:
.option{
display:none;
}
and added it to all your options like:
<option class="option" id = "option1" onmousedown = "searchAddress(option1.text)" >text1</option>
added functions for toggling the visibility:
showOptions = function (){
$('.option').show();
}
hideOptions = function (){
$('.option').hide();
}
and for the grand finale, added onfocus and onfocusout calling thoose functions
<input type = "text"
id = "insertText"
autocomplete="off"
onkeyup = "if (event.keyCode == 13) {SearchAddress(option1.text)}
else {giveSuggestion()}" onfocus='showOptions()' onfocusout='hideOptions()'/>
Hope it's helpful

If the Data is stored in the database for suggestion.
Then, after creating the <input> field Make use of <datalist> tag and place it inside a <div> container dynamically replace the content. Here is how you can do it.
<input type="text" name="search_email" list="listit" onkeyup="suggest(this.value)" id="search_email">
<div id="suggest_container" style="display:inline-block;">
<datalist id="listit">
<option ></option>
</datalist>
</div>
Now all you have to do is write Ajax code for it like
function suggest(val){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('suggest_container').innerHTML=this.responseText;
}
};
xhttp.open("GET", ("dyn_suggest.php?value1="+ val), true);
xhttp.send();
}
After this just write the php code for it and check if the $_GET['value1'] is set or not. If not do nothing otherwise fetch the value
$count1=0; // for 5 values
$res=mysqli_query($con,$query);
echo "<datalist id=\"listit\">";
if(mysqli_num_rows($res)!=0){
while($i= mysqli_fetch_row($res)){
$count1++;
echo "<option value='".$i[0]."' >";
if($count1==5){
break;
}
}
}
echo "</datalist>";

Related

How do I write an html form of variable length to a plain text file?

I am somewhat new to the world of website design. I have an HTML form that consists of a dropdown box and an input box. I also have a button that creates move dropdown boxes and input boxes. There is not a limit on how many the user can create.
Once the user has put all of their desired input in, I want to take the entire form and write it to a plain text file (this will be used in a Python script). How can I do this without using a php form? Any input would be helpful. Thanks!
HTML form:
<form>
<table id = "actions_table" style="position: absolute; left: 486px; top: 25px">
<tr>
<td><select name = "action" id = "action" style="width: 108px;">
<option value = "Click_button">Click Button</option>
<option value = "Input_search">Input Search</option>
</select></td>
<td><input type = "text" style="width:100px" name = "input_text"></td>
</tr>
</table>
<input type = "submit" value="Add to Scrape" style="position: absolute; left: 720px; top: 150px; width:100px">
</form>
Add to form button:
<button type = "button" onclick="addAction()" style="position:absolute; left: 1050px; top: 125px;">Add Action</button>
Action behind Add to form button:
<script>
function addAction(){
//Get table
var action_table = document.getElementById("actions_table");
//Add selection box
var new_input_option = document.createElement("select");
new_input_option.style.width = "108px";
//Add option for click button
var click_opt = document.createElement("option")
click_opt.text = "Click Button"
//Add option for input search
var input_opt = document.createElement("option")
input_opt.text = "Input Search"
//add options
new_input_option.add(click_opt)
new_input_option.add(input_opt)
//Create new input box
var input_box = document.createElement("input")
input_box.style.width = "100px"
//Insert new row below last one
let newRow = action_table.insertRow(-1)
let newCell = newRow.insertCell(0)
let newCell2 = newRow.insertCell(1)
//Add stuff
newCell.appendChild(new_input_option);
newCell2.appendChild(input_box);
}
</script>
I have found ways to write designated form fields by the name of the field, but I just have not been able to simply get all elements from the form and write them to a plain text file. Thanks again for any input!

make input tag toggle between edit and readOnly

I have a question, how do you toggle input tag from edit to readOnly but without using other buttons. I have here my codepen. If you notice I added an event on a div. This one kinda dumb because when they want to edit they click the input and then the next click will disable it. There's something that I saw somewhere. They implemented this same thing. Any links that I could read? thank you.
HTML
<div id='wasa'>
<input id="date" type="date" value="2018-07-22" >
</div>
JS
const test = document.querySelector('#wasa');
const date = document.querySelector('#date');
let foo = false;
test.addEventListener('click', function() {
foo = !foo
date.readOnly = foo;
console.log(foo)
})
You can use the setAttribute and removeAttribute attribute functions to toggle disabled state.
const test = document.querySelector('#wasa');
const date = document.querySelector('#date');
test.addEventListener('click', function() {
if (date.hasAttribute('readonly')) {
date.removeAttribute('readonly')
} else {
date.setAttribute('readonly', 'readonly');
}
})
#wasa {
padding: 1em;
}
<div id='wasa'>
<input id="date" type="date" value="2018-07-22">
</div>
If you are interested in a jQuery answer this would be how I would do it.
It is a little more clean than a pure javascript answer and achieves the same thing.
// remove readonly when clicking on the input
$("body").on("click", "#wasa input", function(){
$(this).prop("readonly", "");
// EDIT: this was the prevoius answer
//$(this).prop("readonly", !$(this).prop("readonly"));// unlock by clicking on the input
});
/* NEW */
// lock input when click/tab away
$("body").on("focusout", "#wasa input", function(){
$(this).prop("readonly", "readonly");
});
#wasa input:read-only {
background: crimson;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='wasa'><input id="date" type="date" value="2018-07-22" readonly></div>
You can use the change event to restore the readonly status of the field.
From my comment...
Take off the toggle — start as readonly by including the readonly attribute on the field
<input type="date" value="2018-07-22" readonly>
Then, when the div is clicked, remove the readonly attribute using date.removeAttribute('readonly') as Nidhin shows.
When a new date is picked a change event is fired; attach a change listener to the date field. In that listener (when the field is changed) then add the readonly attribute back.
Note that a change isn't always fired the moment a value changes, it may not be fired until you leave the field (blur), so you may want to further adapt the code below, but it is fired when you change the value via the datepicker.
const dateDiv = document.getElementById('wasa');
const date = document.querySelector('input[type=date]', dateDiv);
dateDiv.addEventListener('click', function() {
date.removeAttribute('readonly');
});
date.addEventListener('change', function() {
date.setAttribute('readonly','');
});
#date {
background: transparent;
border: none;
}
#date[readonly] {
background-color: lightblue;
}
<div id='wasa'>
<input id="date" type="date" value="2018-07-22" readonly>
</div>

textContent display Content only for a while (using addEventListener)

I'm trying to display typed text, but it shows only for a moment - don't know why.
HTML
<div>
<h1 id="ASD"></h1>
</div>
<form>
<input type="text" id="OUTPUT">
<input type="submit" value="Check">
</form>
CSS
div{
height: 200px;
width: 200px;
background: red;
}
JS
let output= document.getElementById('OUTPUT');
const newSubmit = document.querySelector('input[type=submit]');
function checkNumber() {
document.getElementById('ASD').textContent = output.value;
}
newSubmit.addEventListener('click', checkNumber, false);
http://codepen.io/Shalahmander/pen/QdKvgJ
Typed text should be display in box after click Submit.
The page is refreshing on the submit click (the form is processed). You can handle event object and call .preventDefault to cancel the default behavior, like this:
let output= document.getElementById('OUTPUT');
const newSubmit = document.querySelector('input[type=submit]');
function checkNumber(e) {
document.getElementById('ASD').textContent = output.value;
e.preventDefault();
}
newSubmit.addEventListener('click', checkNumber, false);
But I suggest using <button/></button>or <input type="button"></input> if you want to perform another action (than submit your form).
Also, remember to close your tags: <input>...</input> or <input />.

Tab on disabled input

I am implementing progressive UI disclosure pattern in my application. Using which I am disabling the next elements. So based on input of one element the next element is enabled.
But I have a problem is since the next element is disabled, the tab from the current element is taking the focus to the end of document or the tab header when tab out. As the progressive enables the element after the tab out, while this was happening the next element was not enabled so tab was lost outside the document.
So my requirement is to enable tab on the disabled elements and also on mobile/tablet devices the click events should at least be registered on the disabled elements. Please let me know your views on this.
Answer
To answer the question (as we already discussed in the comments), disabled elements can't be focused.
Workaround
For those looking for a workaround that gives a visual indication that an element is "disabled" and also prevents default functionality while still preserving focusability and click events, following is a simplified example where the submit button appears to be disabled and is prevented from "submitting" unless the input contains some text (also restores "disabled" state if input is cleared).
const input = document.querySelector('input');
const button = document.querySelector('button');
input.addEventListener('input', (event) => {
const target = event.currentTarget;
const next = target.nextElementSibling;
if (target.value) {
next.classList.remove('disabled');
} else {
next.classList.add('disabled');
}
});
button.addEventListener('click', (event) => {
const target = event.currentTarget;
if (target.classList.contains('disabled')) {
event.preventDefault();
console.log('not submitted');
} else {
console.log('submitted');
}
});
button {
background-color: #fff;
color: #0d47a1;
border: 2px solid #0d47a1;
}
button.disabled {
background-color: #e0e0e0;
color: #bdbdbd;
border: 2px solid #bdbdbd;
cursor: default;
}
button.disabled:focus {
outline: none;
}
<input type="text">
<button class="disabled">Submit</button>
You could add an event listener to the keydown event and listen for the tab key like in the code snippet,
document.addEventListener("keydown", keyDown);
function keyDown(e) {
switch (e.which) {
case 9:
var focused = $(document.activeElement);
var all_inputs = $("input");
var disabled_inputs = $("input[disabled='disabled']");
var diff = all_inputs.length - disabled_inputs.length;
var index = all_inputs.index(focused);
if (index == diff - 1 && index != -1 && disabled_inputs.length > 0) {
$(disabled_inputs[0]).removeAttr("disabled").focus();
e.preventDefault();
}
break;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="text" placeholder="this is not disabled!"> <br>
<input type="password" placeholder="this is not either!"> <br>
<input type="button" value="This is!" disabled="disabled"> <br>
<input type="submit" value="This is too!" disabled="disabled">
This will enable the element as you tab onto it. It doesn't effect normal behavior otherwise. I am assuming you don't want to re-disable the element after the focus leaves.
It is better if we have some part of the code to understand better your problem.
For this:
I am implementing progressive UI disclosure pattern in my application. Using which I am disabling the next elements. So based on input of one element the next element is enabled.
You must first handle an event for the first element and then in the callback function you need to enable/disable the second element, let say:
For enable:
$('#firstElement).on('click', function(){
$('#secondElement').removeAttr('disabled')
})
For disable:
$('#firstElement).on('click', function(){
$('#secondElement').attr('disabled', 'disabled')
})
Hope this could help.
On my idea a input event listener or change event listener for dropdown and input fields work better for your case.
E.g:
$(document).on('input','input',function()
{
$(this).next().prop('disabled',false);
}
or
$(document).on('change','input',function()
{
$(this).next().prop('disabled',false);
}
You can use tabindex attribute in this case. Please refer below code, you need to update tabindex of disabled elements in a way that they get skipped when you press tab.
as per w3schools
The tabindex attribute specifies the tab order of an element (when the
"tab" button is used for navigating).
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="input-1" tabindex="1" value="1">
<input class="input-2" tabindex="2" value="2">
<input type="button" onclick="changeTabIndex();" value="change-tab-index">
<input class="input-3" tabindex="3" value="3">
<input class="input-4" tabindex="4" value="4">
<input class="input-5" tabindex="5" value="5">
<script type="text/javascript">
function changeTabIndex() {
$(".input-5").attr("tabindex",4);
$(".input-4").attr("tabindex",5);
}
</script>

Is there a way to do this with basic JS DOM?

I need to apply/remove to an input field according to a user's selection in a separate drop down form - but I can't figure out how to target the input's class.
I need to add/remove the 'pageRequired' class from this input:
<input type="text" title="Company Required" name="customfields-tf-2-tf" class="inputclass pageRequired textInput" id="customfields-tf-2-tf" />
When the user selects one of two options from a drop down field. For example:
<select class="dropdown" name="customfields-s-1-s" id="customfields-s-1-s" >
<option value="Owner"<?php if(in_array("Owner",$temp_values)) { ?> selected='selected'<?php } ?>> Owner</option>
<option value="Broker"<?php if(in_array("Broker",$temp_values)) { ?> selected='selected'<?php } ?>> Broker</option>
</select>
If the user selects broker than I want to add the pageRequired class to the first input field and remove it if the user selects Owner.
EDIT- Ok, so here is the code I am working with:
<script type="text/javascript">
function changeClass(myDropdown) {
if (#customfields-s-1-s.selectedIndex == 1 ) {
$('#customfields-tf-2-tf').addClass('pageRequired');
}
else {
$('#customfields-tf-2-tf').removeClass('pageRequired');
}
}
</script>
If you don't want to use JQuery you can also do this with just plain JavaScript:
<script>
function changeClass(obj) {
var input = document.getElementById("customfields-tf-2-tf");
if(obj.value == 'Broker') {
input.className = input.className.replace('pageRequired','');
}
else if(obj.value == 'Owner') {
input.className = input.className + ' pageRequired';
}
}
</script>
<input title="Company Required" id="customfields-tf-2-tf" class="inputclass pageRequired textInput" type="text">
<br>
<select name="matt" onchange="changeClass(this)">
<option value="Owner">Owner</option>
<option value="Broker">Broker</option>
</select>
This can be done very simply using jquery:
Just add the onchange event to your dropdown and then call a function that either removes the class or adds it depending on the dropdown selection
<select class="dropdown" name="customfields-s-1-s" id="customfields-s-1-s" onchange="javascript:changeClass(this);" >
function changeClass(myDropdown) {
if (myDropdown.selectedIndex == 1 ) {
$('#customfields-tf-2-tf').addClass('pageRequired');
}
else {
$('#customfields-tf-2-tf').removeClass('pageRequired');
}
}
Here are the links on use:
http://api.jquery.com/addClass/
http://api.jquery.com/removeClass/

Categories