Array: Put multple objects in array - javascript

i am having a function like below
var resultObject = {
testResult: $('.test').map(function() {
return {name: $(this).text(), no:'1'};
}).get()
};
console.log(resultObject);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">test1</div>
<div class="test">test2</div>
<div class="test">test3</div>
<div class="test2">1</div>
<div class="test2">2</div>
<div class="test2">3</div>http://stackoverflow.com/questions/ask#
The field "no" should be according to the class="test2"but it doesn't seem like i can do something like .map() in .map()
Big Updated!!
I see there are so many answer below and most of them can solve the issues and I just figured out a way to fix my problem too.
Please let me share it and see if there's anything else i shall improve.
var test1= "";
$(".test" ).each(function( index ) {
test1 = $(this).text();
});
var test2= $('.test2').map(function() {
return {name: $(this).text(), no:test1};
}).get()
var sovCategories = test2;

You don't need a second loop. You can use .eq() to select the element by the same index.
var resultObject = {
testResult: $('.test').map(function(i) {
return {
name: $(this).text(),
no: $('.test2').eq(i).text(),
};
}).get()
};
console.log(resultObject);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">test1</div>
<div class="test">test2</div>
<div class="test">test3</div>
<div class="test2">1</div>
<div class="test2">2</div>
<div class="test2">3</div>
And just because I had fun, a bit shorter version as arrow function too! ;)
var resultObject = {
testResult: $('.test').map((i, e) => ({
name: $(e).text(),
no: $('.test2').eq(i).text()
})).get()
};
console.log(resultObject);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">test1</div>
<div class="test">test2</div>
<div class="test">test3</div>
<div class="test2">1</div>
<div class="test2">2</div>
<div class="test2">3</div>

You can use below to find the div by the number of the iteration, however this might not be the best thing to do. See below the snippet..
var resultObject = {
testResult: $('.test').map(function(i) {
return {name: $(this).text(), no: $('.test2').eq(i).text()};
}).get()
};
console.log(resultObject);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">test1</div>
<div class="test">test2</div>
<div class="test">test3</div>
<div class="test2">1</div>
<div class="test2">2</div>
<div class="test2">3</div>http://stackoverflow.com/questions/ask#
Instead of doing above, better change your html and use data-attributes.
<div class="test" data-no="1">test1</div>
<div class="test" data-no="2">test2</div>
<div class="test" data-no="3">test3</div>
Doing it like this, you will be able to pull the data much easier:
var resultObject = {
testResult: $('.test').map(function(i) {
return {name: $(this).text(), no: $(this).data("no")};
}).get()
};
console.log(resultObject);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test" data-no="1">test1</div>
<div class="test" data-no="2">test2</div>
<div class="test" data-no="3">test3</div>
<div class="test2">1</div>
<div class="test2">2</div>
<div class="test2">3</div>http://stackoverflow.com/questions/ask#

Related

Displaying elements based on search

