OnKeyup search string and hide/show - jQuery - javascript

I'm trying to filter a list of span tags on keyup.
I've created something only it returns strange values...
https://jsfiddle.net/5u373deu/1/
function searchClients() {
var clientSearch = document.getElementById("clientSearch");
var s = clientSearch.value;
$('.select-options span:not(:contains("' + s + '"))').hide();
}
$("#clientSearch").keyup(function() {
searchClients();
});

To make it become case sensitive, you need to override your current contains
jQuery.expr[':'].contains = function(a, index, obj) {
return jQuery(a).text().toUpperCase()
.indexOf(obj[3].toUpperCase()) >= 0;
};
function searchClients() {
var clientSearch = document.getElementById("clientSearch");
var s = clientSearch.value;
$('.select-options span').show();
$('.select-options span:not(:contains("' + s + '"))').hide();
}
$("#clientSearch").keyup(function() {
searchClients();
});
span {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="select-options ps-container below ps-active-y">
<input id="clientSearch" type="text">
<span>Bitcoin</span><span>Cat</span><span>Whiskey</span><span>Table</span>

Try refreshing your display everytime :
Note that your search is case sensitive.
function searchClients() {
var clientSearch = document.getElementById("clientSearch");
var s = clientSearch.value;
$('.select-options span').show();
$('.select-options span:not(:contains("' + s + '"))').hide();
}
$("#clientSearch").keyup(function() {
searchClients();
});
span {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="select-options ps-container below ps-active-y">
<input id="clientSearch" type="text">
<span>Bitcoin</span><span>Cat</span><span>Whiskey</span><span>Table</span>

Here you go: https://jsfiddle.net/5u373deu/6/
The problem was with the fact that you were not showing all elements when the user cleared the filter text.
function searchClients() {
var clientSearch = document.getElementById("clientSearch");
var s = clientSearch.value;
$('.select-options span').show();
$('.select-options span:not(:contains("'+s+'"))').hide();
}
$("#clientSearch").keyup(function() {
searchClients();
});

Related

Placing the caret in an previous editable div and pressing enter should re-evaluate that input

I have this online code execution editable div that currently works step by step by using a function called parse. You input something (for example 7+5) and press enter and you get the result on a new line below and a new input div is created but if you go back to an previous editable input div and put in a new input and press enter it does not work correctly because a new output and input divs are created by default and the new code is not being re-evaluated.
Note that if you put in a : at the end of input in an input box (editable div) then no new output div is created. Output is hidden from view. This is by design to avoid long outputs that does not need to be displayed.
I have also tried to write a new function parse2() but then the step by step evaluation stops working. It appears to be very hard to get both (step by step and go back to old editable div and re-evaluate) to work at the same time. How can this be done? I think I need some if statement in function parse() that determines if it is new input code that being executed or old input code that being re-evaluated. I have also tried to assign a number to the input divs but I have not managed to get that to work.
function parse2(e) {
if (e.keyCode == 13) {
event.preventDefault();
if (document.getElementById("output") == null) {
CreateOutputDiv();
CreateInputDiv();
// calculates and assign values to output div
var d1 = document.getElementById(JSON.stringify(input)).innerText;
console.log("in = " + d1);
var d2 = eval(d1);
console.log("out = " + d2);
output.innerHTML = d2;
document.getElementById("count").value += '\n' + '\n' + cc;
} else if { //re-evaluates inputbox = works
var d1 = document.getElementById(JSON.stringify(input)).innerText;
console.log("new in = " + d1);
var d2 = eval(d1);
console.log("new out = " + d2);
output.innerHTML = d2;
input.focus();
} else { //re-evaluates inputbox = works
CreateOutputDiv();
var d1 = document.getElementById(JSON.stringify(input)).innerText;
console.log("new in = " + d1);
var d2 = eval(d1);
console.log("new out = " + d2);
output.innerHTML = d2;
input.focus(); }}}
JavaS.js and HTML below
// counts the number of input divs created
function increment() {
increment.n = increment.n || 0;
return ++increment.n;
}
// creates an input div
function CreateInputDiv() {
increment();
cc = increment.n;
console.log("increment.n = " + cc);
input = document.createElement("div");
input.setAttribute("id", "input");
input.setAttribute("class", "input");
input.innerHTML = "&nbsp";
input.setAttribute("contenteditable", "true");
input.setAttribute("onkeypress", "parse(event, this)");
document.getElementById('calc').appendChild(input);
input.focus();
}
// creates an output div
function CreateOutputDiv() {
output = document.createElement("div");
output.setAttribute("id", "output");
output.setAttribute("class", "output");
output.setAttribute("tabindex", "0");
output.setAttribute("contenteditable", "true");
document.getElementById('calc').appendChild(output);
}
function parse(e) {
var key = window.event.keyCode;
if (key == 13) { //keycode for enter
event.preventDefault();
var inz = input.innerText;
// check if input contains a colon. Hides output if colon exist.
if (inz.indexOf(':') > -1) {
// colon
var inz = input.innerText.replace(/:/g, '');
console.log("input without colon = " + inz);
var outz = eval(inz);
console.log("out = " + outz);
document.getElementById("count").value += '\n' + eval(cc + 1);
CreateInputDiv();
}
else {
// no colon = display output
// counter
document.getElementById("count").value += '\n' + '\n' + eval(cc + 1);
// create output div
CreateOutputDiv();
// calculate and assign output value to output div
console.log("input = " + inz);
var outz = eval(inz);
console.log("out = " + outz);
output.innerHTML = outz;
// creates a new input div
CreateInputDiv();
}
}
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="JavaS.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<meta charset="utf-8" />
<style>
div:focus {
background-color: lightpink;
}
.input {
background-color: lightgreen;
width: 980px;
border: none;
font-size: 16px;
resize: none;
overflow: auto;
overflow-wrap: break-word;
}
.output {
background-color: lightblue;
width: 980px;
border: none;
font-size: 16px;
resize: none;
overflow-wrap: break-word;
}
#count {
background-color: lightblue;
color: black;
width: 25px;
height: 650px;
font-size: 17px;
resize: none;
overflow: auto;
border: none;
}
#calc{
background-color:lightblue;
overflow: scroll;
vertical-align: top;
border: none;
}
</style>
</head>
<body bgcolor="grey">
<table align="center" width="1000px" height="650px" bgcolor="lightblue">
<tr>
<td><textarea id="count" disabled>1 </textarea> </td>
<td id = "calc"></td>
</tr>
</table>
<script> CreateInputDiv(); </script>
</body>
</html>
When you are creating new input and output divs, you are applying the same id to all inputs and outputs. Instead of which you can use your counter number 'cc' to give all unique ids. Then when you call your parse function, you already are supplying parameter 'this' to it. Use 'this' to get element by id. And if the div with this output id is already present, just alter its content, otherwise create a new one.
<script>
// counts the number of input divs created
function increment() {
increment.n = increment.n || 0;
return ++increment.n;
}
// creates an input div
function CreateInputDiv() {
increment();
cc = increment.n;
//console.log("increment.n = " + cc);
input = document.createElement("div");
input.setAttribute("id", "input"+cc);
input.setAttribute("class", "input");
input.innerHTML = "&nbsp";
input.setAttribute("contenteditable", "true");
input.setAttribute("onkeypress", "parse(event, this)");
document.getElementById('calc').appendChild(input);
input.focus();
}
// creates an output div
function CreateOutputDiv() {
output = document.createElement("div");
output.setAttribute("id", "output"+cc);
output.setAttribute("class", "output");
output.setAttribute("tabindex", "0");
output.setAttribute("contenteditable", "true");
document.getElementById('calc').appendChild(output);
}
function parse(e,e2) {
//console.log(e2);
var key = window.event.keyCode;
if (key == 13) { //keycode for enter
event.preventDefault();
//console.log(e2.id);
var inId = e2.id;
var outId = "output"+ inId.substring(5);
//console.log(outId);
var inz = input.innerText;
// check if input contains a colon. Hides output if colon exist.
if (inz.indexOf(':') > -1) {
// colon
var inz = input.innerText.replace(/:/g, '');
//console.log("input without colon = " + inz);
var outz = eval(inz);
//console.log("out = " + outz);
document.getElementById("count").value += '\n' + eval(cc + 1);
CreateInputDiv();
}
else {
// no colon = display output
// counter
if(document.getElementById(outId)) {
console.log("Already created");
inz = document.getElementById(inId).innerText;
console.log(inz);
var outz = eval(inz);
document.getElementById(outId).innerHTML = outz;
}
else {
document.getElementById("count").value += '\n' + '\n' + eval(cc + 1);
// create output div
CreateOutputDiv();
// calculate and assign output value to output div
//console.log("input = " + inz);
var outz = eval(inz);
//console.log("out = " + outz);
output.innerHTML = outz;
// creates a new input div
CreateInputDiv();
}
}
}
}
</script>

Javascript function .show() not using HTML code - on Page Search

I found some Javascript code that does exactly what I want it to do. It searches a page of <li> for text that you enter in a search box.
However, It does not show (or use) the HTML markup that is within the text.
$(document).ready(function() {
/* initially hide product list items */
$("#dino-list li").hide();
/* highlight matches text */
var highlight = function(string) {
$("#dino-list li.match").each(function() {
var matchStart = $(this).text().toLowerCase().indexOf("" + string.toLowerCase() + "");
var matchEnd = matchStart + string.length - 1;
var beforeMatch = $(this).text().slice(0, matchStart);
var matchText = $(this).text().slice(matchStart, matchEnd + 1);
var afterMatch = $(this).text().slice(matchEnd + 1);
$(this).html(beforeMatch + "<em>" + matchText + "</em>" + afterMatch);
});
};
/* filter products */
$("#search-dinosaurs").on("keyup click input", function() {
if (this.value.length > 0) {
$("#dino-list li").removeClass("match").hide().filter(function() {
return $(this).text().toLowerCase().indexOf($("#search-dinosaurs").val().toLowerCase()) != -1;
}).addClass("match").show();
highlight(this.value);
$("#dino-list").show();
} else {
$("#dino-list, #dino-list li").removeClass("match").hide();
}
});
});
input[type=text] {
width: 200px;
padding: 8px 10px;
}
li em {
background: #ff6;
font-weight: bold;
font-style: normal;
}
<input type="text" id="search-dinosaurs" placeholder="Search for Dinosaurs (start typing)" />
<ul id="dino-list">
<li>Diplo<BR>docus</li>
<li>Stego<FONT COLOR="RED">saurus</FONT>
</li>
<li>Triceratops</li>
<li>Pteradactyl</li>
<li>Tyrannosaurus Rex</li>
<li>Protoceratops</li>
<li>Iguanadon</li>
<li>Velociraptor</li>
</ul>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
In the search box, type: Dipl
You will see the full name, and the <BR> is ignored.
How can I get this code to use the HTML code that is inline with the result?
the result should show:
Diplodocus
Thanks for any thoughts
try this one
$(function(){
$('#dino-list>li').hide();
$('#search-dinosaurs').on('keyup',function(){search(this.value)})
})
function search(txt){
var target = $('#dino-list');
// reset content
var content = target.html();
if (typeof target.data('content')!='undefined') {
target.html(target.data('content'));
} else target.data('content',content);
$('#dino-list>li').hide();
if (txt!='') {
// begin search
$('#dino-list').find('*').contents().each(function() {
if (this.nodeType === 3) {
// wrap text node with 'em'
$(this).replaceWith(this.nodeValue.replace(new RegExp('('+txt+')','gi'),'<em>$1</em>'))
};
});
// display li with em
$('em',target).each(function(){
$(this).closest('li').show();
})
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="text" id="search-dinosaurs" placeholder="Search for Dinosaurs (start typing)" />
<ul id="dino-list">
<li>Diplo<BR>docus</li>
<li>Stego<FONT COLOR="RED">saurus</FONT></li>
<li>Triceratops</li>
<li>Pteradactyl</li>
<li>Tyrannosaurus Rex</li>
<li>Protoceratops</li>
<li>Iguanadon</li>
<li>Velociraptor</li>
</ul>

how determine if object has child of certain element?

I have a very simple function, which I want to work only if selected object has child of certain type - in this case if it has ul nested.
I have tried with this:
var onMouseOver = function() {
if (this.getElementsByTagName('ul') > 0);{
console.log('entered');
}
}
and this:
var onMouseOver = function() {
if (this.querySelector('ul') != null);{
console.log('enter');
}
}
but it doesn't help - function still launches, even when it returnes 'null'.
You should be looking at the length property of those selectors.
var onMouseOver = function() {
if (this.querySelectorAll('ul').length > 0);{
console.log('enter');
}
}
or
var onMouseOver = function() {
if (this.getElementsByTagName('ul').length > 0);{
console.log('entered');
}
}
try this one :)
function ok(obj) {
var l = obj.children.length;
for (var i = 0; i <= l; i++) {
if (obj.children[i].tagName == "UL") {
var c = obj.children[i].children[0];
alert("child id is :-" + c.tagName);
alert("child id is :-" + c.id);
alert("child value is :-" + c.innerHTML);
break;
}
}
}
#child {
display: none;
}
<!DOCTYPE html>
<html>
<body>
<div id="Parent" onmouseover="ok(this)">Find Child ? mouse over me
<p id="child">I'm Child</p>
<ul>
<li id="list">hello</li>
</ul>
</div>
</body>
</html>

using jQuery to append div's and each div has a different ID

So I'm trying to to use jQuery to append a div which will generate a card using the assigned class. The problem is I need to create a different ID each time so I can put random number on the card. I'm sure there's an easier way to do this. So i'm posing two questions. how to make the code where it put the random number on the card go endlessly. and how to append divs with unique ID's. Sorry if my code isn't the best. It's my first project.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<title></title>
<style>
.cardLook {
border: 1px solid black;
width: 120px;
height: 220px;
border-radius: 5px;
float: left;
margin: 20px;
padding: 5px;
background-color: #fff;
}
#card1,#card2,#card3,#card4,#card5 {
transform:rotate(180deg);
}
#cardTable {
background-color: green;
height: 270px
}
.reset {
clear: both;
}
</style>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
</head>
<body>
<button id="deal">Deal</button>
<button id="hit">hit</button>
<button id="stand">Stand</button>
<button id="hi">hi</button>
<div id="number"></div>
<div id="arrayOutput"></div>
<div id="someId"></div>
<div id="out2"></div>
<div id="cardTable">
</div>
<div class="reset"></div>
<script>
var what;
//Services helper functon
document.getElementById('deal').onclick = function deal() {
var score1 = Math.floor(Math.random() *10 + 1);
var score2 = Math.floor(Math.random() *10 + 1);
var firstCard = score1;
var secondCard = score2;
//myNumberArray.push(firstCard, score2);
//card1.innerHTML = myNumberArray[0];
//card2.innerHTML = myNumberArray[1];
$("#deal").click(function(){
$("#cardTable").append("<div class='cardLook' id='card1'></div>");
});
console.log(score2, score1)
}
var myNumberArray = [];
$("#hit").click(function(){
$("#cardTable").append("<div class='cardLook' id="uniqueIdNumberOne"></div>");
if (myNumberArray > 1) {
#cardTable
}
var card = Math.floor(Math.random() * 10) + 1;
document.getElementById('number').innerHTML=card;
myNumberArray.push(card);
var number = myNumberArray.value;
var arrayOutput = document.getElementById('number');
var someId = document.getElementById('someId');
someId.innerHTML = myNumberArray;
card1.innerHTML = myNumberArray[0];
card2.innerHTML = myNumberArray[1];
card3.innerHTML = myNumberArray[2];
card4.innerHTML = myNumberArray[3];
card5.innerHTML = myNumberArray[4];
// console.log("myNumberArray: ", myNumberArray);
what = calcTotal(myNumberArray);
showMe(calcTotal(myNumberArray));
});
//var output = myNumberArray = calcTotal(list);
function calcTotal(myNumberArray) {
var total = 0;
for(var i = 0; i < myNumberArray.length; i++){
total += myNumberArray[i];
}
return total;
}
//document.getElementById('out2').innerHTML = out2;
console.log("myNumberArray: ", myNumberArray);
function showMe(VAL) {
var parent = document.getElementById('out2');
parent.innerHTML = VAL;
if (calcTotal(myNumberArray) > 21) {
alert('you lose');
}
};
document.getElementById('stand').onclick = function stand() {
var compterDeal1 = Math.floor(Math.random() *10 + 1);
var computerCards = compterDeal1;
console.log(computerCards);
computerArray.push(computerCards);
if (computerCards < 21) {
stand();
}
}
var computerArray = [];
</script>
</body>
</html>
Use an unique class with all of then, and call then by class
Add a global integer:
var cardNumber = 0;
A function to generate an id:
function newCardId() {
cardNumber ++;
return 'uniqueCardId' + cardNumber.toString();
}
And use:
var newId = newCardId();
$("#cardTable").append("<div class=\"cardLook\" id=\"" + newId + "\"></div>");
Finally to access your new div:
$('#' + newId).
Note: Escape quotes within a string using backslash!

