getElementsByClassName is not working in if condition - javascript

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;

Related

Why can't get input value checkbox in array?

In the code described below, the value of the input should be taken from everyone in the array and a new div with the input value in innerHtml should be created. I don't know why get an error that length.value not defined?
<input type="checkbox" class="checkboxnewdivs" id="checkboxnewdivs" name="checkboxnewdivs" value="divsone">
<input type="checkbox" class="checkboxnewdivs" id="checkboxnewdivs" name="checkboxnewdivs" value="divstwo">
<input type="checkbox" class="checkboxnewdivs" id="checkboxnewdivs" name="checkboxnewdivs" value="divsthree">
<button onclick="myFunction()">Click me</button>
<div id="container"></div>
function myFunction() {
let array = [];
var checkboxnewdivs = document.querySelectorAll('input[name="checkboxnewdivs"]:checked');
for (var i = 0; i < checkboxnewdivs.length; i++) {
var iddivs = array.push(checkboxnewdivs[i].value);
var div_new = document.createElement("DIV");
div_new.innerHTML = "ID div:"+iddivs ;
document.getElementById("container").appendChild(div_new);
}
}
var checkboxnewdivs = document.querySelectorAll('input[name="checkboxnewdivs"]:checked').value;
Should be
var checkboxnewdivs = document.querySelectorAll('input[name="checkboxnewdivs"]:checked');
The first one is trying to get a value property from a node collection, which will obviously be undefined.
You also had some typos (double 's') and don't define array anywhere. Define that where you defined checkboxnewdivs.
Working demo: https://jsfiddle.net/mitya33/m9L2dvz5/1/

How do you make javascript(including function with array and return) write in div on button click without going to another page

I have had a lot of problems with this problem. When I console.log(sum); I get the answer I am looking for, but when I try to output the answer from a button click and an input field it does not work. I changed felt3.innerHTML=addnumber(ttt); to document.write(addnumber(ttt)); which made it work, but it is sending it to another page, which is something I do not want. How I can make this work:
<form id="form3">
Tall:<input type="number" id="number"><br>
<input type="button" id="button3" value="plusse"><br>
</form>
<div id="felt3"></div>
and:
var number = document.getElementById("number");
var felt3 = document.getElementById("tall3");
var form3 = document.getElementById("form3");
var button3 = document.getElementById("button3");
var sum=0;
function addnumber(x){
var array = [];
array.push(x);
for (var i = 0; i < array.length; i++) {
sum=sum+array[i];
}
return sum;
}
button3.onclick=function(){
var ttt=Number(number.value);
felt3.innerHTML=addnumber(ttt);
}
If I understand your question correctly, then the solution here is to update the argument that you are passing to getElementById("tall3"), rewriting it to document.getElementById("felt3");.
Doing this will cause your script to aquire the reference to the div element with id felt3. When your onclick event handler is executed, the result of addnumber() will be assigned to the innerHTML of the valid felt3 DOM reference as required:
var number = document.getElementById("number");
// Update this line to use "felt3"
var felt3 = document.getElementById("felt3");
var form3 = document.getElementById("form3");
var button3 = document.getElementById("button3");
var sum=0;
function addnumber(x){
var array = [];
array.push(x);
for (var i = 0; i < array.length; i++) {
sum=sum+array[i];
}
return sum;
}
button3.onclick=function(){
var ttt=Number(number.value);
// Seeing that felt3 is now a valid reference to
// a DOM node, the innerHTML of div with id felt3
// will update when this click event is executed
felt3.innerHTML=addnumber(ttt);
}
<form id="form3">
Tall:<input type="number" id="number"><br>
<input type="button" id="button3" value="plusse"><br>
</form>
<div id="felt3"></div>

Coloring specific elements in a string

I'm working on a code to color all the curly brackets from my input field (textt). I have no problem finding them using a for and if statement, but i cant seem to color them or even make them bold. This is what i have currently:
function colorBrackets() {
var string = document.getElementById("textt").value;
var a = string.split(" ");
var result = "";
for (var i=0; i<a.length; i++) {
if((a[i] == "{") || (a[i] == "}")) {
a[i].style.color = "blue";
}
}
//brackets is my output field
document.getElementById("brackets").value = result;
}
I appreciate any help!
You need to insert spans around the part of the text you want to color.
I just replaced the { and } in the text with { and } surrounded by styled spans.
Then appended it back as innerHTML and voila.
function colorBrackets() {
let string = document.getElementById("input").innerText;
let result = string.replace(/{|}/g, '<span style="color: red">$&</span>');
document.getElementById("output").innerHTML = result;
}
colorBrackets();
<div id="input">{Hello }</div>
<div id="output"></div>
PS: This wouldn't work inside an input field. Since the value of an input has to be a string and not HTML. But the good news is that you can apply it in a div with contenteditable = true.

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;

Removing a div as user removes input in 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';
}
}

Categories