Issue in reloading of names while live search using JavaScript - javascript

so I was trying to make a simple search option whereas the user types in the name, the name shows up. However, with my code, the name shows up only when the user completely types the name right. Basically, I want it to show all available names relevant to user's search (If user
const li = document.querySelectorAll("li");
const input = document.querySelector("#search");
const form = document.querySelector("form");
const searchBtn = document.querySelector("button");
const loopThrough = () => {
for (var i = 0; i < li.length; i++) {
if (input.value.toLowerCase() === li[i].innerText.toLowerCase()) {
li[i].style.display = "block";
}
if (li[i].style.display = "block" && input.value.toLowerCase().length == 0) {
li[i].style.display = "none";
}
}
}
input.addEventListener("keyup", loopThrough);
<form>
<input type="search" id="search" placeholder="Search here...">
<button type="button">Search</button>
</form>
<ul>
<li>Pierre</li>
<li>Peter</li>
<li>Philip</li>
<li>Mazen</li>
<li>Zeina</li>
<li>Anna</li>
<li>Wael</li>
<li>Fadi</li>
<li>Faris</li>
<li>Walid</li>
</ul>
types "p", I want all names that start with "p" to show up.)
and initially, in CSS, all li display property is set to none

This is a trivial thing to do with JavaScript and a document like you have. Some pointers:
Forget "keyup", and in fact all explicit keyboard events. You are doing yourself and your users disservice. Not all devices have keyboards, and smart people behind Web standards have long ago foreseen this and there are "input" and "change" events available to fire on every text input control.
You can initiate a search on every "input" or "change" event, but if your search queries take any time at all, you would be wise to reset a search timeout on every "input" event at least instead -- some people type very fast, and there is no good need on application's part to run a search query for every letter typed -- that would be well over 10 searches a second in many cases for fast typers. Waste of resources -- reset a timeout so that a search is queued after half a second or so. The number should typically be user's preference, but it's a minute preference that most people won't bother with, so just use some good enough average.
Don't use inline styles in this case. They very seldom are a fitting part of a solution. Use CSS classes, so that behavior and style of the elements that match your search, can be specified in the stylesheet. Or you can use the hidden attribute, it may be suitable, depending.
Here is some off-the-top-of-my-head code that solves your problem, adapted from your snippet:
var timeout;
document.getElementById("form").elements.search.addEventListener("input", function(ev) {
if(timeout) clearTimeout(timeout);
timeout = setTimeout(function(input) {
for(const li of document.querySelectorAll("li")) {
li.classList.toggle("match", li.textContent.startsWith(input.value));
}
}, 500, ev.target);
});

Use startsWith function
With your code:
const li = document.querySelectorAll("li");
const input = document.querySelector("#search");
const form = document.querySelector("form");
const searchBtn = document.querySelector("button");
const loopThrough = () => {
for (var i = 0; i < li.length; i++) {
if (input.value.toLowerCase().startsWith(li[i].innerText.toLowerCase())) {
li[i].style.display = "block";
}
if (li[i].style.display = "block" && input.value.toLowerCase().length == 0) {
li[i].style.display = "none";
}
}
}
input.addEventListener("keyup", loopThrough);

Related

Get JavaScript Object

