I'm trying to toggle a div display property using a search input. So far everything is working, however, when the search bar is empty, I want it to toggle back to display:none. I can't seem to get it to work, and do not want to use a button to achieve this. Is there a way to fire a function when the input becomes empty? Right now, the function is firing when the page loads, so my divs are starting out hidden. I'd like them to display when a their relative tag is input into the search bar, but to hide again when the input is empty or their exact tag is not in the input. Any help would be great!
Code:
function myFunction() {
var input = document.getElementById("Search");
var filter = input.value.toLowerCase();
var nodes = document.getElementsByClassName('connect-cat');
for (i = 0; i < nodes.length; i++) {
if (nodes[i].innerHTML.toLowerCase().includes(filter)) {
nodes[i].style.display = "block";
} else {
nodes[i].style.display = "none";
}
}
};
function check()
{
var isEmpty = $('Search').is(":empty");
$('#silent').toggle(isEmpty);
};
Input bar:
<input type="text" id="Search" onKeyup="myFunction();" Placeholder="Please enter a search term...">
The check function is firing at the top of the page:
$(document).ready(function()
{
check();
}
You should attach the event on the input field instead.
Try something like this:
$('#Search').change(function() {
var length = $(this).val().length;
if (length == 0) {
// hide div
}
});
Related
I am making a page for a school project, and I am trying to make a keypad for a passcode system. However, I don't know how to get the keys to work. Looking it up, I have found multiple working keypads, however, I don't know what parts of their code I would have to add to my page to make it work.
The code that follows is currently what I have attached to the onclick part of each of the buttons:
<script>
function kpclick(){
var current = document.getElementById("tbInput").value;
var append = this.innerHTML;
if (current.length < 4) {
if (current=="0") {
document.getElementById("tbInput").value = append;
} else {
document.getElementById("tbInput").value += append;
}
}
}
</script>
The "tbInput" mentioned is a textbox underneath the keypad in the same div that later will be hidden and (hopefully) disabled. If there is no solution that allows the keypad to be used while the textbox is disabled, I will likely move it outside of the div the keypad is in.
When I press any of the buttons currently, nothing happens. What's happening here?
I'm assuming this is meant to be the button context. You can pass it with onclick="kpclick(this)".
function kpclick(target) {
var current = document.getElementById("tbInput").value;
var append = target.innerHTML;
if (current.length < 4) {
if (current == "0") {
document.getElementById("tbInput").value = append;
} else {
document.getElementById("tbInput").value += append;
}
}
}
<button onclick="kpclick(this)">0</button>
<button onclick="kpclick(this)">1</button>
<input id="tbInput">
I'm trying to check whether the length of characters typed into the text box is less than 6, and if it is, I want its background to be red. Unfortunately, I can't seem to figure out where I'm going wrong with this simple problem.
var textBox = getElementsByName('random');
function checkLength() {
if (textBox.value.length < 6) {
textBox.style.backgroundColor = "red";
}
}
<input type="text" name="random" onfocus="checkLength();">
A few issues in your code:
you need to put <script> code at the end, so that DOM is loaded and ready before you access elements in it.
getElementsByName('random') needs to document.getElementsByName('random'), which will actually return a list so you need to get first element from the list.
Also logically, you need to remove the red background once the text
length in input exceeds 6 and it would be better if you attach function to oninput event.
<input type="text" name="random" oninput="checkLength();">
<script type="text/javascript">
var textBox = document.getElementsByName('random')[0];
function checkLength() {
if (textBox.value.length < 6) {
textBox.style.backgroundColor = "red";
} else {
textBox.style.backgroundColor = "white";
}
}
</script>
When the page first loads, the element with a name of random doesn't exist.
You will need to initialise your textBox global after the page loads.
You can do this by replacing
var textBox = document.getElementsByName("random")[0]
with
var textBox;
window.onload = function() {
textBox = document.getElementsByName("random")[0]
}
Try this
// add an id of "random" to your input
function checkLength() {
const textBox = document.getElementById("random")
if (textBox.value.length < 6) {
textBox.style.backgroundColor = "red";
} else {
textBox.style.backgroundColor = "white";
}
}
Working example: http://jsbin.com/caseqekusi/1/edit?html,js,output
Note: If you want the box to be red right away, you'll have to modify it a bit, let me know if you have questions.
I would suggest to use oninput as well, so it updates as you type and marks the field as "valid" as soon as you have reached a certain length.
You could also get rid of var textbox = ... by using document.activeElement. It makes your function reusable for other input fields. And it no longer matters when your code is loaded.
function checkLength() {
// Get current focused element
const textBox = document.activeElement;
if ( !textBox.value || textBox.value.length < 6 ) {
textBox.style.backgroundColor = "red";
}
else {
textBox.style.backgroundColor = "#fff";
}
}
<input type="text" name="random" onfocus="checkLength()" oninput="checkLength()">
I have filter for my list <ul> here is my html for the input where I have my filter.
<h1>Image Gallery</h1>
<div class="searchbox">
<input type="text" placeholder="Search" class="search" onkeyup="search()" id="myInput" >
</div>
my js
function search() {
var filter = $('input').val().toUpperCase().split(' ');
var li = $('li');
var a = $('a');
for (var i = 0; i < li.length; i++) {
a = li[i];
var text = a.innerHTML.toUpperCase();
for(var f = 0; f < filter.length; f++) {
if (text.indexOf(filter[f]) > -1 ) {
li[i].style.display = '';
//break; // don't need further matches
}
else {
li[i].style.display = 'none';
}
}
}
}
The thing that I want to is when I hit the x from the input and clear out letters and reload info, but doesn't reload the assets, you have to press BACKSPACE for this to happen. an example of this is here
you can write anything and the filter works but then click on the X inside the input only clears the letters, then you hit BACKSPACE and you reset the info.
so how can you do this with only th X from the input, only one click and:
clear the letters
but also reset the info, like if you were pressing the BACKSPACE
It sounds like you want to add an event listener to the clear button ('x') inside of your input field which will run your search function (or alternatively a clear function which you create which refreshes your data).
At the moment, backspace works because the onkeyup="search()" event triggers a function call that updates your data. The simplest solution would be to create a click event for the input's 'X' that calls the same function, ideally setting the input's value to an empty string. As I mentioned you could alternatively create a 'clearSearch' function and use that as the callback function to the click event which would specifically clear the previous results and set the value of the input field to an empty string.
Edit - Add example of event listener to invoke search method:
As I mentioned above, it sounds like you have some code which generates a clear button (the 'x' you are referring to) inside of your input. I'm not sure what that is, so in my example code below I have simulated that behavior with a button (id="clearButton").
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
</head>
<body>
<input type="text" placeholder="Search" onkeyup="search()" class="search" id="myInput" />
<!-- Added this button because I'm not sure how you are generating the 'x' -->
<input type="button" click="clear()" id="clearButton" value="X" />
<script type="text/javascript">
// Use an event listener to assign the 'clear' function to the click event on the button
window.onload = function() {
document.getElementById("clearButton").addEventListener("click",clear);
}
function search() {
var filter = $('input').val().toUpperCase().split(' ');
var li = $('li');
var a = $('a');
for (var i = 0; i < li.length; i++) {
a = li[i];
var text = a.innerHTML.toUpperCase();
for(var f = 0; f < filter.length; f++) {
if (text.indexOf(filter[f]) > -1 ) {
li[i].style.display = '';
//break; // don't need further matches
} else {
li[i].style.display = 'none';
}
}
}
}
function clear() {
// Select the 'myInput' search box, and set it's value to an empty String
document.getElementById("myInput").value = "";
// Call seach, which should reset the result list
search();
}
</script>
</body>
</html>
I used vanilla JS for the code I've added, but it will work the same with jQuery.
He is using the basic w3s search box in a full screen js modal that`s why the X - close button.
The solution offered by user4184202 was very good may be click="clear()" should be onclick="clear()" ?
If anyone needs to also remove highlighted text you can use:
document.getElementById("myInput").value = "";
$('#myUL').removeHighlight();
search()
and it now clears both the input box and older highlights
Below one is worked for me, when we typing inside search input field onkeyup will be triggered and on click of 'x' icon inside search field will trigger onsearch event and onsearch event will be triggering onkeyup.
<input type="search" id="search-name" class="form-control display" placeholder="Search
by Name" onkeyup="callSomeFunction()" onsearch="this.onkeyup();">
function callSomeFunction() {
// can write your code here
}
I have a snippet of HTML that is part of a form where there are two input's. Via CSS I have managed to make the label associated with each input to sit inside their corresponding input to act as a placeholder.
Now, with some standard JS (not JQuery I'm afraid), I wanted to capture the event that the user does (i.e. on a mouse click or keyboard press) on the input and dynamically change the look and feel of the label.
http://jsfiddle.net/8nBAQ/2/
The conditions that I need to meet are:
When a user clicks on the input for the first time. The label changes colour to a light grey. After click, if the user then enters a character, the label disappears and the character you have just pressed is displayed instead.
When a user clicks on the input for the first time. The label changes colour to a light grey. After click, if the user then clicks or tabs away from the input, the label changes colour back to it's original state of black.
After entering a few characters into the input, if the user decides to delete the whole set of characters by either pressing backspace deleting each character until none are left or highlighting the whole set of characters with a mouse and presses the delete key, the label appears but is in a light grey colour.
Any help you can offer with the JS would be great!
Thanks
-JaXL
Here is my solution. I added the following to the input tag and label
<label class="label-inside" for="input1" id="input1_label" title="Enter input 1">Input 1</label>
<ul class="form-input">
<li>
<input type="text" id="input1" name="myInput1" value="" autocomplete="off" title="Enter Input 1" onblur="handleBlur(this, document.getElementById('input1_label'))"
onkeydown="handleFirstClick(event, this, document.getElementById('input1_label'))"
onkeyup="handleKey(this, document.getElementById('input1_label'))" />
</li>
</ul>
And here is my Javascript
<script>
function handleBlur(input, label )
{
if ( !input.value || input.value.length == 0)
{
label.style.display = 'block';
label.style.color = 'black';
label.clickedBefore = false;
}
}
function handleFirstClick(e, input, label )
{
if ( !label.clickedBefore )
{
label.clickedBefore = true;
e.preventDefault();
label.style.color = 'red';
}
}
function handleKey(input, label)
{
console.log("handling key up : " + input.value.length);
label.style.display = 'none';
if (!input.value || input.value.length == 0 )
{
label.style.display = 'block';
label.style.color = 'red';
}
}
</script>
Let me know if something else is needed.
EDIT : adding code to add all handlers at once according to input_id.
window.onload = function(){
console.log("windows loaded");
var labels = {}
var all_labels = document.getElementsByTagName("label");
for ( var i = 0; i < all_labels.length; i++)
{
labels[all_labels[i].getAttribute("for")] = all_labels[i];
}
function attachHandlers( input_id )
{
var input = document.getElementById(input_id);
var label = labels[input_id];
input.onclick = function(e){handleFirstClick(e, input, label)};
input.onkeyup = function(e){handleKey(input, label)};
input.onblur = function(e){handleBlur(input, label)};
}
var attachInput = ["input1"];
for ( var j =0; j <attachInput.length; j++)
{
attachHandlers(attachInput[j]);
}
}
I have a drop down if i click it will retrieve values from db.If thre are 4 values that has to pass into text box and make it visible.If 5 values then 5 values has to get visible.There will be a count if 4 boxes count has to get into 5th box.if 5 values then count has to get int0 6th box.
How do i do it?
If the text boxes are in the markup and you've just hidden them (e.g., style="display: none"), you can show them again by setting their style.display property to "":
textBoxElement.style.display = "";
For example, here's a button click handler that looks for a text field to show and shows it; if there aren't any more to show, it hides the button:
var myForm = document.getElementById('myForm');
document.getElementById('btnShowField').onclick = function() {
var index, field, foundOne, foundMore;
foundOne = foundMore = false;
for (index = 0; index < myForm.elements.length; ++index) {
field = myForm.elements[index];
if (field.type === "text" && field.style.display === "none") {
if (!foundOne) {
// Found one, show it
field.style.display = "";
foundOne = true;
}
else {
// Found more, so we don't need to hide the button
foundMore = true;
break;
}
}
}
if (!foundMore) {
// No more hidden fields, hide the button
this.style.display = "none";
}
};
Live example
If you want to add more text boxes to a form at runtime when they aren't in the markup, you can easily do that:
var textBox = document.createElement('input');
textBox.type = "text";
textBox.name = "somename";
formElement.appendChild(textBox);
Live example
Usually the structure will be a bit more complex than that, but that's the general idea.
Off-topic: A lot of these things can be made dramatically easier by leveraging a JavaScript library like jQuery, Prototype, YUI, Closure, or any of several others. They'll smooth over browser differences and provide a lot of value-add functionality, so you can focus on what you're actually trying to do rather than browser quirks and such.