Displaying multiple objects one at a time in a dialog box - javascript

I am completely stuck. I am trying to display objects individually in a pop-up dialog box, and I can't find any information as to how to do this. I can display them all at once, but that is not what I am trying to do.
$.each(needs, function(i, v) {
console.info(v);
var brand = v.brand;
console.info(brand);
var model = v.model;
var growerID = v.growerID;
if (v.portalID === null) {
var unmatched = {
brand: v.brand,
model: v.model,
growerID: v.growerID
}
newmatch.push(unmatched);
console.info(newmatch);
} else {
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<form>
<div class="fleft">
<div>
<img src="/app/public/css/images/logo.png">
</div>
<div class="form-group brand ui-corner-all">
<label for="owner">Brand</label>
<div class="card-type ui-corner-all " id="brand"></div>
</div>
<div class="form-group ui-corner-all">
<label for="model">Model</label>
<div class="model ui-corner-all " id="trxio_model"></div>
</div>
<div class="form-group growerId">
<label for="growerId">Grower ID</label>
<div class="card-type ui-corner-all " id="growerId"></div>
</div>
<div class="form-group vendor ui-corner-all ">
<label for="owner">Default Vendor</label>
<div class="card-type ui-corner-all " id="vendor"></div>
</div>
<button type="submit" class="btn btn-lg">Update Product Info</button>
</div>
</form>
</div>
Any help would be appreciated. Thanks.

Because you provided only a partial code that doesn't really work I've written a little example how to iterate over a collection of cars and how to render them into HTML container. Hopefully that will lead you to the solution:
var cars = [
{
name: "VW",
year: 1988,
},
{
name: "Honda",
year: 1999,
},
{
name: "BMW",
year: 2005,
}
]
const container = document.querySelector('#container')
const toRender = cars.map(car => `<div class="car"><span class="name">${car.name}</span> <span class="year">${car.year}</span></div>`)
container.innerHTML = toRender.join('')
.container {
padding: 10;
background: #f0f0f0;
}
.car {
margin: 10px 0;
}
.name {
display: inline-block;
padding: 5px;
color: #ff0000;
min-width: 100px;
}
.year {
color: blue;
}
<div id="container"></div>

Related

Target every label elements that has the correct data-answer attributs with javascript

I have a HTML code and I want to select each label that has the data-anwser set to "correct", how can I do it with pure Javascript? Here's my HTML
<div class="form-group answer" role="group">
<label data-answer="correct">
<div>Test</div>
</label>
</div>
<div class="form-group answer" role="group">
<label data-answer="incorrect">
<div>Test</div>
</label>
</div>
And here's the begining of what I tried with the JS
<script>
var div = document.getElementsByClassName('answer');
window.onload = (event) => {
for (var i = 0; i < div.length; i++) {
var label = div[i].getElementsByTagName('label');
if (label[i].dataset == 'correct') {
console.log("CORRECTE");
} else {
console.log("INCORECTE");
}
console.log(label[i].dataset);
}
}
</script>
Thank you:)
use query selectors:
const btn = document.getElementById('btn');
btn.addEventListener('click', ev => {
const correctAnswers = document.querySelectorAll('.answer [data-answer="correct"]');
correctAnswers.forEach(el => {
el.classList.toggle('selected');
});
});
.form-group > label {
margin: 0.33em;
padding: 0.33em;
border: 2px solid gray;
background-color: silver;
width: 250px;
display: inline-block;
}
.form-group > label.selected {
background-color: yellow;
border: 2px dotted black;
}
<div class="form-group answer" role="group">
<label data-answer="correct">
<div>Test 1</div>
</label>
</div>
<div class="form-group answer" role="group">
<label data-answer="incorrect">
<div>Test 2</div>
</label>
</div>
<div class="form-group answer" role="group">
<label data-answer="correct">
<div>Test 3</div>
</label>
</div>
<button id="btn">highlight correct answers</button>
Try this
var answersCorrect = document.querySelectorAll("*[data-answer='correct']")
Array.from(answersCorrect).forEach(element => {
console.log(element)
})

update row striping after removing element

I am making a todo-list. And I added row striping on it, which worked.
Now when I delete a task it should update the row striping, which it does not. After deleting an element instead of being eg. white white beige it should update to white beige white.
I have a tried a lot of things but I couldn't get anything to work. To be fair I am new to all of this and not quite experienced in working with row striping.
Is there even a way to do it?
Here is what I have so far:
loadEvents();
function loadEvents() {
document.querySelector('form').addEventListener('submit', submit);
document.querySelector('ul').addEventListener('click', deleteOrTick);
}
function submit(a) {
a.preventDefault();
let input = document.querySelector('input');
if (input.value != '')
addTask(input.value);
input.value = '';
}
function addTask(task) {
let ul = document.querySelector('ul');
let li = document.createElement('li');
li.innerHTML = `<div class="input-group mb-3 row"><div class="col-11"><label>${task}</label></div>
<span class="delete">x</span></div>`;
ul.appendChild(li);
document.querySelector('.allToDos').style.display = 'block';
}
function deleteOrTick(a) {
if (a.target.className == 'delete')
deleteTask(a);
}
function deleteTask(a) {
let remove = a.target.parentNode;
let parentNode = remove.parentNode;
parentNode.removeChild(remove);
event.stopPropagation();
}
ul {
list-style-type: none;
}
li {
font-size: 1.3em;
color: #2f4f4f;
}
.todo li:nth-child(2n) {
background: #e0d9c3;
}
.todo {
width: 500px;
}
.delete {
cursor: pointer;
}
<div class="container">
<form action="index.html" method="post">
<div class="heading">
<h1 class="header">ToDo-List</h1>
<p class="intro">Do what you do</p>
</div>
<div class="input-group mb-3">
<input type="text" class="form-control" name="task" placeholder="Add a todo" aria-describedby="basic-addon2">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="submit">Add</button>
</div>
</div>
</form>
</div>
<div class="container">
<div class="allToDos ">
<ul class="todo">
<li>
<div class="input-group mb-3 row">
<div class="col-11">
<label>hi was geht ab</label>
</div>
<span class="delete">x</span>
</div>
</li>
</ul>
</div>
</div>
deleteTask can be
function deleteTask(event) {
let remove = event.target.parentNode;
let parentNode = remove.parentNode;
remove.parentNode.remove();
event.stopPropagation();
}
document.querySelector('li').addEventListener('click',deleteOrTick); // not ul
function deleteTask(a){
let remove = a.currentTarget;
let parentNode = remove.parentNode;
parentNode.removeChild(remove);
a.stopPropagation(); //not event
}

jQuery search using data attributes

I'm trying to search for items using the data-find attribute but my function is just matching the input string with any text inside of the container.
You can see this by adding words to the HTML and then entering the input.
How do I get my function to match what's in the data-find attribute?
$(document).ready(function() {
$("#search-text").keyup(function() {
var n = $("#search-text").val(),
t = ($(".item").attr("[data-find]"),
n.replace(/ /g, "'):finditem('"));
$.extend($.expr[":"], {
finditem: function(n, t, e, i) {
return (
(n.textContent || n.inText || "")
.toLowerCase()
.indexOf((e[3] || "").toLowerCase()) >= 0
);
}
}),
$("#subcat-list div")
.not(":finditem('" + t + "')")
.each(function(n) {
$(this).removeClass("subcat-item");
}),
$("#subcat-list div:finditem('" + t + "')").each(function(n) {
$(this).addClass("subcat-item");
});
});
});
#subcat-list {
display: flex;
}
.subcat-item {
height: 50px;
width: 50px;
}
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="search-text" placeholder="search">
<div id="subcat-list">
<div class="subcat-item" style="background:red">
<div class="item" data-find="red"></div>
</div>
<div class="subcat-item blue" style="background:blue">
<div class="item" data-find="blue"></div>
</div>
<div class="subcat-item green" style="background:green">
<div class="item" data-find="green"></div>
</div>
</div>
Use each, toggleClass and includes
$(document).ready(function() {
$("#search-text").keyup(function() {
var n = $("#search-text").val().toLowerCase(); //convert value to lowercase for case-insensitive comparison
$(".item").each( function(){
var $this = $(this);
var value = $this.attr( "data-find" ).toLowerCase(); //convert attribute value to lowercase
$this.parent().toggleClass( "hidden", !value.includes( n ) );
})
});
});
Demo
$(document).ready(function() {
$("#search-text").keyup(function() {
var n = $("#search-text").val();
$(".item").each( function(){
var $this = $(this);
var value = $this.attr( "data-find" ).toLowerCase();
$this.parent().toggleClass( "hidden", !value.includes( n ) );
})
});
});
#subcat-list {
display: flex;
}
.subcat-item {
height: 50px;
width: 50px;
}
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="search-text" placeholder="search">
<div id="subcat-list">
<div class="subcat-item" style="background:red">
<div class="item" data-find="red"></div>
</div>
<div class="subcat-item blue" style="background:blue">
<div class="item" data-find="blue"></div>
</div>
<div class="subcat-item green" style="background:green">
<div class="item" data-find="green"></div>
</div>
</div>
You can use filter to show and hide the divs depending on the data
using .includes you can check weather a data-find contains the characters of the value if the textbox
$(function() {
$("#search-text").keyup(function() {
var n = $(this).val(); /* Get the value of the textbox */
$(".subcat-item").show(); /* Show all .subcat-item */
$(".item").filter(function() { /* Filter all .item and hide*/
return !$(this).data('find').includes(n);
}).parent().hide();
});
});
#subcat-list {
display: flex;
}
.subcat-item {
height: 50px;
width: 50px;
}
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="search-text" placeholder="search">
<div id="subcat-list">
<div class="subcat-item" style="background:red">
<div class="item" data-find="red"></div>
</div>
<div class="subcat-item blue" style="background:blue">
<div class="item" data-find="blue"></div>
</div>
<div class="subcat-item green" style="background:green">
<div class="item" data-find="green"></div>
</div>
</div>
use a simple attribute selector:
$(".item[data-find*='" + n + "']")
will search for .item whose data-find contains the value of n.