I am working client side on a web page that I am unable to edit.
I want to use JS to click on a particular button, but it does not have a unique identifier.
I do know the class and I do know a (unique) string in the innerHTML that I can match with, so I am iterating through the (varying number) of buttons with a while loop looking for the string:
var theResult = '';
var buttonNum = 0;
var searchString = '720p';
while (theResult.indexOf(searchString) == -1
{
theResult = eval(\"document.getElementsByClassName('streamButton')[\" + buttonNum + \"].innerHTML\");
buttonNum++;
}
Now I should know the correct position in the array of buttons (buttonNum-1, I think), but how do I reference this? I have tried:
eval(\"document.getElementsByClassName('streamButton')[\" + buttonNum-1 + \"].click()")
and variation on the position of ()'s in the eval, but I can't get it to work.
You could try something like:
var searchStr = '720p',
// Grab all buttons that have the class 'streambutton'.
buttons = Array.prototype.slice.call(document.querySelectorAll('button.streamButton')),
// Filter all the buttons and select the first one that has the sreachStr in its innerHTML.
buttonToClick = buttons.filter(function( button ) {
return button.innerHTML.indexOf(searchStr) !== -1;
})[0];
You don't need the eval, but you can check all the buttons one by one and just click the button immediately when you find it so you don't have to find it again.
It is not as elegant as what #Shilly suggested, but probably more easily understood if you are new to javascript.
var searchString = '720p';
var buttons = document.getElementsByClassName("streamButton"); // find all streamButtons
if(buttons)
{
// Search all streamButtons until you find the right one
for(var i = 0; i < buttons.length; i++)
{
var button = buttons[i];
var buttonInnerHtml = button.innerHTML;
if (buttonInnerHtml.indexOf(searchString) != -1) {
button.click();
break;
}
}
}
function allOtherClick() {
console.log("Wrong button clicked");
}
function correctButtonClick() {
console.log("Right button clicked");
}
<button class='streamButton' onclick='allOtherClick()'>10</button>
<button class='streamButton' onclick='allOtherClick()'>30</button>
<button class='streamButton' onclick='correctButtonClick()'>720p</button>
<button class='streamButton' onclick='allOtherClick()'>abcd</button>
I would stay clear of eval here, what if the text on the button is some malicious javaScript?
Can you use jQuery? if so, check out contains. You can use it like so:
$(".streamButton:contains('720p')")

How to set input field maxlength from label

I'm trying to figure out a way to change the maxlength of ajax called input fields by pulling the value to set out of the field's label and updating the default value. The field labels all follow the same format - id, class, type and maxlength. The new maxlength value to set is always present in the id ...max_X_characters...
`<input id="ecwid-productoption-16958710-Line_5_:0028max_4_characters:0029" class="gwt-
TextBox ecwid-productBrowser-details-optionTextField ecwid-productoption-
Line_5_:0028max_4_characters:0029" type="text" maxlength="200"></input>`
So in this example I need to set the maxlength to 4.
The other problem is that there are multiple input fields, often with different maxlength values. See here for an example.
I was thinking of setting a script to pull out the value once the fields have loaded, but I don't mind admitting it, this one's over my head - hopefully one of you bright guys n gals can figure it out!
Update: Thanks for the suggestions, I've tried both, in various combinations, but can't get them to work.
Here's the code suggested by Ecwid's tech team that sets all input fields on the page to one maxlength (6 in this case)
`Ecwid.OnPageLoaded.add(function(page){if (page.type == "PRODUCT") {
$("input.ecwid-productBrowser-details-optionTextField").attr('maxlength','6');
};
})`
However, as I stated there are input fields with different maxlengths for some products.
I've tried replacing the '6' above with a function, based on your suggestions, to get the maxlength from the input id, but can't get it to work.
Any more ideas?
Thanks
Update:
Cracked it (nearly), here's the working code
`Ecwid.OnPageLoaded.add(function(page){
var regex = new RegExp("max_(\\d+)_characters");
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
var inp = inputs[i];
if (regex.test(inp.id)) {
var newLimit = inp.id.match(regex)[1];
inp.maxLength = newLimit;
}
}
});`
Thanks so much for your help, it works like a dream on the product page but there is another area where it doesn't. A customer can edit the input text via a pop-up, from the shopping basket.
The fields have similar code:
`<input id="ecwid-productoption-16958710-Line_5_:0028max_4_characters:0029"
class="gwt-TextBox ecwid-productBrowser-details-optionTextField ecwid-productoption-
Line_5_:0028max_4_characters:0029" type="text" maxlength="200"></input>`
Suggestions very welcome
Chris
UPDATE:
Many, many, many thanks to ExpertSystem (you genius you!) - I think we've got it. (tested on IE10, firefox 21, chrome 27).
The code below is for people using Yola and Ecwid together, but I guess the original code may work for people using other sitebuilders. It limits the number of characters a user can enter into input fields, in Ecwid, by checking for a number in the input field's title (in this case the value between 'max' and 'characters') and replacing that as the field's maxLength value. It limits fields in the product browser, in the html widgets and in the cart pop-up.
Here it is:
Go to Yola's Custom Site Tracking Code section. In the 'Footer Code' column (actually placed at the bottom of the 'body'), place this code:
<script>
Ecwid.OnPageLoaded.add(function(page){
var regex = new RegExp("max_(\\d+)_characters");
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
var inp = inputs[i];
if (regex.test(inp.id)) {
var newLimit = inp.id.match(regex)[1];
inp.maxLength = newLimit;
}
}
});
</script>
<script>
var regex = new RegExp("max_(\\d+)_characters");
function fixMaxLength(container) {
var inputs = container.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
var inp = inputs[i];
if (regex.test(inp.id)) {
var newLimit = inp.id.match(regex)[1];
inp.maxLength = newLimit;
}
}
};
</script>
and this into the 'Header Code' column:
<script>
document.addEventListener("DOMNodeInserted", function() {
var popups = document.getElementsByClassName("popupContent");
for (var i = 0; i < popups.length; i++) {
fixMaxLength(popups[i]);
}
});
</script>
That's it! You're good to go.
It is not exactly clear what is meant by "ajax called input fields", but supposing that the input fields are created and added to DOM inside a success callback for some AJAX call, you can place the following piece of code in your pages <head>:
var regex = new RegExp("max_(\\d+)_characters");
function fixMaxLength(container) {
var inputs = container.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
var inp = inputs[i];
if (regex.test(inp.id)) {
var newLimit = inp.id.match(regex)[1];
inp.maxLength = newLimit;
}
}
}
And then, at the end of the AJAX call's "onSuccess" callback, append this:
fixMaxLength(document);
UPDATE:
Based on your comments below, if you need to apply fixMaxLength() to div's of class "popupContent", which get dynamically added to your DOM, an easy way (not the most efficient though) would be adding a listener for DOM modification events (e.g. somewhere in <head>):
document.addEventListener("DOMNodeInserted", function() {
var popups = document.getElementsByClassName("popupContent");
for (var i = 0; i < popups.length; i++) {
fixMaxLength(popups[i]);
}
});
(NOTE: I have only tested it on latest versions of Chrome and Firefox, so I am not really sure for which other/older browsers this does work.)
(NOTE2: GGGS, has tested it (and found it working) on IE10 as well.)
How about a regular expression on your id attribute? Such as the following:
jQuery('input').each(function() {
var idVal = jQuery(this).attr('id');
var regex = /max_(\d+)_characters/g;
var result = regex.exec(idVal);
var length = result[1];
});
This is a loop over all the inputs. Once this is run, the length variable will have the proper length each go through, for your next step.

