Select Div Title Text and Make Array With Jquery - javascript

I'm trying to add the text from all divs Title Attributes to an array but I can't seem to select the right thing.
I need the title because it will contain the string that I need to use.
Here are three divs with different titles
<div class = 'test' title='title1'>Hello</div>
<div class = 'test' title='title2'>goodbye</div>
<div class = 'test' title='title2'>goodbye</div>
Here is my Jquery so far.
$(document).ready(function() {
$array = $('[title][title!=]').each(function(){
$(this).attr("title").makeArray;})
alert($array)
});
The alert just says [Object object]
In my example I'm trying to select create an array that contains [Title1, Title2, Title3].
Can anyone help me do this?
********************************UPDATE************************************
Thanks the first one worked perfectly. I really appreciate it.

var array = $.map($('[title][title!=""]'), function(el) { return el.title });
FIDDLE
Selects all elements that has a title attribute that is not empty, and maps the titles to an array

var theArray = []; // set an empty array to a variable outside of scope
$('.test').each(function() { // loop through all the .test divs
var theTitle = $(this).attr('title'); // selects the text of the title for the current .test element
theArray.push(theTitle); // this adds the text of the current title to the array
});
console.log(theArray); // just to test and make sure it worked, remove once verify

I'd suggest:
var titles = $('.test').map(function(){
return this.title;
}).get();
References:
get().
map().

Related

looping over nested array to create elements with js/jquery