Need Help In Javascript Text Typer Effect

I have a javascript text typer code:
CSS:
body
{
background-color:black;
}
#writer
{
font-family:Courier;
font-size:12px;
color:#24FF00;
background-color:black;
}
Javascript:
var text = "Help Please, i want help.";
var counter = 0;
var speed = 25;
function type()
{
lastText = document.getElementById("writer").innerHTML;
lastText+=text.charAt(counter);
counter++;
document.getElementById("writer").innerHTML = lastText;
}
setInterval(function(){type()},speed);
HTML:
<div id="writer"></div>
I want to know how can i use <br> tag (skipping a line or moving to another line). I tried many ways but failed, I want that if I Typed My name is Master M1nd. and then i want to go on the other line how would i go?
I've made a jQuery plugin, hope this will make things easier for you. Here is a live demo : http://jsfiddle.net/wared/V7Tv6/. As you can see, jQuery is loaded thanks to the first <script> tag. You can then do the same for the other <script> tags if you like, this is not necessary but considered as a good practice. Just put the code inside each tag into separate files, then set appropriate src attributes in the following order :
<script src=".../jquery.min.js"></script>
<script src=".../jquery.marquee.js"></script>
<script src=".../init.js"></script>
⚠ Only tested with Chrome ⚠
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
jQuery.fn.marquee = function ($) {
function findTextNodes(node) {
var result = [],
i = 0,
child;
while (child = node.childNodes[i++]) {
if (child.nodeType === 3) {
result.push(child);
} else {
result = result.concat(
findTextNodes(child)
);
}
}
return result;
}
function write(node, text, fn) {
var i = 0;
setTimeout(function () {
node.nodeValue += text[i++];
if (i < text.length) {
setTimeout(arguments.callee, 50);
} else {
fn();
}
}, 50);
}
return function (html) {
var fragment, textNodes, text;
fragment = $('<div>' + html + '</div>');
textNodes = findTextNodes(fragment[0]);
text = $.map(textNodes, function (node) {
var text = node.nodeValue;
node.nodeValue = '';
return text;
});
this.each(function () {
var clone = fragment.clone(),
textNodes = findTextNodes(clone[0]),
i = 0;
$(this).append(clone.contents());
(function next(node) {
if (node = textNodes[i]) {
write(node, text[i++], next);
}
})();
});
return this;
};
}(jQuery);
</script>
<script>
jQuery(function init($) {
var html = 'A <i>marquee</i> which handles <u><b>HTML</b></u>,<br/> only tested with Chrome. Replay';
$('p').marquee(html);
$('a').click(function (e) {
e.preventDefault();
$('p').empty();
$('a').off('click');
init($);
});
});
</script>
<p></p>
<p></p>
Instead of passing <br> char by char, you can put a \n and transform it to <br> when you modify the innerHTML.
For example (http://jsfiddle.net/qZ4u9/1/):
function escape(c) {
return (c === '\n') ? '<br>':c;
}
function writer(text, out) {
var current = 0;
return function () {
if (current < text.length) {
out.innerHTML += escape(text.charAt(current++));
}
return current < text.length;
};
}
var typeNext = writer('Hello\nWorld!', document.getElementById('writer'));
function type() {
if (typeNext()) setInterval(type, 500);
}
setInterval(type, 500);
Also probably you'll be interested in exploring requestAnimationFrame (http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/), for your typing animation :)

Categories