I need to select a ul element - javascript

I've added an 'Find an online stockist' button to all product pages. If you click on it, it takes you to a different page. I need to set a filter in the page to 'Online Store'. It will look like this when done:
I'm trying to select this box, so that I can add a to it. (It's the same box as in the previous screenshot but without any filters in it yet.)
Please note I can't change the filter box - it's 3rd party code.
When I inspect the page with no filters in it, it looks like this:
If I inspect it with a filter, it looks like this:
I just need to add a new <li> to the 'chosen-choices' but I can't select it.
I can select the store-filter-sec div:
var storefiltersec = $(".store-filter-sec");
If I view it in the console, it shows the right children:
But I can't select item 2 - div.chosen-container.chosen-container-multi.
var chosenContainer = storefiltersec.find(".chosen-container");
var chosenContainer1 = storefiltersec.find(".chosen-container.chosen-container-multi");
var chosenContainer2 = storefiltersec.find("div.chosen-container.chosen-container-multi");
var chosenContainer3 = $(".chosen-container");
var chosenContainer4 = $(".chosen-container.chosen-container-multi");
var chosenContainer5 = $("div.chosen-container.chosen-container-multi");
var chosenContainer6 = $(".chosen-container .chosen-container-multi");
The plan is that once I can get hold of div.chosen-container.chosen-container-multi, I can then get to
ul.chosen-choices (one of its children):
I tried to get chosen-choices by tag.
var elements = document.getElementsByTagName('ul');
'chosen-choices' shows up in the console:
but I can specify just that one. I tried this:
console.log('specific element', elements[12]);
and get:
Please tell me how I can select ul.chosen-choices in either javascript or jquery.

in javascript to select .store-filter-sec and to put it in a variable:
const el_filtersec = document.querySelector('.store-filter-sec');
Now from this selected element you select .chosen-container
const chosen-container = document.querySelector('.chosen-container');
by the way you can select directly chosen-container
Now the problem is you have several, so:
Array.from(document.querySelectorAll('.chosen-container')).forEach(el => {
// do what you have to do...
}
If you still want store-filter-sec and for each finding chosen-container:
Array.from(document.querySelectorAll('.store-filter-sec')).forEach(el1 => {
Array.from(el1.querySelectorAll('.chosen-container')).forEach(el2 => {
// do what you have to do...
}
}

Related

How to get the ID of the select-option element with "change" event listener?

I am new into javascript, and I've been working on this "project", but I need some help because I'm stuck. I might've not expressed my self correctly in the title so here it is:
I would like to get the ID of an option element (<select> <option id="#"> </select>) by using the "change" event listener on the <select>. So when I choose for example "Action" from the select dropdown, I'd like that change to trigger a function that will get that element's ID and use it in a function down below. Here's the code that I have so far, which basically does the following:
1.) Gets the genre list;
2.) Then for every item in the response.data.genres, sets a number which corresponds to the length of the array (total 19 items).
3.) If the selected "option" element matches the name of the genre in the array, then it defines the genre ID(the integer) and makes another request to the API in order to list the movies matching that genres ID. Thanks in advance.
//Genres
function genres(){
//API request.
axios.get("https://api.themoviedb.org/3/genre/movie/list?api_key=<API_KEY>&language=en-US")
.then((response)=>{
//console.log(response);
let genres = response.data.genres;
genres.length;
console.log(genres)
for(var i = 0; i < genres.length; i++){
var genresId = response.data.genres[i];
var tag = document.getElementById("Thriller");
console.log(genresId);
if(tag.id === genresId.name){
let genre = genresId.id;
axios.get("https://api.themoviedb.org/3/discover/movie?api_key=<API_KEY>&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1&with_genres="+genre)
.then((response)=>{
console.log(response);
})
}
}
})
}
So there are two steps if I understand correctly.
1. get the list of genres and fill a selectbox with it.
2. get a list of movies if an option in the selectbox is selected.
The first step, you can do with an innerHTML method. For every genre that is returned, you build a string like <option value='genre'>genre</option>. With innerHTML you add these options to the select box. The value property is what you use to see which option is selected.
Next we add an eventlistener to the dropbox so our script will react to the changes the user makes. The event we're listening for is 'change' and it will trigger the function 'getMovies'. See Mozilla docs for more info. event.target.value will give you the value of the selected option, which you can use as genre id.
Inside this function you will do your second api call to get your movie list.
A simple example without the api calls is this:
let genreDropdown = document.getElementById('genre');
genreDropdown.innerHTML = getGenres();
genreDropdown.addEventListener("change", getMovies);
function getGenres(){
let genres = ['action', 'romcom', 'thriller']; //this would be replaced with the api call to get the genres
let innerHtml = '';
for(var i = 0; i < genres.length; i++){
var option = '<option value='+genres[i]+'>'+genres[i]+'</option>';
innerHtml += option;
}
return innerHtml;
}
function getMovies(event) {
let genre = event.target.value;
alert(genre) //you can replace this with the api call to get the movies.
}
<select id='genre'>
<option>loading...</option>
</select>
The following Code will look for a <select> (its id to be exact) Element and on change it will output the ID of the Direct Child (<option> in this case).
$(document).ready(function(){
$("#myDropdown").on("change", function(){
the_id = $(this).children(":selected").attr("id")
$("#output").html(the_id);
});
});
I have made an Example for you > JS Fiddle
Hope you can use the jQuery Code.