use javascript to dislay a form field as text until clicked on

I have got this working with the start point as a span, but I want to have the form still function if javascript is disabled in the browser this is how I had it working originally. I'm still very new to javascript, can someone lend a hand please.
window.onload = function() {
document.getElementById('container').onclick = function(event) {
var span, input, text;
// Get the event (handle MS difference)
event = event || window.event;
// Get the root element of the event (handle MS difference)
span = event.target || event.srcElement;
// If it's a span...
if (span && span.tagName.toUpperCase() === "SPAN") {
// Hide it
span.style.display = "none";
// Get its text
text = span.innerHTML;
// Create an input
input = document.createElement("input");
input.type = "text";
input.size = Math.max(text.length / 4 * 3, 4);
span.parentNode.insertBefore(input, span);
// Focus it, hook blur to undo
input.focus();
input.onblur = function() {
// Remove the input
span.parentNode.removeChild(input);
// Update the span
span.innerHTML = input.value;
// Show the span again
span.style.display = "";
};
}
};
};
Best way to do this would be to show the input first, then quickly swap it out when the page loads, then swap it back when the user clicks.
You might also consider using the form element the whole time, but just changing CSS classes on it to make it look like normal text. This would make your UI cleaner and easier to maintain in the future.
Then just put the input fields there from the start, and hide them with a script that runs when the form has loaded. That way all the fields will be visible if Javascript is not supported.
I think your best option would be to wrap a form with noscript tags which will fire when Javascript is disabled in a browser. If they display even while in the noscript tags then just set them as not visible with Javascript.
if you have jQuery, something like this should work.
function makeElementIntoClickableText(elm){
$(elm).parent().append("<div onClick='switchToInput(this);'>"+ elm.value +"</div>");
$(elm).hide();
}
function switchToInput(elm){
$(elm).prev().prev().show();
$(elm).hide();
}
makeElementIntoClickableText($("input")[0]);
use the readonly attribute in the input elements:
<input type="text" readonly />
And then remove that attribute with JavaScript in the onclick event handler, reassigning it on blur:
var inputs = document.getElementsByTagName('input');
for (i=0; i < inputs.length; i++) {
inputs[i].setAttribute('readonly',true);
inputs[i].onclick = function(){
this.removeAttribute('readonly');
};
inputs[i].onblur = function(){
this.setAttribute('readonly',true);
};
}
JS Fiddle demo.

