Removing a div as user removes input in javascript - javascript

I'm trying to take user input, match result, display result in drop-down, and then click on a name from drop down to display it. I've been able to display result in drop-down using innerHTML but it wasn't clickable so now I'm dynamically creating Div elements. However, I'm not sure how to clear the list when user presses backspace. I was previously doing that with document.getElementById('placeholder').innerHTML="" statement. Here's what I've done so far. The code in comments is for when I was displaying the drop down menu using innerHTML:
HTML code:
<body>
<input id="filter" type="text" placeholder="Enter your filter text here.."
onkeyup="test()"/>
<div id="lc">
<!--- <p id='placeholder'> </p> -->
</div>
<script type="text/javascript" src="js/filter.js"></script>
</body>
JS code:
// JavaScript Document
s1 = new String()
var myArray = new Array();
myArray[0] = "Donald Duck";
myArray[1] = "Winnie Pooh";
myArray[2] = "Komal Waseem";
myArray[3] = "Hockey";
myArray[4] = "Basketball";
myArray[5] = "Shooting";
myArray[6] = "Mickey Mouse";
function test() {
s1 = document.getElementById('filter').value;
var myRegex = new RegExp((s1),"ig");
arraysearch(myRegex);
}
function arraysearch(myRegex) {
var flag=0;
//document.getElementById('placeholder').innerHTML="";
for(i=0; i<myArray.length; i++) {
//if(myArray[i].charAt(0).indexOf(s1) != -1) {
if(myArray[i].match(myRegex)) {
flag = 1;
//document.getElementById('lc').style.visibility = 'visible';
//document.getElementById('placeholder').innerHTML += myArray[i]+"<br/>";
var element = document.createElement("div");
element.appendChild(document.createTextNode(myArray[i]));
document.getElementById('lc').appendChild(element);
}
//}
if (flag == 0) {
document.getElementById('lc').style.visibility='hidden';
}
}

Related

Making array with input of textarea

I'm trying to capture the input of a textarea and converting it to an array but it is reading the whole input as one element and making array of length 1.
<html>
<textarea id="area"></textarea>
<input type="submit" onclick="won()">
<p id="one" style="display: none;"></p>
</html>
The js part displays a message of the length of the array.
var area = document.getElementById("area");
var lines = area.value.split("\n");
var pa = document.getElementById("one");
function won() {
pa.style.display = "block";
pa.innerHTML = lines.length;
}
What I'm trying to achieve with the whole thing is that. The multi line input is to be converted into an array with each new line being a new element. Then I loop through the array and if even one element doesn't pass a validation function, an exception message is displayed under the texarea.
Can someone kindly help me with this?
With your snippet, you're grabbing the value onload so it would be empty, it should be in the event where you grab the value. Also avoid inline event triggering, add the event via js.
var area = document.getElementById("area");
var button = document.getElementById("btn-submit");
var one = document.getElementById("one");
button.addEventListener('click', () => {
// get value
var lines = area.value.split("\n");
one.style.display = "block";
one.innerHTML = lines.length;
})
<textarea id="area"></textarea>
<button type="button" id="btn-submit">Submit</button>
<p id="one" style="display: none;"></p>
What I'm trying to achieve with the whole thing is that. The multi
line input is to be converted into an array with each new line being a
new element. Then I loop through the array and if even one element
doesn't pass a validation function, an exception message is displayed
under the texarea.
const area = document.getElementById("area");
const button = document.getElementById("btn-submit");
const error = document.getElementById("error");
const items = document.getElementById("items");
button.addEventListener('click', () => {
// get textarea value, remove emptys
const lines = area.value.split("\n").filter(Boolean);
// reset error and items dom
error.innerHTML = items.innerHTML = ''
// do your validation, could loop or use .some(), .includes()
if (!lines.length) {
error.innerHTML = 'Enter at least one item'
} else if (!lines.includes('cat')) {
error.innerHTML = 'Entered lines should include at least one cat'
} else {
// no errors
items.innerHTML = `${lines.length} items<br><ul><li>${lines.join('</li><li>')}</li></ul>`
}
})
<textarea id="area"></textarea>
<button type="button" id="btn-submit">Submit</button>
<div id="error"></div>
<div id="items"></div>
Simply put your line var lines = area.value.split("\n"); under the won function like below and you will get your total lines.
Example
var area = document.getElementById("area");
var pa = document.getElementById("one");
function won() {
var lines = area.value.split("\n");
pa.style.display = "block";
pa.innerHTML = lines.length;
}
You can check it here too, https://codepen.io/vadera-abhijeet/pen/yLPxLRY

getElementsByClassName is not working in if condition

I'm Trying to get all the classnames with "items" and checking if innerHTML of each className by for loop and with given string. But even though the condition is true, nothing is happening in if condition.
I've implemented with the javascript and everything is working except the getElementsByClassName is not working
function clearAndAdd(){
var texter = document.getElementById("textBox").value;
if (texter != ""){
var allList = [];
document.getElementById("textBox").value = "";
created = 'deleteCurrent("'+texter+'")';
document.getElementById("lister").innerHTML = document.getElementById("lister").innerHTML+"<li class='items' onclick='"+created+"'>"+texter+"<span></span></li>";
document.getElementById("textBox").focus();
}
}
function deleteCurrent(text){
var allList = [];
var list = document.getElementsByClassName("items");
for(var i=0; i<list.length; i++){
var value = list[i].innerHTML;
if (value == text){
document.getElementById("output").innerHTML = value;
break;
}
}
}
<!-- HTML code -->
<body>
<div class="input-categories">
<ul id="lister">
</ul>
<input type="text" id="textBox" onblur="clearAndAdd();" />
</div>
<div id="output">
</div>
</body>
When I'm running the code with passing the string in text... even the value and the text are same, if condition is not executed. Can anyone help me with this
The content returned by list[i].innerHTML contains a <span> tag, so obviously it will never match the text you look for.
Instead of innerHTML use the textContent property: that will just return the text content:
var value = list[i].textContent;

Search function filter li's in pure Js

I'm trying to make an input that filters a <ul> based on the value in pure JavaScript. It should filter dynamically with the onkeyup by getting the li's and comparing their inner element name with the filter text.
Here is my function:
var searchFunction = function searchFeature (searchString) {
console.log("Is my search feature working?");
//Get the value entered in the search box
var inputString = document.getElementById('inputSearch');
var stringValue = inputString.value;
//Onkeyup we want to filter the content by the string entered in the search box
stringValue.onkeyup = function () {
//toUpperCase to make it case insensitive
var filter = stringValue.toUpperCase();
//loop through all the lis
for (var i = 0; i < eachStudent.length; i++) {
//Do this for all the elements (h3, email, joined-details, date)
var name = eachStudent[i].getElementsByClassName('student-details')[1].innerHTML;
//display all the results where indexOf() returns 0
if (name.toUpperCase().indexOf(filter) == 0)
eachStudent[i].style.display = 'list-item';
else
eachStudent[i].style.display = 'none';
}
}}
My HTML for the search bar:
<div class="student-search">
<input id="inputSearch" placeholder="Type name here.." type="text"> <button>Search</button></div>
My HTML for one of the li's:
<ul class="student-list">
<li class="student-item cf">
<div class="student-details">
<img class="avatar" src="#">
<h3>John Doe</h3>
<span class="email">John.Doe#example.com</span>
</div>
<div class="joined-details">
<span class="date">Joined 01/01/14</span>
</div>
</li>
I would like to filter all the elements (name, email, joined date) based on the value of the input.
Unfortunately, I don't get any errors and it's simply not working.
The function is correctly invoked because the console.log prints...
Here goes the codepen: http://codepen.io/Delano83/pen/qaxxjA?editors=1010
Any help or comments on my code is very appreciated.
There were several issues:
stringValue.onkeyup - stringValue is the value. You can't onkeyup it.
var eachStudent = document.querySelector(".student-item"); will fetch the first thing with student-item class. You need to use querySelectorAll or just use jquery's $('.find-item').
if (name.toUpperCase().indexOf(filter) == 0) indexOf returns 0 if the filter is found at the beginning of the name. 0 as match if found at index 0. You need to check against -1, which means it was not found at all.
Otherwise it more or less worked, good job.
I also added Jquery for me to fix it faster. If you insist on using pure javascript I am sure you will be able to edit it.
Check it out here: http://codepen.io/anon/pen/WGrrXW?editors=1010. Here is the resulting code:
var page = document.querySelector(".page");
var pageHeader = document.querySelector(".page-header");
var studentList = document.querySelector(".student-list");
var eachStudent = document.querySelectorAll(".student-item");
var studentDetails = document.querySelector(".student-details");
//Recreate Search Element in Js
var searchBar = function createBar(searchString) {
var studentSearch = document.createElement("div");
var input = document.createElement("input");
var searchButton = document.createElement("button");
input.type = "text";
var txtNode = document.createTextNode("Search");
if (typeof txtNode == "object") {
searchButton.appendChild(txtNode);
}
studentSearch.setAttribute("class", "student-search");
input.setAttribute("id", "inputSearch");
//append these elements to the page
studentSearch.appendChild(input);
studentSearch.appendChild(searchButton);
input.placeholder = "Type name here..";
return studentSearch;
}
var searchFunction = function searchFeature(searchString) {
console.log("Is my search feature working?");
//Get the value entered in the search box
var inputString = document.getElementById('inputSearch');
var stringValue = inputString.value;
//Onkeyup we want to filter the content by the string entered in the search box
inputString.onkeyup = function() {
//toUpperCase to make it case insensitive
var filter = $(this).val().toUpperCase()
//loop through all the lis
for (var i = 0; i < eachStudent.length; i++) {
//Do this for all the elements (h3, email, joined-details, date)
var name = $(eachStudent[i]).find('h3').text()
console.log(name, filter, name.toUpperCase().indexOf(filter))
//display all the results where indexOf() does not return -1
if (name.toUpperCase().indexOf(filter) != -1)
eachStudent[i].style.display = 'list-item';
else
eachStudent[i].style.display = 'none';
}
}
}
function addElements() {
console.log('Add search bar, trying to anyway...')
pageHeader.appendChild(searchBar());
// page.appendChild(paginationFilter());
onLoad();
}
window.onload = addElements;
window.onLoad = searchFunction;

Text Box Search / Javascript Function Arrays **not corresponding**

I want the user to "Search" some "Authors" and if they select the one in the database they are sent to a corresponding HTML. Otherwise "No Author Found" displays...
For some reason I cannot wrangle it properly - pls help!
//Search by Author
function searchAuth() {
var search_string = document.getElementById('search_string').value;
var arrayelement = ["John","Stan","Henry","Paul","Samuel"];
for (i=0;i<arrayelement.length;i++) {
if (input == arrayelement.John) {
var itemLink = document.getElementById('demo').innerHTML =
"<a href='https://www.google.ca/?gws_rd=ssl'>Your link</a>";
} else if (input == arrayelement.Stan) {
var itemLink = document.getElementById('demo').innerHTML =
"<a href='https://www.google.ca/?gws_rd=ssl'>Your link</a>";
}else {
var itemLink = document.getElementById('demo').innerHTML =
"Author not found."
}
}
<!--Author-->
<h3>Search By Author</h3>
<form name="searchTest" onsubmit="return(searchAuth());" action="#">
<input type="text" id="search_string" />
<input type="submit"/>
<p id="demo"></p>
Perhaps you are trying to do things like these..
P.S this is just a demo, for you to start :)
EDIT: added few explanation on some stuffs you might get confuse with. :)
//events once textbox gets out focus
//the events varies on which or where do you want to add the event. it can be on click of a search button or submit button just like in your example.
document.getElementById('search-text-box-id').addEventListener("focusout", function() {
//searchString gets the textbox value.
var searchString = document.getElementById('search-text-box-id').value;
var searchList = ["John","Stan","Henry","Paul","Samuel"];
//Loop searchList
for (i=0; i < searchList.length; i++) {
//i which usually means the index or the key of the array's object(s).
var searchItem = "";
//searchList[i] loops its object by getting the index resulting to John, Stan and so on and so forth.
if (searchString == searchList[i]) {
searchItem = searchList[i];
document.getElementById('search-result-container').innerHTML = searchItem + " link";
//stop looping as the loop found a match.
return;
}
else {
searchItem = "Author not found.";
document.getElementById('search-result-container').innerHTML = searchItem;
}
}
});
<label for="search-text-box"></label>
<input type="text" id="search-text-box-id" name="search-text-box" />
<p id="search-result-container"></p>