I would like the .box elements to show/hide based on the words the user searches for, so for example if a user types in 'Title2 Title1' because those words exists inside box one and two they will remain visible with the renaming .box elements hiding. All the text within the .box elements needs to be searchable not just that in the .title element.
Below is how far I've got. It's almost there but it's not quite working as hoped.
Any help would be great.
Many thanks.
<input placeholder="Search" id="search" type="text" />
<div class="box">
<div class="title">Box Title1</div>
<div class="content">
Box title one content
</div>
</div>
<div class="box">
<div class="title">Box Title2</div>
<div class="content">
Box title two content
</div>
</div>
<div class="box">
<div class="title">Box Title3</div>
<div class="content">
Box title three content
</div>
</div>
<script>
$("#search").on("input", function () {
var search = $(this).val();
if (search !== "") {
var searchArray = search.split(" ");
searchArray.forEach(function(searchWord) {
$(".box").each(function () {
if($(this).is(':contains('+ searchWord +')')) {
$(this).show();
} else {
$(this).hide();
}
});
});
} else {
$(".box").show();
}
});
</script>
You need to use a different search method. :contains does not work as you expect. Consider the following example.
$(function() {
function filter(e) {
var term = $(e.target).val();
if (term.length < 3) {
$(".box").show();
return;
}
$(".box").each(function(i, el) {
if ($(".content", el).text().indexOf(term) >= 0) {
$(el).show();
} else {
$(el).hide();
}
});
}
$("#search").keyup(filter);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input placeholder="Search" id="search" type="text" />
<div class="box">
<div class="title">Box Title1</div>
<div class="content">Box title one content</div>
</div>
<div class="box">
<div class="title">Box Title2</div>
<div class="content">Box title two content</div>
</div>
<div class="box">
<div class="title">Box Title3</div>
<div class="content">Box title three content</div>
</div>
So for example if on is entered, no filtering is performed. If one is entered, the script will look inside the content class of each box and if one is found in the text, it will be shown otherwise, it is hidden. If the User clears their search out, all items are shown.
Hide all box before iterate, then only show when match any words:
$("#search").on("input", function () {
var search = $(this).val();
if (search !== "") {
var searchArray = search.split(" ");
// Hide all .box
$(".box").each(function () {
$(this).hide();
})
searchArray.forEach(function(searchWord) {
$(".box").each(function () {
if($(this).is(':contains('+ searchWord +')') ) {
$(this).show();
}
});
});
} else {
$(".box").show();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input placeholder="Search" id="search" type="text" />
<div class="box">
<div class="title">Box Title1</div>
<div class="content">
Box title one content
</div>
</div>
<div class="box">
<div class="title">Box Title2</div>
<div class="content">
Box title two content
</div>
</div>
<div class="box">
<div class="title">Box Title3</div>
<div class="content">
Box title three content
</div>
</div>
Loop through all .boxs and using regex pattern matching, check either the title or content matches the search query. Show all matched boxes and hide all others
I have also fiddled it here
$("#search").on("input", function () {
var searchables=$('.box');
console.log(searchables)
var query=$(this).val();
searchables.each(function(i,item){
var title=$(item).find('.title').text();
var content=$(item).find('.content').text();
var rgx=new RegExp(query,'gi');
if(rgx.test(title) || rgx.test(content))
{
$(item).show();
}
else
{
$(item).hide();
}
})
})

dynamically replace same div ids with unique ids [duplicate]

This question already has answers here:
How can I assign a unique ID to all div's that have a specific class using JQuery
(4 answers)
Closed 3 years ago.
I was wondering if there's simple JS/JQuery to change the div ids inside the container from 'one' to unique ids (like 'one_1', 'one_2', 'one_3')
<div id="container">
<div id="one">ONE</div>
<div id="one">ONE</div>
<div id="one">ONE</div>
</div>
Desired Output
<div id="container">
<div id="one_1">ONE</div>
<div id="one_2">ONE</div>
<div id="one_3">ONE</div>
</div>
I've gotten so far as to extract the three divs, but now need to replace the text:
document.getElementById("container").querySelectorAll("#one")
You could just loop over the container's children and update their IDs:
var children = document.getElementById('container').children;
for (var i = 0; i < children.length; i++) {
var child = children[i];
child.id = child.id + "_" + (i + 1);
}
You may use the version of .attr() which takes a function as its second parameter:
jQuery(($) => {
$('#container > div').attr('id', (index, id) => `${id}_${index + 1}`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div id="one">ONE</div>
<div id="one">ONE</div>
<div id="one">ONE</div>
</div>
Or, if you can't use ES6+ Javascript:
jQuery(function ($) {
$('#container > div').attr('id', function (index, id) {
return id + '_' + (index + 1);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div id="one">ONE</div>
<div id="one">ONE</div>
<div id="one">ONE</div>
</div>
jQuery solution:
$("#container div").each(function( index ) {
this.id = this.id+"_"+(index+1);
});
Single line (thanks to Andreas's comment)
$("#container div").attr("id", (index, oldId) => oldId + "_" + (index + 1))
$(".changer").on("click",function(){
var i = 1;
$("#container").children().each(function(){
var id = this.id;
$(this).attr("id",(id + "_" + i));
i++;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div id="one">ONE</div>
<div id="one">ONE</div>
<div id="one">ONE</div>
</div>
<button class="changer">
Change IDs
</button>

How to detect number of elements has text start with special word using jquery?

I have a tag like below:
<section id="sec">
<div id="item1">item1</div>
<div id="item2">item2</div>
<div id="item3">item3</div>
<div id="abcitem1">abcitem1</div>
</section>
I want to check how many div tags contextText start with item. May I know is there any easier way that writes for condition and count them one by one(like Jquery)?
Use .filter() to filtering selected elements and use regex in .match() to check existence of item in element text.
var count = $("#sec div").filter(function(){
return $(this).text().match(/^item/);
}).length;
console.log(count);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="sec">
<div id="item1">item1</div>
<div id="item2">item2</div>
<div id="item3">item3</div>
<div id="abcitem1">abcitem1</div>
</section>
var res=0;
$( "#sec div" ).each(function( index ) {
var str= $(this).text() ;
if(str.startsWith("item")==true){
res++;
}
});
console.log(res); //returns 3
You could use reduce function to get the occurrence of elements which start with 'item'.
This is a native javascript solution, which uses startsWith, so you do not have to mess around with regular expressions.
var childDivs = document.getElementById('sec')
.getElementsByTagName('div');
var counter = Array.from(childDivs)
.reduce((accumulator, currentValue) => {
if (currentValue.innerHTML.startsWith('item')) {
return accumulator = accumulator + 1;
}
return accumulator;
}, 0);
console.log( counter );
<section id="sec">
<div id="item1">item1</div>
<div id="item2">item2</div>
<div id="item3">item3</div>
<div id="abcitem1">abcitem1</div>
</section>
Without any jQuery or regex
var nodes = document.querySelectorAll('#sec div')
var count = 0
nodes.forEach(node => count += node.innerText.startsWith('item'))
console.log(count)
<section id="sec">
<div id="item1">item1</div>
<div id="item2">item2</div>
<div id="item3">item3</div>
<div id="abcitem1">abcitem1</div>
</section>
it's possible to add booleans to a number, true means 1 and false means 0
Here is a pure JS way to count it.
function checkItemsCount(section) {
if (!section) return 0;
const sec = document.querySelector(section);
const items = sec.querySelectorAll('div');
let count = 0;
for (let i = 0; i < items.length; i++) {
if (/^item/.test(items[i].innerText)) count++;
}
return count;
}
console.log(checkItemsCount('#sec'));
<section id="sec">
<div id="item1">item1</div>
<div id="item2">item2</div>
<div id="item3">item3</div>
<div id="abcitem1">abcitem1</div>
</section>

Find first instance of specific value and add ID, repeated

Given a series of div's with known values is it possible to create a filter or array that finds the first instance of the values and adds an ID over multiple items? Here's the basic structure:
<div class="boxes">
<div class="box"><time>2017</time></div>
<div class="box"><time>2016</time></div>
<div class="box"><time>2015</time></div>
<div class="box"><time>2014</time></div>
<div class="box"><time>2014</time></div>
<div class="box"><time>2014</time></div>
<div class="box"><time>2013</time></div>
</div>
And here's the snippet I'm using to find one of the values:
var elems = $('.box').filter(function(){
return this.textContent.trim() === "2014"
}).first().attr('id', 'one');
I'm not sure the best way to go about looking for additional instances?
For example, it feels like there's a better way than simply repeating the argument. The novice in me admittedly does not know what this type of function would be called.
var elems = $('.box').filter(function(){
return this.textContent.trim() === "2014"
}).first().attr('id', 'one');
var elems = $('.box').filter(function(){
return this.textContent.trim() === "2017"
}).first().attr('id', 'one');
It would be a bonus to not have to add the specific value, i.e. 2017 (<time id="one">2017</time>), 2016 (<time id="two">2016</time>) but I'm not even sure if that's realistic.
Working Fiddle: https://jsfiddle.net/heykenneth/gn4gmvt0/1/.
You can do this by wrapping up parameters of the code you've already written:
markFirstYear("2014", "one");
markFirstYear("2015", "two");
markFirstYear("2016", "three");
markFirstYear("2017", "four");
// ... etc
function markFirstYear(year, id) {
var elems = $('.box').filter(function(){
return this.textContent.trim() === year
}).first().attr('id', id);
}
#one {color:red;}
#two {color:blue;}
#three {color:green;}
#four {color:purple;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="boxes">
<div class="box"><time>2017</time></div>
<div class="box"><time>2016</time></div>
<div class="box"><time>2015</time></div>
<div class="box"><time>2014</time></div>
<div class="box"><time>2014</time></div>
<div class="box"><time>2014</time></div>
<div class="box"><time>2013</time></div>
</div>
First create array of all values you have, then just get unique values from that array and finally iterate through unique array.
var myArr = new Array();
$('.box time').each(function(){
myArr.push($(this).text());
});
var unique = myArr.filter(function(item, index, array) {
return index == myArr.indexOf(item);
});
for (var i = 0; i <= unique.length; i++) {
var elems = $('.box').filter(function() {
return this.textContent.trim() === unique[i];
}).first().attr('class', 'one');
}
.one {color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="boxes">
<div class="box"><time>2017</time></div>
<div class="box"><time>2016</time></div>
<div class="box"><time>2015</time></div>
<div class="box"><time>2014</time></div>
<div class="box"><time>2014</time></div>
<div class="box"><time>2014</time></div>
<div class="box"><time>2013</time></div>
</div>

sortable new order error get value tkEmail

I need to sort items that are within div with the same id and class. I have problems to return the value of tkEmail tag. I can not get the value.
example:
item 1
Order: 0 Value: 1
HTML:
<div id="sortable">
<div class='sortear' tkEmail='1'>Item 1</div>
<div class='sortear' tkEmail='2'>Item 2</div>
</div>
<br>
<div id="sortable">
<div class='sortear' tkEmail='3'>Item 3</div>
<div class='sortear' tkEmail='4'>Item 4</div>
</div>
JS:
$(document).ready(function () {
$('div#sortable').sortable({
update: function () { novaOrdem() },
});
});
function novaOrdem(){
$('div#sortable').each(function (i) {
alert($(this).attr('tkEmail'))
});
}
Ids have to be unique and you're not actually checking the child divs in the call to each. $('div#sortable').children() will get you what you want. Also, tkEmail is not valid and it would be better practice to use a data attribute e.g. data-tk-email:
HTML:
<div id="sortable">
<div class='sortear' data-tk-email='1'>Item 1</div>
<div class='sortear' data-tk-email='2'>Item 2</div>
<div class='sortear' data-tk-email='3'>Item 3</div>
<div class='sortear' data-tk-email='4'>Item 4</div>
</div>
JQuery:
$(document).ready(function() {
$('div#sortable').sortable({
update: function() {
novaOrdem()
},
});
});
function novaOrdem() {
var items = $('div#sortable').children();
$.each(items, function() {
alert($(this).html() + ', Order: ' + $(this).index() + ', Value: ' + $(this).data('tkEmail'))
});
}
Fiddle Demo

Categories