Recreate Select Control Options Dynamically jQuery

I have the following function which I use to populate a Select control with options. I am grabbing values from objects on the document, and if a condition is met, throwing another value into a Select Control as an option...
function dispatchList() {
//grab list element
var list = document.getElementById("techName");
//foreach div assigned the .square class,
$('.square').each(function () {
//convert each div with .square class toString
var square = $(this).html().toString();
//grab availability value
var availability = $(this).find('tr:eq(4)').find('td').text();
//grab IP
var online = $(this).find('tr:eq(3)').find('td').text()
//if availability and IP values meet below condition...
if ((availability === "True") && (online.indexOf("10.") === 0)) {
//grab the name value from this div
var availableName = $(this).find('tr:eq(0)').find('td').text();
//create a new option element
var item = document.createElement("option");
//create a new text node containing the name of the tech
item.appendChild(document.createTextNode(availableName));
//append the new text node (option) to our select control
list.appendChild(item);
}
})
}
This function works great, but it runs when the document is ready. I need it to run when the document is ready, but also to recreate this list without refreshing the page. Ideally the select control could be emptied and recreated with a click event on a div.
This is the part I have struggled with. I have the following click event which it would make sense to chain this to, but I have not been able to work it out...
function availability() {
//for each element with a class of .square...
$('.square').each(function () {
//grab the id of each input element (button) contained in each .square div...
var btnId = $(this).find("input").attr("id");
//when .square div is clicked, also click it's associated asp button...
$(this).on('click', function (clickEvent) {
document.getElementById(btnId).click();
//****AND ALSO TRIGGER THE dispatchList() FUNCTION TO REBUILD THE #techName LIST****
})
})
}
Can this be done without AJAX or some other post back on the select control?
Does the #techName list need to be emptied first, and then rebuilt?
Thank you for any advice!
$(document).ready(function(){
$(".square").on('click', function (clickEvent) {
var el = clickEvent.target || clickEvent.srcElement
document.getElementById($(el).find('input').attr("id")).click();
dispatchList();
})
})
That's all i can do with the given question. I didn't test the code. You can give fiddle or anything to test. Also this function is written in the browser.

Bootstrap form group checkboxes doesn't get checked in between nav pills