Dynamic index setting in javascript

I have a table to which i need to add rows dynamically on click of a button. Each row has 3 textboxes and a clear button. On click of clear the data in the textboxes need to be cleared i.e. onclick of the button i send the index of the row to a method which deletes the contents of the textboxes at that index.
Problem - How do i specify the index number in the onClick property of the row button while adding the new row?
How do i specify the index number in the onClick property of the row button while adding the new row?
You don't. Instead, use the fact that the textboxes and the button are in the same row. I probably wouldn't use onclick on the button at all; instead, I'd have a single click handler on the table and handle the button clicks there (this is called event delegation). Something like this:
var table = document.getElementById("theTableID");
table.onclick = function(event) {
var elm, row, boxes, index, box;
// Handle IE difference
event = event || window.event;
// Get the element that was actually clicked (again handling
// IE difference)
elm = event.target || event.srcElement;
// Is it my button?
if (elm.name === "clear") {
// Yes, find the row
while (elm && elm !== table) {
if (elm.tagName.toUpperCase() === "TR") {
// Found it
row = elm;
break;
}
elm = elm.parentNode;
}
if (row) {
// Get all input boxes anywhere in the row
boxes = row.getElementsByTagName("input");
for (index = 0; index < boxes.length; ++index) {
box = boxes[index];
if (box.name === "whatever") {
box.value = "";
}
}
}
}
};
...but if you want to keep using the onclick attribute on the button instead, you can grab the middle of that:
The button:
<input type="button" onclick="clearBoxes(this);" ...>
The function:
function clearBoxes(elm) {
var row, boxes, index, box;
// Find the row
while (elm) {
if (elm.tagName.toUpperCase() === "TR") {
// Found it
row = elm;
break;
}
elm = elm.parentNode;
}
if (row) {
// Get all input boxes anywhere in the row
boxes = row.getElementsByTagName("input");
for (index = 0; index < boxes.length; ++index) {
box = boxes[index];
if (box.name === "whatever") {
box.value = "";
}
}
}
}
References:
DOM2 Core specification - well-supported by all major browsers
DOM2 HTML specification - bindings between the DOM and HTML
DOM3 Core specification - some updates, not all supported by all major browsers
HTML5 specification - which now has the DOM/HTML bindings in it, such as for HTMLInputElement so you know about the value and name properties.
Off-topic: As you can see, I've had to work around some browser differences and do some simple utility things (like finding the nearest parent element of an element) explicitly in that code. If you use a decent JavaScript library like jQuery, Prototype, YUI, Closure, or any of several others, they'll do those things for you, letting you concentrate on your actual problem.
To give you an idea, here's that first example (handling the click via event delegation) written with jQuery:
$("#theTableID").delegate("input:button[name='clear']", "click", function() {
$(this).closest("tr").find("input:text[name='whatever']").val("");
});
Yes, really. And other libraries will similarly make things simpler.
Best to use event delegation, or you can use this in JavaScript.
Event Delegation w/jQuery
<input class="clear-row-btn" type="button" >Clear Row</input>
.live event
$(".clear-row-btn").live("click", function(){
var $tr = $(this).closest("tr");
$tr.find("input[type='text']").val("");
});
HTML w/onclick method
<input type="button" onclick="clearRow(this)" >Clear Row</input>
jQuery
function clearRow(btn) {
var $tr = $(btn).closest("tr");
$tr.find("input[type='text']").val("");
}
JavaScript
function clearRow(element) {
while(element.nodeName!='TR'){
element = element.parentNode;
}
//find textboxes inside the element, which is now the parent <tr>
}

Limit the number of children in a form using Javascript