Code to detect option value does not work as expected

I was attempting to do some string comparisons in javascript. I have seen several tutorials and examples but they do not seem to work. I am missing something fundamental?
Attempt 1
function addAspect(aspect) {
var print = document.createElement('p');
var ptext;
if (aspect == "Option1") ptext = document.createTextNode("This is option1");
}
Doesnt work.
Then I found this example to which all readers said it worked fine
function addAspect() {
var print = document.createElement('p');
var ptext;
var aspect = String(document.getElementById("aspectResult").value);
if (aspect == "Option1") ptext = document.createTextNode("This is option1");
}
Doesnt work.
I also tried .toString() as well as the '===' exact match comparison.
Full code
<html>
<head>
<script type="text/javascript">
function addAspect()
{
var print = document.createElement('p');
var ptext;
var aspect = document.getElementById("aspectResult").value;
if (aspect == "Option1"){
ptext = document.createTextNode("This is option1");
}
print.appendChild(ptext);
document.getElementById("mainBlock").appendChild(print);
}
</script>
</head>
<body>
<form>
<select id="aspectResult">
<option value="Option1">Option1</option>
</select>
<input type="button" value="Check" onclick="addAspect()"/>
</form>
<span id="mainBlock">&nbsp</span>
</body>
</html>
Any suggestions?
First, a small introduction to how dropdowns work:
<select id="aspectResult">
<option value="Option1">Option1</option>
</select>
To read the selected value from the dropdown, you should do this:
var dropdown = document.getElementById('aspectResult'),
selectedValue = dropdown.options[dropdown.selectedIndex].value;
Then, you create the <p> element with a text node inside:
var p = document.createElement('p'),
txt;
if (selectedValue == 'Option1') {
txt = document.createTextNode('This is option 1');
}
Afterwards, you can append the newly created paragraph to the container of your choice:
var container = document.getElementById('mainBlock');
if (txt) {
p.appendChild(txt);
container.appendChild(p);
}
All together now!
If you are trying to add the ptext to the paragraph, you need to add two lines to the end:
function addAspect(aspect) {
var prnt = document.createElement('p');
var ptext;
if( aspect == "Option1" ) {
ptext = document.createTextNode("This is option1");
prnt.appendChild(ptext); // Add the text to the paragraph
document.body.appendChild(prnt); // Add the paragraph to the document
}
}
Your function creates a text node but then does nothing with it, so you code appears to do nothing at all. You need to append the text node to an element somewhere in the DOM:
document.body.appendChild(ptext);
Your full code appears to be working fine in IE9, Firefox 4 and Chrome 11. See http://jsbin.com/ekura5/.

Categories