Here's the JSFiddle of my work: https://jsfiddle.net/pb23Ljd8/5/
I use Bootstrap nav-pills to show all products and categorized too like this:
And I based my checkboxes from here: http://bootsnipp.com/snippets/featured/fancy-bootstrap-checkboxes
I count the number of products checked in between the tabs like this:
jQuery(document).ready(function($) {
jQuery(".select-product").change(function() {
jQuery(".counter").text(jQuery("[type='checkbox']:checked").length);
});
});
But the glyphicon check icons doesn't appear on the second and third tabs for some reason. But when I click the products on the second and third, it increases the counter and also when I view it on the first tab, it is checked.
I just need the products to also be visibly checked on the second and third tabs and not only on the first one so it's not confusing for the user.
Ideas, anyone?
Edit: I fetch the list of products from CMS so it's dynamic. I now understand that the duplication of IDs is causing the problem.
Before we try and resolve this issues, we should break it down and see what the actual problem is.
First, let's check if we remove the content from tab 1b is the issue still present?
Nope, if we remove the checkboxes from the first tab, the checkboxes function normally on the second and third.
Fiddle #1
What if we change the id of the checkboxes (remember ids should be unique).
Notice how Book #1 now works if we change the first checkbox's id to 1a.
Fiddle #2
So now we "know" the issue is likely due to the fact that we are using checkboxes with the same id value (ref). The "issue" is now:
How do we check multiple checkboxes if one is checked
(or something like that)
Here's what I would do:
assign all "like" checkboxes the same class (ex. Book #1 checkboxes will have class b1)
use jQuery/javascript to make sure all that all "like" checkboxes, check and uncheck in unison
Working Example
EDIT
Dynamic values for the classes can be achieved by putting the IDs as classes so the similar products would match. These can be passed to JS like this assuming that $products_id_array is a PHP array that contains all the classes needed.
var productIDs = <?php echo json_encode($products_id_array) ?>;
and then creating the snippet of jQuery code on the fiddle like this
productIDs.forEach(function(val, key) {
jQuery('.' + val).on('change', function(){
jQuery('.' + val).prop('checked',this.checked);
});
})
Try this JS, This will work
jQuery(".select-product").change(function() {
var checkValue = jQuery(this).prop('checked');
$('.select-product#' + jQuery(this)[0].id).each(function() {
if (checkValue == true) {
jQuery(this).prop('checked', true)
} else {
jQuery(this).prop('checked', false);
}
});
var uniqueId = [];
jQuery("[type='checkbox']:checked").each(function() {
uniqueId.push(jQuery(this)[0].id);
});
Array.prototype.getUnique = function() {
var u = {},
a = [];
for (var i = 0, l = this.length; i < l; ++i) {
if (u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}
jQuery(".counter").text(uniqueId.getUnique().length);
});

jquery selection attributes

Let's say I have a sample table like this :
http://jsfiddle.net/65BkH/
Now what i want is, if there is this <button id="invite">Invite</button>. I want this button to select the "invite url" of the selected contact. If you see the jsfiddle, if you click the checkbox, it will crop all the others contacts. How could i do that?
I've tried to target the contact, but i can only get the top contact.
$('#linkedin_match tbody .match .m a').attr('href');
what i want is to target the currently selected.
FURTHER PROBLEM :
This button I'm talking about is not the table per say.
$('#btn_save').click(function(e) {
var hrefVar = $('#linkedin_match tbody .match .m').find('a').attr('href');
alert(hrefVar);
});
Now if i used that, it still searches for the first link, even though i've selected the others. So, any changes?.
You can use this:
$('#invite').on('click',function(){
var url = $this.closest('tr').find('a').prop('href');
});
To get all the checked href related with the checked inputs in a array use this:
$('#invite').on('click', function () {
var all_url = [];
$('input:checked').each(function () {
var url = $(this).closest('tr').find(' td.m a').prop('href');
all_url.push(url);
});
});
Demo here
$('.m').click(function(e){
var hrefVar = $(this).find('a').attr('href');
alert(hrefVar);
});
fiddle

creating elements inside an unordered list

I've got a function that creates an unordered list in a form. I have another function that is supposed to add items to the list according to the selected value of a select box. The second function adds items to the list and they have the appropriate id's and whatnot, but no text. I cannot get the items to have text in them no matter what I try. Here is the current contents of the JavaScript function.
function anotherItem()
{
var textValue = document.forms['newForm'].selectBox1.value;
var ul = document.getElementById("newList");
var new_item = document.createElement("li");
new_item.id = textValue;
new_item.innerHtml = textValue; // I've also tried new_item.value = textValue among variations.
ul.insertBefore(new_item, ul.firstChild);
}
5| new_item.innerHtml = textValue;
| └┬─┘
| └───Should be "HTML"
JavaScript is case-sensitive. Now textValue should be written in the create li.
(It should had created an error if you put innerHtml, if you look in the console.)
Test it out: http://jsfiddle.net/DerekL/svUqG/

Categories