Replace values in an array dynamically - javascript

I have a scenario like this. Say: let a = [2,5,6] and let b = [1,2,3,4,5,6,7,8]. Array b is displayed in boxes and revealed when one clicks any of the boxes. What I am trying to do is, when one clicks on any box and the value is the same as any value in array a, I replace the value with other unique values and if they're not the same I display as it is.
e.g. If I click a box that has a value of 2 or 5 or 6 i replace the values with the other values.
A minimal example is:
new Vue({
el: "#app",
data: {
a: [2,5,6],
b: [1,2,3,4,5,6,7,8]
},
methods: {
replaceNumber() {
// function to replace the values
}
}
})
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
.numbers {
display: flex;
}
li {
list-style-type: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<h2>Numbers:</h2>
<br/>
<ul class="numbers">
<li v-for="num in a">
{{num}}
</li>
</ul>
<br/>
<template>
<button #click="replaceNumber" v-for="number in b">
{{ number }}
</button>
</template>
</div>

Use indexOf() to locate the position of the element you want to replace.
Then use splice() together with the index you got to remove that element.
Then use splice() again to insert a new value to the same index.
Check the documentation of each method above to understand their syntax.

You can try with random numbers if found in first array i.e a
var a = [2,5,6]
var b = [1,2,3,4,5,6,7,8]
a.forEach(function(e){
$("#aDiv").append(`<h2>${e}</h2>`);
})
b.forEach(function(e){
$("#bDiv").append(`<h2 class="seconddiv">${e}</h2>`);
});
$(".seconddiv").on('click',function(){
let val= $(this).html();
if(a.includes(parseInt(val))){
var uniqueNo = 0;
do {
uniqueNo=getRandomInt(0,10);
}
while (a.includes(parseInt(uniqueNo)));
$(this).html(uniqueNo);
}
})
let getRandomInt= (x,y)=>x+(y-x+1)*crypto.getRandomValues(new Uint32Array(1))[0]/2**32|0
#aDiv,#bDiv{
color:yellow;
background-color:black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="maindiv">
<div id="aDiv">
</div>
<div id="bDiv" style="margin-top:50px;">
</div>
</div>

Related

jQuery .append() and .remove() skipping behavior with slider function

I'm having trouble with some dynamic HTML. I've got a slider that adds or removes DOM elements as the value changes. Each time it increases, an element is added, and each time it decreases, an element is removed.
Here's the HTML:
<input type="range" min="3" max="16" class="rgb-slider" value="3" tabindex="-1" oninput="slider(this.value)">
<div class="container">
<div class="boxes">
<div class="box"><span></span></div>
<div class="box"><span></span></div>
<div class="box"><span></span></div>
</div>
</div>
Here's the JS:
var colorCount = 3;
function slider(value) {
if (colorCount < parseInt(value)) {
$('.boxes').append('<div class="box"><span></span></div>');
colorCount = value;
} else {
$('.box:last-child').remove();
colorCount = value;
}
}
http://jsfiddle.net/meu9carx/
However, when I quickly move the slider, it seems to skip or trip up, and I end up with more or fewer than I started with. The slider has a range from 3-16, but sometimes the min value goes to more or less than 3. Sometimes, all the boxes vanish.
Is there a smarter way to code this? I'm trying to avoid hard-coding divs here.
If the mouse moves fast, it's possible for the input value to change by more than one (in either direction) during a single input event. Use the value in the input to determine how many squares there should be exactly, rather than adding or removing only a single element each time.
const boxes = $('.boxes');
$('input').on('input', function() {
const targetSquares = Number(this.value);
while (boxes.children().length < targetSquares) {
boxes.append('<div class="box"><span></span></div>');
}
while (boxes.children().length > targetSquares) {
$('.box:last-child').remove();
}
});
body{
background: #777;
font-family: 'Arimo', sans-serif;
}
.container { padding: 20px 0; }
.boxes { display: flex; }
.box {
padding: 10px;
background: #ffffff;
height: 100px;
flex: 1;
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="range" min="3" max="16" class="rgb-slider" value="3" tabindex="-1">
<div class="container">
<div class="boxes">
<div class="box"><span></span></div>
<div class="box"><span></span></div>
<div class="box"><span></span></div>
</div>
</div>

Javascript - Automate duplicating tags from parent div to child div based on class snippet

I would like to automate duplicating a class from a parent div to each separate child span based on a word.
As an example:
parent div contains the following classes: grid-item tag-street-style tag-slender tag-classic tag-navy tag-grey tag-white is-loaded
I would like to duplicate any classes within the parent div with the precursor "tag-" and place them into each separate child span. In this case, the parent div contains the classes with the initial "tag-" word: tag-street-style tag-slender tag-classic tag-navy tag-grey tag-white
Some other parent divs will contain other classes that contain the initial word "tag-"
The "tag-" classes can be different in other parent divs but there will always be 5 "tag-" classes. As an example, a different parent div may contain the following classes with the initial "tag-" word: tag-smart-style tag-casual tag-modern tag-red tag-black tag-green
I already have a code snippet but this is locked in to 5 specific "tag-" classes. Here is the code:
let classMap = {
"tag-street-style": ".colour-tag-1",
"tag-slender": ".colour-tag-2",
"tag-navy": ".colour-tag-3",
"tag-grey": ".colour-tag-4",
"tag-white": ".colour-tag-5",
};
I would like the first "tag-" class identified within the parent div to be duplicated into "colour-tag-1" within the first child span.
Then I would like the second "tag-" class identified within the parent div to be duplicated into "colour-tag-2" within the second child span.
Then I would like the third "tag-" class identified within the parent div to be duplicated into "colour-tag-3" within the third child span.
Then I would like the fourth "tag-" class identified within the parent div to be duplicated into "colour-tag-4" within the fourth child span.
Then I would like the fifth "tag-" class identified within the parent div to be duplicated into "colour-tag-5" within the fifth child span.
$(document).ready( function() {
$(".grid-item .grid-meta-wrapper").each(function(e){
$(this).append('<div class="product-view-item-colour-tags"><span class="product-view-item-colour-tag colour-tag-1">tag1</span><span class="product-view-item-colour-tag colour-tag-2">tag2</span><span class="product-view-item-colour-tag colour-tag-3">tag3</span><span class="product-view-item-colour-tag colour-tag-4">tag4</span><span class="product-view-item-colour-tag colour-tag-5">tag5</span></div>');
});
let classMap = {
"tag-street-style": ".colour-tag-1",
"tag-slender": ".colour-tag-2",
"tag-navy": ".colour-tag-3",
"tag-grey": ".colour-tag-4",
"tag-white": ".colour-tag-5",
};
for (let cls in classMap) {
document.querySelector(classMap[cls]).classList.add(cls);
}
});
<style>
.tag-street-style {
background-color: purple;
}
.tag-slender {
background-color: red;
}
.tag-navy {
background-color: blue;
}
.tag-grey {
background-color: grey;
}
.tag-white {
background-color: black;
color: white;
}
.tag-red {
background-color: black;
color: red;
}
.tag-black {
background-color: white;
color: black;
}
.tag-green {
background-color: black;
color: green;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="grid-item tag-street-style tag-slender tag-classic tag-navy tag-grey tag-white is-loaded">
<section class="grid-meta-wrapper">
<div class="grid-main-meta">
<div class="grid-title"> T-Shirt </div>
<div class="grid-prices">
<div class="product-price">
<span>12.99</span>
</div>
</div>
</div>
<div class="grid-meta-status"></div>
</section>
</div>
<br><br><br>
<div class="grid-item tag-smart-style tag-casual tag-modern tag-red tag-black tag-green is-loaded">
<section class="grid-meta-wrapper">
<div class="grid-main-meta">
<div class="grid-title"> T-Shirt </div>
<div class="grid-prices">
<div class="product-price">
<span>12.99</span>
</div>
</div>
</div>
<div class="grid-meta-status"></div>
</section>
</div>
First, here is a testable solution:
$(document).ready( function() {
$(".grid-item .grid-meta-wrapper").each(function(e){
$(this).append('<div class="product-view-item-colour-tags"><span class="product-view-item-colour-tag colour-tag-1">tag1</span><span class="product-view-item-colour-tag colour-tag-2">tag2</span><span class="product-view-item-colour-tag colour-tag-3">tag3</span><span class="product-view-item-colour-tag colour-tag-4">tag4</span><span class="product-view-item-colour-tag colour-tag-5">tag5</span></div>');
});
let classes = [...document.getElementById("tag-specifier").classList].filter(item => item.indexOf("tag-") === 0);
for (let index = 0; index < classes.length; index++) {
let currentItem = document.querySelector(".colour-tag-" + (index + 1));
if (currentItem !== null) {
currentItem.classList.add(classes[index]);
}
}
});
.tag-street-style {
background-color: purple;
}
.tag-slender {
background-color: red;
}
.tag-navy {
background-color: blue;
}
.tag-grey {
background-color: grey;
}
.tag-white {
background-color: black;
color: white;
}
.tag-red {
background-color: black;
color: red;
}
.tag-black {
background-color: white;
color: black;
}
.tag-green {
background-color: black;
color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tag-specifier" class="grid-item tag-street-style tag-slender tag-classic tag-navy tag-grey tag-white is-loaded">
<section class="grid-meta-wrapper">
<div class="grid-main-meta">
<div class="grid-title"> T-Shirt </div>
<div class="grid-prices">
<div class="product-price">
<span>12.99</span>
</div>
</div>
</div>
<div class="grid-meta-status"></div>
</section>
</div>
Now, let's understand it:
I have added the id of tag-specifier to the element which has the classes, so the code will have an easy time finding the classes to work with
document.getElementById("tag-specifier").classList is returning an object of key-value pairs where the keys are indexes (starting from 0) and the values are class names
I convert the result of classList into an array via [...document.getElementById("tag-specifier").classList] because I intend to use the filter() function of the array, alternatively I could have written a loop with similar effect
.filter() is being called for the newly converted array. This function takes a callback (more on that below) that determines which items we are interested about from the array and returns an array that contains only the items that the callback found interesting
a callback is a function that is scheduled to be executed at some future point of time
in our case, the callback of .filter() is a function which will be executed for each elements of the array and will evaluate them whether they are interesting
our callback is item => item.indexOf("tag-") === 0, which is a function (we use the arrow operator => to differentiate the parameter, which is item and the actual function body, which is item.indexOf("tag-") === 0), that is, we are only interested about items whose name starts with tag-
after the call for .filter(), the value assigned to classes is an array of class names that only holds valuable class names from our perspective, that is, class names starting with tag-
we loop classes using a variable we create for this purpose, named index
we search for the element that corresponds to the selector of ".colour-tag-" + (index + 1). The reason for the index + 1 is that Javascript arrays are 0-indexed and your tag indexes start from 1
note that (index + 1) is enclosed into parantheses. The reason for this is that + is an operator that acts both as concatenator and numeric addition and evaluates from left-to-right, that is, without the paranthesis around (index + 1) the result of ".colour-tag-" + index + 1 would be looking like .colour-tag-01 instead of .colour-tag-2
we check whether currentItem exists, so we program defensively, so, if any anomaly occurs, we intend our code to handle it gracefully
if currentItem existed, then we add the current class, which is classes[index]
EDIT
The initial solution I have implemented was assuming that we deal with a single such case, while your problem included multiple similar cases on the same page. To solve this issue, I have added an extra layer to the solution, querying the roots of all relevant subtrees in HTML and using them as the context of their respective problem-spaces.
Here is a snippet that illustrates it (yes, the first 3 tags will be unstyled, but this is not due to the logic of the code, but it is rather due to the styling specification of the structure):
$(document).ready( function() {
$(".grid-item .grid-meta-wrapper").each(function(e){
$(this).append('<div class="product-view-item-colour-tags"><span class="product-view-item-colour-tag colour-tag-1">tag1</span><span class="product-view-item-colour-tag colour-tag-2">tag2</span><span class="product-view-item-colour-tag colour-tag-3">tag3</span><span class="product-view-item-colour-tag colour-tag-4">tag4</span><span class="product-view-item-colour-tag colour-tag-5">tag5</span><span class="product-view-item-colour-tag colour-tag-6">tag6</span></div>');
});
for (let context of $(".list-grid .grid-item")) {
let idDeclaration = context.id;
let classes = [...context.classList].filter(item => item.indexOf("tag-") === 0);
for (let index = 0; index < classes.length; index++) {
let currentItem = context.querySelector(".colour-tag-" + (index + 1));
if (currentItem !== null) {
currentItem.classList.add(classes[index]);
}
}
}
});
.product-view-item-colour-tags .tag-navy {
background-color: blue;
}
.product-view-item-colour-tags .tag-grey {
background-color: grey;
}
.product-view-item-colour-tags .tag-white {
background-color: black;
color: white;
}
.product-view-item-colour-tags .tag-red {
color: red;
}
.product-view-item-colour-tags .tag-black {
background-color: white;
color: black;
}
.product-view-item-colour-tags .tag-green {
color: green;
}
.product-view-item-colour-tags .tag-yellow {
background-color: black;
color: yellow;
}
.product-view-item-colour-tags .tag-orange {
color: orange;
}
.product-view-item-colour-tags .tag-pink {
color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list-grid">
<div id="thumb-product-3-9" class="grid-item tag-street-style tag-slender tag-classic tag-navy tag-grey tag-white is-loaded">
<section class="grid-meta-wrapper">
<div class="grid-main-meta">
<div class="grid-title"> T-Shirt 1</div>
<div class="grid-prices">
<div class="product-price">
<span>9.99</span>
</div>
</div>
</div>
<div class="grid-meta-status"></div>
</section>
</div>
<br>
<div id="thumb-product-3-12" class="grid-item tag-social-style tag-thicker tag-premium tag-green tag-black tag-red is-loaded">
<section class="grid-meta-wrapper">
<div class="grid-main-meta">
<div class="grid-title"> T-Shirt 2</div>
<div class="grid-prices">
<div class="product-price">
<span>12.99</span>
</div>
</div>
</div>
<div class="grid-meta-status"></div>
</section>
</div>
<br>
<div id="thumb-product-3-1" class="grid-item tag-outdoor-style tag-warmer tag-premium tag-pink tag-white tag-orange is-loaded">
<section class="grid-meta-wrapper">
<div class="grid-main-meta">
<div class="grid-title"> T-Shirt 3</div>
<div class="grid-prices">
<div class="product-price">
<span>14.99</span>
</div>
</div>
</div>
<div class="grid-meta-status"></div>
</section>
</div>
<br>
<div id="thumb-product-3-4" class="grid-item tag-street-style tag-slender tag-casual tag-green tag-yellow tag-red is-loaded">
<section class="grid-meta-wrapper">
<div class="grid-main-meta">
<div class="grid-title"> T-Shirt 4</div>
<div class="grid-prices">
<div class="product-price">
<span>15.99</span>
</div>
</div>
</div>
<div class="grid-meta-status"></div>
</section>
</div>
</div>

VanillaJS - find middle element in the container

So I have a setup like this
<div class=“container”>
<div class=“segment segment1”></div>
<div class=“segment segment2”></div>
<div class=“segment segment3”></div>
.
.
.
<div class=“segmentN”></div>
</div>
Where N is an number defined by user so list is dynamical. For container I have applied styles to display it as grid, so EVERY time list has 3 items displayed, list is scrollable. My problem is, how can I via VanillaJS find element which is in the middle of container ? If there are 3 elements in the page, it should select 2nd one, when scrolling down it should select element which is in the middle of container every time to apply some styles to it in addition to grab it’s id. If there are 2 elements, it should select 2nd item as well. I was thinking about checking height of container, divide it by half and checking position of element if it’s in range. So far I was able to write this code in js
function findMiddleSegment() {
//selecting container
const segmentListContainer = document.querySelector(`.container`);
const rect = segmentListContainer.getBoundingClientRect();
//selecting all divs
const segments = document.querySelectorAll(`.segment`);
segments.forEach( (segment) => {
const location = segment.getBoundingClientRect();
if( (location.top >= rect.height / 2) ){
segment.classList.add(`midsegment`);
} else {
segment.classList.remove(`midsegment`);
}
});
}
But it doesn’t work. It finds element in the middle as should, but also applies style for every other element beneath middle segment. I’ve read some answers on stackoverflow, but couldn’t find any idea how to solve my problem.
EDIT
In addition to my problem I add additional function to show how I invoke it.
function handleDOMChange() {
findMiddleSegment(); //for "first run" when doc is loaded
const segmentListContainer = document.querySelector(`.container`);
segmentListContainer.addEventListener('scroll', findMiddleSegment);
}
A very easy way to do it is using the Intersection Observer:
const list = document.querySelector('ul'),
idDisplay = document.querySelector('p b');
const observer = new IntersectionObserver(
highlightMid,
{
root: list,
rootMargin: "-33.33% 0%",
threshold: .5
}
);
function makeList() {
list.innerHTML = '';
observer.disconnect();
const N = document.querySelector('input').value;
for (let i = 0; i < N;) {
const item = document.createElement('li');
item.id = `i_${++i}`;
item.textContent = `Item #${i}`;
list.append(item);
observer.observe(item);
}
};
function highlightMid(entries) {
entries.forEach(entry => {
entry.target.classList
.toggle('active', entry.isIntersecting);
})
const active = list.querySelector('.active');
if (active) idDisplay.textContent = '#' + active.id;
}
ul {
width: 50vw;
height: 50vh;
margin: auto;
padding: 0;
overflow-y: auto;
border: solid 1px;
}
li {
box-sizing: border-box;
height: 33.33%;
padding: .3em 1em;
list-style: none;
transition: .3s;
}
.active {
background: #6af;
}
<i>Make a list of:</i>
<input type="number" min="2" placeholder="number of items">
<button onclick="makeList()">make</button>
<p>Active id is <b>yet to set</b></p>
<ul></ul>
If container has only a list of segments inside, it's easer to count the element's children and find the mid element.
const segmentListContainer = document.querySelector(`.segmentListContainer`);
const midSegmentIndex = Math.floor(segmentListContainer.children.length / 2) - 1;
let midSegment = segmentListContaner.children[midSegmentIndex];
midSegment.classList.add('midsegment');
P.S.
The reason why your code adds 'mdsegment' to each element's class name after the real midsegment element is because of this conditional statement line you wrote.
if(location.top >= rect.height / 2){
segment.classList.add(`midsegment`);
}
Something like this. You can use Math.round, Math.ceil or Math.floor like I did. This works because querySelectorAll returns an array and you can use array.length to count the total number of items in the array then use a for loop to loop over all the segments and place the class based on the Math.(round, floor or ceil) based on your needs.
const container = document.querySelector(".container");
const segments = container.querySelectorAll(".segment");
const middleSegment = Math.floor(segments.length / 2);
for (let index = 0; index < segments.length; index++) {
segments[middleSegment].classList.add("middle-segment");
}
.middle-segment{
background-color: red;
}
<div class="container">
<div class="segment">segment</div>
<div class="segment">segment</div>
<div class="segment">segment</div>
<div class="segment">segment</div>
<div class="segment">segment</div>
<div class="segment">segment</div>
<div class="segment">segment</div>
</div>
You don't need javascript for this. CSS will do
.container {
width: 350px;
}
.container .segment {
width: 100px;
height: 100px;
float: left;
background-color: #EEE;
border: 1px dotted gray;
margin: 3px;
text-align: center;
color: silver;
}
.segment:nth-child(3n-1) {
background-color: aquamarine;
color: black;
}
<div class="container">
<div class="segment">segment</div>
<div class="segment">segment</div>
<div class="segment">segment</div>
<div class="segment">segment</div>
<div class="segment">segment</div>
<div class="segment">segment</div>
<div class="segment">segment</div>
<div class="segment">segment</div>
<div class="segment">segment</div>
<div class="segment">segment</div>
<div class="segment">segment</div>
<div class="segment">segment</div>
<div class="segment">segment</div>
<div class="segment">segment</div>
</div>

Using template strings to append HTML

New to es6, is there a way to append HTML using template literals `` in the DOM without overwriting what was currently posted?
I have a huge block of HTML that I need to post for a list that is being created. Where a user is able to post their input.
Every-time the task is submitted it overwrites the current submission. I need it to append underneath.
fiddle for demonstration purpose.
https://jsfiddle.net/uw1o5hyr/5/
<div class = main-content>
<form class ='new-items-create'>
<label>Name:</label><input placeholder=" A Name" id="name">
<button class = "subBtn">Submit</button>
</form>
</div>
<span class="new-name"></span>
JavaScript
form.addEventListener('submit',addItem);
function addItem(event){
event.preventDefault();
let htmlStuff =
`
<div class="main">
<div class="a name">
<span>${name.value}</span>
</div>
<div>
`
itemCreated.innerHTML = htmlStuff;
}
insertAdjacentHTML() adds htmlString in 4 positions see demo. Unlike .innerHTML it never rerenders and destroys the original HTML and references. The only thing .innerHTML does that insertAdjacentHTML() can't is to read HTML. Note: assignment by .innerHTML always destroys everything even when using += operator. See this post
const sec = document.querySelector('section');
sec.insertAdjacentHTML('beforebegin', `<div class='front-element'>Front of Element</div>`)
sec.insertAdjacentHTML('afterbegin', `<div class='before-content'>Before Content</div>`)
sec.insertAdjacentHTML('beforeend', `<div class='after-content'>After Content</div>`)
sec.insertAdjacentHTML('afterend', `<div class='behind-element'>Behind Element</div>`)
* {
outline: 1px solid #000;
}
section {
margin: 20px;
font-size: 1.5rem;
text-align: center;
}
div {
outline-width: 3px;
outline-style: dashed;
height: 50px;
font-size: 1rem;
text-align: center;
}
.front-element {
outline-color: gold;
}
.before-content {
outline-color: blue;
}
.after-content {
outline-color: green;
}
.behind-element {
outline-color: red;
}
<section>CONTENT OF SECTION</section>
You can just use += to append:
document.getElementById('div').innerHTML += 'World';
<div id="div">
Hello
</div>
Element.prototype.appendTemplate = function (html) {
this.insertAdjacentHTML('beforeend', html);
return this.lastChild;
};
If you create the element prototype as per above, you can get the element back as reference so you can continue modifying it:
for (var sectionData of data) {
var section = target.appendTemplate(`<div><h2>${sectionData.hdr}</h2></div>`);
for (var query of sectionData.qs) {
section.appendTemplate(`<div>${query.q}</div>`);
}
}
Depending on how much you're doing, maybe you'd be better off with a templating engine, but this could get you pretty far without the weight.

Filter elements in DOM based on data-attr with jQuery

I'm trying to filter these items with jQuery autocomplete according to their data-name, but I got stuck with it a bit. Generally, I want to start typing the text in the input field and remove items from DOM if they don't match. Any help is much appreciated.
Pen: https://codepen.io/anon/pen/aVGjay
$(function() {
var item = $(".item");
$.each(item, function(index, value) {
console.log($(value).attr("data-name"));
var everyItem = $(value).attr("data-name");
});
$("#my-input").autocomplete({
source: everyItem, //?
minLength: 1,
search: function(oEvent, oUi) {
// get current input value
var sValue = $(oEvent.target).val();
// init new search array
var aSearch = [];
// for each element in the main array
$(everyItem).each(function(iIndex, sElement) {
// if element starts with input value
if (sElement.substr(0, sValue.length) === sValue) {
// add element
aSearch.push(sElement);
}
});
// change search array
$(this).autocomplete("option", "source", aSearch);
}
});
});
.items {
width: 200px;
}
.item {
background-color: red;
margin-top: 2px;
}
<input type="text" placeholder="Filter items" id="my-input">
<div class="items">
<div class="item" data-name="one">one</div>
<div class="item" data-name="two">two</div>
<div class="item" data-name="three">three</div>
<div class="item" data-name="four">four</div>
</div>
It's a little odd to use autocomplete for this, as that's intended to build a filtered option list from a provided object or remote data source, not from DOM content.
You can build the functionality yourself by attaching an input event listener to the #my-input which in turn goes through the .item elements and uses a regular expression to filter ones with matching data-name attributes and displays them, something like this:
$(function() {
var $items = $(".item");
$('#my-input').on('input', function() {
var val = this.value;
$items.hide().filter(function() {
return new RegExp('^' + val, 'gi').test($(this).data('name'));
}).show();
});
});
.items {
width: 200px;
}
.item {
background-color: red;
margin-top: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="Filter items" id="my-input">
<div class="items">
<div class="item" data-name="one">one</div>
<div class="item" data-name="two">two</div>
<div class="item" data-name="three">three</div>
<div class="item" data-name="four">four</div>
</div>

Categories