I am trying to limit the number of additional form input fields that a user can add dynamically to a file upload form to just 3. The form is loaded with one static input field and through javascript can add additional fields with an add button or remove additional form input fields with a remove button. Below is the html in it's static form.
<fieldset>
<legend>Upload your images</legend>
<ol id="add_images">
<li>
<input type="file" class="input" name="files[]" />
</li>
</ol>
<input type="button" name="addFile" id="addFile" value="Add Another Image" onclick="window.addFile(this);"/>
</fieldset>
With javascript I would like to create a function where the number of child elements are counted and if the number is equal to three then the "Add Another Image" button becomes disabled. In addition, if there are three elements in the form the user - with the remove button - removes a child then the "Add Another Image" button becomes enabled again.
I think I'm may be missing some crucial lines of code. The below javascript code only allows me to add one additional input field before the Add Another Image button becomes disabled. Removing this field with the remove file button removes the field but the Add Another Image button is still disabled. Below is where I'm currently at with the javascript.
function addFile(addFileButton) {
var form = document.getElementById('add_images');
var li = form.appendChild(document.createElement("li"));
//add additional input fields should the user want to upload additional images.
var f = li.appendChild(document.createElement("input"));
f.className="input";
f.type="file";
f.name="files[]";
//add a remove field button should the user want to remove a file
var rb = li.appendChild(document.createElement("input"));
rb.type="button";
rb.value="Remove File";
rb.onclick = function () {
form.removeChild(this.parentNode);
}
//create the option to dispable the addFileButton if the child nodes total "3"
var nodelist;
var count;
nodelist = form.childNodes;
count = nodelist.length;
for(i = 0; i < count; i++) {
if (nodelist[i] ==3) {
document.getElementById("addFile").disabled = 'true';
}
else { //if there are less than three keep the button enabled
document.getElementById("addFile").disabled = 'false';
}
}
}
Oh, OK, I've tested out the code now and see a couple of problems:
You're counting the number of child elements but this includes the text elements so there's actually one for the <li> and one for the text within it.
You've enclosed the true/false setting for the disabled property in quotes but it doesn't work and always set's it to false.
The remove button doesn't re-enable the add button.
I found this to work:
function addFile(addFileButton) {
var form = document.getElementById('add_images');
var li = form.appendChild(document.createElement("li"));
//add additional input fields should the user want to upload additional images.
var f = li.appendChild(document.createElement("input"));
f.className="input";
f.type="file";
f.name="files[]";
//add a remove field button should the user want to remove a file
var rb = li.appendChild(document.createElement("input"));
rb.type="button";
rb.value="Remove File";
rb.onclick = function () {
form.removeChild(this.parentNode);
toggleButton();
}
toggleButton();
}
function toggleButton() {
var form = document.getElementById('add_images');
//create the option to dispable the addFileButton if the child nodes total "3"
var nodelist;
var count;
nodelist = form.childNodes;
count = 0;
for(i = 0; i < nodelist.length; i++) {
if(nodelist[i].nodeType == 1) {
count++;
}
}
if (count >= 3) {
document.getElementById("addFile").disabled = true;
}
else { //if there are less than three keep the button enabled
document.getElementById("addFile").disabled = false;
}
}
I would suggest a slightly different approach. Create all three file input fields statically and provide a clear button. If the user chooses to leave it empty they can. If that is not elegant use your "Remove" to simply hide the field (CSS style display: none;).
I'm not sure why you're using the for loop? Shouldn't it be like this:
var nodelist = form.childNodes;
if (nodelist.length >= 3) {
document.getElementById("addFile").disabled = 'true';
}
else { //if there are less than three keep the button enabled
document.getElementById("addFile").disabled = 'false';
}
The last part of that function is a bit strange. Technically, when adding fields, you should only be disabling the button (i.e. you could never enable the button by adding fields). I would suggest removing the for loop and going with:
var count = form.getElementsByTagName("li").length;
if(count == 3)
document.getElementById("addFile").disabled = true;
The reason the add field button is still disabled when you remove an item is because you don't re-enable the add field button when you click remove. Try this for the remove button click handler:
rb.onclick = function () {
form.removeChild(this.parentNode);
document.getElementById("addFile").disabled = false;
}

Categories