I come with a problem, I hope you can help me solve.
I have already searched on this side quite a bit, but couldn't find an answer that solves my problem. I recently worked with looping over objects with jquery each and that worked fine. ATM I need to loop over entries of an array.
This is an example of how the array looks. It contains arrays, which themselves contain the src of an img and the title of the img.
var imgRef = [[http://127.0.0.1:5555/images/imgf0002.png, fig number 1],[http://127.0.0.1:5555/images/imgf0012.png, fig number 12]]
What I would like to do is to loop over the arrays and create a div for each entry. Inside the divs there should be an img containing the src of the other array and a p tag with the name. Then this will be appended to another element on the website.
<div>
<img src="http://127.0.0.1:5555/images/imgf0002.png">
<p>Fig number 1</p>
</div>
<div>
<img src="http://127.0.0.1:5555/images/imgf0012.png">
<p>Fig number 2</p>
</div>
I have started with this. Just to see whether I can loop over the entries, but it didn't work.
$.each(imgRef, function (index, value) {
$('<div />', {
'text': value
}).appendTo('#localImg');
});
var imgRef = [['http://127.0.0.1:5555/images/imgf0002.png', 'fig number 1'],['http://127.0.0.1:5555/images/imgf0012.png', 'fig number 12']]
$.each(imgRef, function(index, value){
$('.localImg').append('<div><img src="'+value[0]+'"><p>'+value[1]+'</p></div>');
});
you've got to iterate over the array with arr.forEach((elem) => {}) or other iterator methods. Since each of elements of the main array, is an array of two elements, you can use array destructuring and use [url, title] instead of elem in the iterator function. Then in the body create the html string from title and url and append it into your target using $.append method.
let theArray = [["url1","title1"],["url2","title2"] /*,...*/];
theArray.forEach(([url, title]) => {
$('#localImg').append(`<div>
<img src="${url}">
<p>${title}</p>
</div>`);
});
var imgRef = [['http://127.0.0.1:5555/images/imgf0002.png', 'fig number 1'],['http://127.0.0.1:5555/images/imgf0012.png', 'fig number 12']]
$.each(imgRef, function (index, [src, text]) {
// create the div element
const div = $("<div></div>")
// create the image and add src for it.
const img = $('<img />', {
src,
});
// create the p element and add the text to it.
const p = $('<p></p>', {
text
})
// append both image and p in the div
div.append([img, p])
// then insert the block inside the localImage container.
$('#localImg').append(div)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="localImg"></div>

get the all the id's from a class when the image is selected

I have few uploaded images in one div and I want to move them to another div and update the database table. For that I need the id's of the images selected and the name of the div where I want to move.
I have the id of the selected image using the check box but I am not sure how can I get all id's in the end .
function MoveImages(){
for ( var i = 0; i < $(".ct input[type=checkbox]:checked").length; i++) {
var element = $(".ct input[type=checkbox]:checked")[i];
var parent = element.parentNode;
var id = parent.getAttribute('id');
}
}
how can I get all the id's in the end ?
This is how my class looks like.
<div class="ct" id="559429bc0d559162552c9728">
<input type="checkbox" class="remove">
<img src="/image?id=c9728" data-src="random.JPG" id="previewImagec9728">
</div>
the move function should return all the id's.
With a bit of JQuery's $.each, substring, and JS array methods, you can grab the raw IDs and put them in an array like so:
var ids = [];
//For each element that matches ".ct input[type=checkbox]:checked".
$.each($('.ct input[type=checkbox]:checked'), function() {
//Find the image element, get the id value, and strip the first 12 characters.
var id = $(this).find('img').attr('id').substring(12);
//Put ID in array.
ids.push(id);
});
Use $.map():
var yourIds = $(".ct input[type=checkbox]:checked").map(function(){
return $(this).parent().attr('id');
});
Try jquery's each:
$('.ct').each(function() {
var id = $(this);
})
use :has and .map
$('.ct:has(:checked)').toArray().map(function(element, index) { return element.id })
or
$('.ct:has(:checked)').map(function(index, element) { return element.id }).toArray()
in both cases .toArray() is to get a normal array instead of a jquery array

Duplicate the value from the group of radio

I want to duplicate the text value of the active radio buttom before other div. Radios are divided into groups. In each group is always active, only one. Therefore, a new value from each group should always be one, too. I will add a text value, but I cant to make the removal of the previous value of the group.
$('.views-exposed-widget').find('.form-type-radio').on('click', function(){
var a = $(this).closest('.form-type-radio').find('label[class="option"]').text();
$('.views-widget-sort-by').before('<span>'+a+'</span>');
});
My example: http://jsfiddle.net/e59ogp8a/
You could name them (and thus create a mapping between the radio group and the spans) so you can find them easily
$('.views-exposed-widget').on('change', 'input', function () {
var self = $(this),
name = this.name,
text = self.closest('.form-type-radio').find('label[class="option"]').text(),
target = $('.views-widget-sort-by').find('[data-for="'+ name +'"]'); // find the related span
// check if we found a related span, and if not create it
if (target.length == 0){
target = $('<span data-for="'+name+'"></span>').appendTo('.views-widget-sort-by');
}
// set the text of the span
target.text( text );
});
Demo at http://jsfiddle.net/gaby/5nutt42g/1/
You also had a wrong id on the the first radio (it should be edit-tid-1-4 and not edit-tid-1-2)
You have to remove all the prev siblings of your div element.
$('.views-exposed-widget').find('.form-type-radio').on('click', function(){
var a = $(this).closest('.form-type-radio').find('label[class="option"]').text();
$('.views-widget-sort-by').prevAll().remove();
$('.views-widget-sort-by').before('<span>'+a+'</span>');
});
You can use the group name as span's class name to clear the values of the group after group's button clicked.
Take a look here: http://jsfiddle.net/e59ogp8a/3/
$('.views-exposed-widget').find('.form-type-radio').on('click', function(){
var a = $(this).closest('.form-type-radio').find('label[class="option"]').text();
var groupName= $(this).find('.dls-radio').attr("name");
console.log($('.views-widget-sort-by').prev('.'+groupName).text(''));
$('.views-widget-sort-by').before('<span class="'+groupName+'">'+a+'</span>');
});

Can't set attribute on array items that contain nodes

I'm a beginner Javascripter and I want to run this script to randomly change the background color of boxes. This is my JS:
var divs = document.getElementsByClassName("col-sm-3");
var innDivs = [];
colournumber = function() {
return(Math.random().toString(16) + '000000').slice(2, 8);
}
for (i=0;i<divs.length;i++) {
innDivs[i] = divs[i].getElementsByTagName("div");
innDivs[i].setAttribute("style","background-color:#"+colournumber());
}
But I'm getting the error that I can't setAttribute on innDivs[i]. Any ideas how I do this?
http://jsfiddle.net/w8gLqghz/
getElementsByTagName get you a list of elements. It is the elements themselves that have the setAttribute method.
You'll have to iterate through the list and set each individual element's attribute;
for (i=0;i<divs.length;i++) {
innDivs[i] = divs[i].getElementsByTagName("div");
for (j=0;j<innDivs[i].length;j++) {
innDivs[i][j].setAttribute("style","background-color:#"+colournumber());
}
}
http://jsfiddle.net/mowglisanu/w8gLqghz/5/
As you would see if you look in the debugger, innDivs is empty (you never put anything in it).
Therefore, innDivs[i] doesn't exist.
Did you mean divs?

Adding items to an array using jQuery

I'm using jQuery to add elements to a specified element. So a user selects options from a drop down menu and it's appended to a div. My jQuery is:
$('#datacombo').on('change', function () {
var selecteddata = $("#datacombo").val().toString();
$('#datadisplay').append("<p>"+ selecteddata + "</p>"); });
my HTML is simple a div:
<div id="datadisplay"></div>
I'm wanting to use ALL the 'selected data' at a later point so i want to add the selected items to a variable array.
I've searched on here and tried these:
How do I gather dropdown values into array with jQuery?
But couldnt get it to work, any suggestions?
Just declare array as global variable. And then push elements to it.
var selectedDatas = new Array();
$('#datacombo').on('change', function () {
var selecteddata = $("#datacombo").val().toString();
selectedDatas.push(selecteddata);
$('#datadisplay').append("<p>"+ selecteddata + "</p>");
});

Categories

Resources