Count each individual vowel in string upon click

Writing some js for an html file where i input a sentence (string). and when i click a button, it outputs the amount of each individual vowel, excluding y and not paying attention to punctuation. I cannot use var so i am trying to make this work using let. I believe i'm on the right path here,starting with the vowel a, yet if the sentence doesn't contain an a i get an error. I can't think of what to do next. Any thoughts?
'use strict';
let vButton = document.querySelectorAll('#vowels');
vButton.forEach(function(blip) {
blip.addEventListener('click', function(evt) {
evt.preventDefault();
console.log('click');
let vowelString = document.getElementById('roboInput'),
sentence = vowelString.value;
if (sentence !== '') {
let aMatches = sentence.match(/a/gi).length;
alert("a - " + aMatches);
}
vowelString.value = '';
});
});
a {
cursor: pointer;
}
.well-robot {
min-height: 340px;
}
.input-robot {
width: 100%;
min-height: 100px;
}
.output-robot {
border: 1px solid #000000;
min-height: 150px;
margin-top: 10px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
<div class="container">
<div class="alert alert-info">
Hello! I'm a smart robot. I can do many interesting things. Type something below and click a button to watch me work!
</div>
<div class="row">
<div class="col-sm-4">
<img src="./robot.gif">
</div>
<div class="col-sm-8 well well-robot">
<textarea id="roboInput" placeholder="Input something here!" class="input-robot"></textarea>
<div class="btn-group btn-group-justified">
<a class="btn btn-default" id="vowels">Count Vowels</a>
<a class="btn btn-default" id="anagrams">Count Anagrams</a>
<a class="btn btn-default" id="distance">Word Distance</a>
</div>
<div id="robotResult" class="output-robot">
</div>
</div>
</div>
</div>
When there's no match for the regular expression, .match() returns null, not an empty array, so you can't get the length. You need to check for that.
let matches = sentence.match(/a/gi);
let matchLength = matches ? matches.length : 0;
alert('a - ' + matchLength);
If I understand your question correctly, you may want something like this:
'use strict';
let vButton = document.querySelectorAll('#vowels');
vButton.forEach(function(blip) {
blip.addEventListener('click', function(evt) {
evt.preventDefault();
//console.log('click');
let vowelString = document.getElementById('roboInput'),
sentence = vowelString.value;
if (sentence) {
let result = {a: 0, e: 0, i: 0, o: 0, u: 0 };
for(var i = 0, l = sentence.length; i < l; i++) {
if(result.hasOwnProperty(sentence[i]))
result[sentence[i]]++;
}
console.log(result);
}
vowelString.value = '';
});
});
a {
cursor: pointer;
}
.well-robot {
min-height: 340px;
}
.input-robot {
width: 100%;
min-height: 100px;
}
.output-robot {
border: 1px solid #000000;
min-height: 150px;
margin-top: 10px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
<div class="container">
<div class="alert alert-info">
Hello! I'm a smart robot. I can do many interesting things. Type something below and click a button to watch me work!
</div>
<div class="row">
<div class="col-sm-4">
<img src="./robot.gif">
</div>
<div class="col-sm-8 well well-robot">
<textarea id="roboInput" placeholder="Input something here!" class="input-robot"></textarea>
<div class="btn-group btn-group-justified">
<a class="btn btn-default" id="vowels">Count Vowels</a>
<a class="btn btn-default" id="anagrams">Count Anagrams</a>
<a class="btn btn-default" id="distance">Word Distance</a>
</div>
<div id="robotResult" class="output-robot">
</div>
</div>
</div>
</div>

Get highest values from objects created with map

I have dynamically added divs with nested divs to the dom. These have data-attributes:
data-name-nr, data-model, data-price.
What I want is to take the highest value of "data-price" to an array from each of all "data-div". In my example there is two nested divs inside the last
More explanation: In my example I have three div with class "frame" = I need an array with three values. In reality there night be whatever between 1 and 10 or even more.
So the outcome of my example would be
let array = [100,150,200]
or
let object = {1:100,2:150,3:200} //from the name-nr
So far I only managed to map the data-items
I tried with map.get and other, they all gave me errors and I don't know which direction I should go. Please can you help?
Example:
HTML
<div class="flex">
<div class="frame" data-name-nr="1">
<div class="border" data-name-nr="1" data-price="100" data-div="1/1"></div>
</div>
<div class="frame" data-name-nr="2">
<div class="border" data-name-nr="2" data-price="150" data-div="1/1"></div>
</div>
<div class="frame" data-name-nr="3">
<div class="border fifty" data-name-nr="3" data-price="100" data-div="1/2"></div>
<div class="border fifty" data-name-nr="3" data-price="200" data-div="2/2"></div>
</div>
</div>
JS
function functionName() {
jQuery( ".frame .box" ).map(function() {
const key = ['name','model','price']
let values = [[jQuery(this).data("name-nr"),( jQuery(this).data('div')),( jQuery(this).data('price'))]]
let result = values.map(row =>
row.reduce((acc, cur, i) =>
(acc[key[i]] = cur, acc), {}))
console.log(result[0])
})
}
$(document).on('click', '.click', functionName)
Console
Object { name: 1, model: "1/1", price: 100 }
Object { name: 2, model: "1/1", price: 150 }
Object { name: 3, model: "1/2", price: 100 }
Object { name: 3, model: "2/2", price: 200 }
https://jsfiddle.net/mik_a/a6jt7kb0/
Create a hash table by reducing to a hash with unique names with the largest price and then take them out to the array as required.
See demo below:
function functionName() {
let hash = jQuery(".frame .box").map(function() {
return {
name: jQuery(this).data("name-nr"),
model: jQuery(this).data('div'),
price: jQuery(this).data('price')
};
}).get().reduce(function(p,c){
if((p[c.name] && p[c.name].price < c.price) || !p[c.name])
p[c.name] = c
return p;
},Object.create(null));
let result = Object.keys(hash).map(function(e) {
return hash[e];
});
console.log(result);
}
$(document).on('click', '.click', functionName)
.flex {
display: flex;
align-items: center;
justify-content: center;
width: 400px;
height: 300px;
}
.frame {
outline: 1px solid red;
flex: 1;
display: flex;
flex-direction: column;
height: 100%;
}
.box {
border-top: 1px solid green;
}
.fifty {
height: 50%;
}
button {
width: 100px;
height: 35px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="flex">
<div class="frame" data-name-nr="1">
<div class="box" data-name-nr="1" data-price="100" data-div="1/1"></div>
</div>
<div class="frame" data-name-nr="2">
<div class="box" data-name-nr="2" data-price="150" data-div="1/1"></div>
</div>
<div class="frame" data-name-nr="3">
<div class="box fifty" data-name-nr="3" data-price="100" data-div="1/2"></div>
<div class="box fifty" data-name-nr="3" data-price="200" data-div="2/2"></div>
</div>
</div>
<button class="click" value="CLICK">
click
</button>
and the ES6 version:
function functionName() {
let hash = jQuery(".frame .box").map(function() {
return {
name: jQuery(this).data("name-nr"),
model: jQuery(this).data('div'),
price: jQuery(this).data('price')
};
}).get().reduce((p, c) => {
if ((p[c.name] && p[c.name].price < c.price) || !p[c.name])
p[c.name] = c;
return p;
}, Object.create(null));
let result = Object.keys(hash).map(e => hash[e]);
let sum = Object.keys(hash).map(e => hash[e].price).reduce((p,c) => p + c, 0);
console.log(result, sum);
}
$(document).on('click', '.click', functionName)
.flex{display:flex;align-items:center;justify-content:center;width:400px;height:300px}.frame{outline:1px solid red;flex:1;display:flex;flex-direction:column;height:100%}.box{border-top:1px solid green}.fifty{height:50%}button{width:100px;height:35px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="flex">
<div class="frame" data-name-nr="1">
<div class="box" data-name-nr="1" data-price="100" data-div="1/1"></div>
</div>
<div class="frame" data-name-nr="2">
<div class="box" data-name-nr="2" data-price="150" data-div="1/1"></div>
</div>
<div class="frame" data-name-nr="3">
<div class="box fifty" data-name-nr="3" data-price="100" data-div="1/2"></div>
<div class="box fifty" data-name-nr="3" data-price="200" data-div="2/2"></div>
</div>
</div>
<button class="click" value="CLICK">
click
</button>
You could select the frame and then reduce on the inside boxes:
$('.frame').map(function() {
const biggerBox = $(this).find('.box').toArray().reduce((bigger, current) =>
$(bigger).data('price') > $(current).data('price') ? bigger : current)
const data = $(biggerBox).data()
console.log({ name: data.nameNr, price: data.price, div: data.div })
})
using a fork from your fiddle: https://jsfiddle.net/zmq5jdh5/

Categories

Resources