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/
Related
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...
}
}
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.
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.
I am trying to have the user check the boxes they are interested in getting resources for and then click the button to get a list of those resources that are hyperlinked to those resources. The hyperlinks (ul id="results” in HTML) are hidden until they called upon by the button “Get Resources”.
Plus I would like to add text to it before results saying “You have indicated an interest in:” (line break) then a listing the hyperlinks (line break) “Please click on the links to learn more”. If no check box is selected the div id=“alert” displays, which I got to work.
I think I am very close, I just can’t seem to get the list of resources.
Here is a link to my coding:
JSFiddle Code sample
$(document).ready(function() {
$('#alert').hide();
$('#results > li').hide();
/* Get the checkboxes values based on the parent div id */
$("#resourcesButton").click(function() {
getValue();
});
});
function getValue(){
var chkArray = [];
/* look for all checkboxes that have a parent id called 'checkboxlist' attached to it and check if it was checked */
$("#checkBoxes input:checked").each(function() {
chkArray.push($(this).val());
});
/* we join the array separated by the comma */
var selected;
selected = chkArray.join(',') + ",";
/* check if there is selected checkboxes, by default the length is 1 as it contains one single comma */
if(selected.length > 1){
// Would like it to say something before and after what is displayed
$('#results > li.' + $(this).attr('value')).show();
} else {
$('#alert').show();
}
}
I'd ditch the selected variable and just check the chkArray contents against the list item classes like:
function getValue() {
var chkArray = [];
/* look for all checkboxes that have a parent id called 'checkboxlist' attached to it and check if it was checked */
$("#checkBoxes input:checked").each(function () {
chkArray.push($(this).val());
});
$('#results li').each(function () {
if ($.inArray($(this).attr('class'), chkArray) > -1) $(this).show()
else($(this).hide())
})
/* check if there is selected checkboxes, by default the length is 1 as it contains one single comma */
if (!chkArray.length) {
$('#alert').show();
//alert("Please at least one of the checkbox");
}
}
jsFiddle example
I found a straightforward way of achieving what you want. DEMO: https://jsfiddle.net/erkaner/oagc50gy/8/
Here is my approach: I looped through all checkboxes. This way I could get the index of the current item in the original list, i, and use this index to display the corresponding item in the second list. I filter the checked items by using .is(':checked') condition, and then added them item to the array:
function getValue() {
var chkArray = [];
$("#checkBoxes input").each(function (i) {//now we can get the original index anytime
if($(this).is(':checked')){//is the item checked?
chkArray.push($(this).val());//if so add it to the array
var selected;
selected = chkArray.join(", ");
if (selected.length) {
$('#results').find('li').eq(i).show();//show the corresponding link by using `i`
} else {
$('#alert').show();
}
}
});
}
Last thing in your $(document).ready function, add:
$("#checkBoxes input:checkbox").click(function() {
$('li.' + $(this).val().replace(/ /g, '.')).show()
});
JSFiddle
Explanation:
On document ready, add a click handler to the checkboxes that shows the corresponding hidden list item below. The tricky thing here is the spaces in the list names. This makes each word a separate classname, so simply combine the list names with a dot . which results in a sequential classname call in jQuery.
By using <li class="Fitness & Recreation"> as a list item classname, you are giving this item 3 classnames: Fitness, &, and Recreation. In jQuery you select elements with multiple classnames by including each name preceded by a dot .. For example, selecting a list item element with the classnames foo, bar, and baz:
$('li.foo.bar.baz').show()
In the case of <li class="Fitness & Recreation">:
$('li.Fitness.&.Recreation').show()
Since these values are stored in the value attribute of the checkboxes we use jQuery to pull these values: $(this).val(), replace the spaces with dots: .replace(/ /g, '.'), and concatenate the result to the li. portion to access the appropriate list item.
I have some code that loops over each row of the table and creates a json object. The elements in the rows can be either of the following:
<input type="text" id="myelem"/>
or
<p id="myelem">foo</p>
Notice that the id attribute for the both is same. This is because on the table there is a button Add a new Row when this button is clicked another row is added to the table with a checkbox. When user submits the form the checkbox goes away and the value they entered turns into <p id="myelem">value they entered</p>
Below is the code I'm using for this.
$('.input-row').each(function(index, row) {
var innerObject = {};
var key = $('#myelem', row).val().toUpperCase();
jsonObject[key] = "bar";
});
The above works fine for textboxes becuse I'm using the .val() function. However, how do I get the data from the row if it contains <p id="myelem">foo</p> ??
my pseudo code would be something like this:
$('.input-row').each(function(index, row) {
var innerObject = {};
/*
if #myelem is a text box then use .val()
if #myelem is a <p> tag then use .html()
*/
var key = $('#myelem', row).val().toUpperCase();
jsonObject[key] = "bar";
});
ids should always be globally unique on a page. If you need multiple elements to be referenced, you should use classes. If you set myelem as a class rather than an id you could then reference it like this
$('.input-row .myelem')
You can check which type the element is with
var value = null;
if($('#myid').is('input')) {
value = $('#myid').val();
}
else if($('#myid').is('p')) {
value = $('#myid').html();
}
IDs are unique. You cannot use more than one ID in the same page. If you do so how should you decide which element to use?
You could use jQuery is() eg if $('#myelem').is ('p'){...}
If still want to stick your development way then below might help you:
$('.input-row').each(function(index, row) {
var innerObject = {};
var c = $('#myelem', row);
var isInputField = c.get(0).tagName.toUpperCase()=="INPUT";
var key =isInputField ? c.val().toUpperCase():c.html().toUpperCase();
jsonObject[key] = "bar";
});
This is to just get you started. You are using .each on class input-row but you have not shown the class in your code that you provided. I have used class instead of id in this example. Use it to work ahead.
Fiddle