I have a for loop.
In the loop there is an if statement that adds an error css style if the dropdown is found empty.
My problem is that the loop only loops 3 times then stops when it is supposed to loop 15 times.....and i do not know why.
The loop alone works fine, but but when i add the if statement, that's when it becomes weird.
Help.
here is my loop
//add all the id's in an array. array size is 15
var drop_down=["Cars_chassis","Cars_model".....];
for (var i = 0; i < drop_down.length; i++) {
//check if dropdown is empty
if(document.getElementById(drop_down[i]).value == ""){
//change the color of border
$('#'+drop_down[i]).css('border-color' , '#dddcdc');
}
}
I would suggest adding a CSS class to each one of these elements instead of specifying their id. Why manage all of those ids when one class can do the trick?
<select id="Cars_chassis" class="bordered-select"></select>
<!-- Add class to other 15 -->
At this point you could statically define a style for these drop downs in CSS.
.bordered-select{
border-color: #DDDCDC;
}
Or set the style on the elements using the class selector. It appears your using jQuery so the following example would work.
$(".bordered-select").css('border-color', '#DDDCDC');
If you only need to highlight those without a value the following would remove those without a value from the matched set of elements:
$(".bordered-select").filter(function(){
return $(this).val() == "";
}).css("border-color", "#DDDCDC");
Working Example: http://jsfiddle.net/v4hQz/
var drop_down=["Cars_chassis","Cars_model".....];
for (var i = 0; i < drop_down.length; i++) {
//check if dropdown is empty
if( $('#' + drop_down[i]).value == ""){
//change the color of border
$('#'+drop_down[i]).css('border-color' , '#dddcdc');
}
}
OR you can try
var drop_down=["Cars_chassis","Cars_model".....];
var contents = $('#' + drop_down[i]);
for (var i = 0; i < drop_down.length; i++) {
//check if dropdown is empty
if( $(contents[0]).value == ""){
//change the color of border
$('#'+drop_down[i]).css('border-color' , '#dddcdc');
}
}
document.getElementById(drop_down[i]); //returns a HTML DOM Object
var contents = $('#' + drop_down[i]); //returns a jQuery Object
You can try replace the if (javascript) to if (jquery syntax)
Related
I have these sections on this side scrolling site. And want to add a class which will change styling depending if you're on a certain section.
I'm working on this function. The top is what determines the section of the side scroller you are viewing.
The let variables and below is where it stops working. I'm trying to have it so if a nonHome ID section is clicked, for example "slide-1", then add the class 'nav-visibilty'. If they are a match "slide-2" and "slide-2" then remove said class. Am I close?
https://codepen.io/mikayp-the-styleful/pen/NWPxoXR?editors=1111
setTimeout(function(){
for (i=0; i < nonHome.length; i++ ){
if (nonHome[i].id != nonHomeID){
nonHome[i].classList.add("nav-visibility");
console.log('add')
} else{
nonHomeID.classList.remove("nav-visibility");
console.log('rem')
}
}
I am still not totally clear on the behavior that you want, but there are two errors in the code that can be fixed:
It seems like you are always using 'slide-2' instead of the slideId in your event handler.
As mentioned in a comment, nonHomeID is being used incorrectly in your comparison (it is either a string or an element, but you are using it as if it was a string in the if condition, and as the element in the else branch.) Here I have kept it as an element and renamed it for clarity.
Fixing these errors results in code that applies the nav-visibility class to all slides except the one selected by the button. Is that the desired behavior?
let nonHome = document.querySelectorAll(".slide-container section");
let nonHomeSelected = document.getElementById(slideId);
var i;
setTimeout(function() {
for (i = 0; i < nonHome.length; i++) {
if (nonHome[i] != nonHomeSelected) {
nonHome[i].classList.add("nav-visibility");
console.log("add");
} else {
nonHome[i].classList.remove("nav-visibility");
console.log("rem");
}
}
}, 1000);
Edit to add: If the goal is to add nav-visibility to all only the specific slideId, you should not be adding in a loop, i.e. you need to pull your check for whether the slide is Home outside the loop. There are conceptually two steps here: remove the class from all elements that are no longer to have it, then add the class to the element that needs it.
let slideToAddVisibilityTo = document.getElementById(slideId)
let homeSlide = document.getElementById('slide-2')
let allSlides = document.querySelectorAll(".slide-container section")
for (let i = 0; i < allSlides.length; ++i)
allSlides[i].classList.remove('nav-visiblity')
if (slideToAddVisibilityTo != homeSlide)
slideToAddVisibilityTo.classList.add('nav-visibility')
Just hide them all, then show the clicked one:
function showSection(id) {
var sections = document.getElementsByTagName("section");
for(var i=0; i<sections.length; i++) sections[i].classList.remove("nav-visibility");
var current = document.getElementById(id);
current.classList.add("nav-visibility");
}
Example: showSection("foo") will remove nav-visibility from all sections, then add it to the section with id foo.
I am trying to apply a class where text matches with sibling elements.
My certain condition is:
I have a table with multiple rows based on data that I get through database.
One of the td elements has my defined class.
Now I wanted to apply a class only on those td elements where the text of this element matches with another one.
So It would be like, td's whose html/text is equal has that class.
I tried:
$('#table tbody>tr').find('td[class^="customtd"]').each(function() {
if($(this).html().trim() == $(this).siblings('td').html().trim()) {
$(this).addClass('active');
}else {
$(this).removeClass('active');
}
});
You'd have to iterate each sibling td (or use filter), check for a text match, then add the class:
$('#table tbody>tr').find('td[class^="customtd"]').each(function() {
var text = $(this).text();
$(this).siblings("td").filter(function() {
return $(this).text() == text;
}).addClass("active");
});
You have to set the value you are searching for and then loop through all table data. If you find a match, add the certain class.
Furthermore you should cache variables in jQuery and avoid using each() function since its performance is really bad compared to for loops.
//cache the element you are searching for
var search = $('.customtd').html().trim();
//cache the whole table so we can use a for loop
var table = $('#table tbody>tr>td');
//use for loop for more performance
for (var i = 0; i < table.length; i++) {
if(table.eq(i).html().trim() == search) {
table.eq(i).addClass('active');
}else {
table.eq(i).removeClass('active');
}
}
Here is a working example:
http://jsfiddle.net/jnh2heuh/2/
I have 3 columns which include dynamically generated list elements (li tags)
these have an attribute that I try to use to hide a row / li when an amount of character is not reached in this element.(by using opacity property)
I have it working...sometimes and sometimes it only works for one column out of the 3...
So I'd appreciate some insight on what's wrong here.
(function() {
// selecting all elements with class
// class="checkout-tariff-meta-maybe-hidden"
var elems = $(".checkout-tariff-meta-maybe-hidden");
// interact between founded elements
for (var k = 0; k < elems.length; k++) {
// getting text content size
var textSize = elems[k].textContent.length;
// if text size is one we will hide element
if (textSize <= 1) {
// hiding
elems[k].style.opacity = "0";
}
}
}());
You can just go straight to the point and do something like:
// Adjust as needed
$(document ).ready(function() {
$('.checkout-tariff-meta-maybe-hidden').filter( function() {
return $(this).text().length<3; } ).hide();
});
Since you're using jQuery, to hide an element you can just do:
$(elems[k]).hide();
Alternatively, if you're looking to hide it without collapsing (since you're changing opacity, I assume this is the case), look into .fadeTo():
$(elems[k]).fadeTo(1, 0);
You might look at ...
if (textSize <= 1) {
elems[k].style.opacity = "0";
} else {
elems[k].style.opacity = "1";
}
... to ensure they get turned back on when longer.
I have this JSFiddle where I am trying to make it so that the items in an unordered list are visible only if the option selected in a drop down matches their class. List items may have multiple classes, but so long as at least one class matches, the item should be made visible.
The Javascript looks like this:
function showListCategories() {
var selection = document.getElementById("listDisplayer").selectedIndex;
var unHidden = document.getElementsByClassName(selection);
for (var i = 0; i < unHidden.length; i++) {
unHidden[i].style.display = 'visible';
}
};
The idea is that it gets the current selection from the drop down, creates an array based on the matching classes, then cycles through each item and sets the CSS to be hidden on each one.
However, it's not working. Can anyone tell me where I'm going wroing?
Note that I haven't yet coded the "show all" option. I think I'll probably be able to figure that out once I have this first problem solved.
In your fiddle change load script No wrap - in <head>.
Just change your function like following
function showListCategories() {
var lis = document.getElementsByTagName('li');
for (var i = 0; i < lis.length; i++) {
lis[i].style.display = 'none';
}
//above code to reset all lis if they are already shown
var selection = document.getElementById("listDisplayer").value;
lis = document.getElementsByClassName(selection);
for (var i = 0; i < lis.length; i++) {
lis[i].style.display = 'block';
}
};
and in css it should be none not hidden
.cats, .rats, .bats {
display: none;
}
If you want to show all li when showAll is selected, add all classes to all lis.
You have a few things going on. First, your fiddle is not setup correctly, if you open the console you'll see:
Uncaught ReferenceError: showListCategories is not defined
This means that the function doesn't exist at the point you attach the event or that the function is out of scope, because by default jsFiddle will wrap your code in the onLoad event. To fix it you need to load the script as No wrap - in <body>.
Second, there's no such thing as a display:visible property in CSS. The property you want to toggle is display:none and display:list-item, as this is the default style of <li> elements.
Now, to make this work, it is easier if you add a common class to all items, let's say item, that way you can hide them all, and just show the one you want by checking if it has a certain class, as opposed to querying the DOM many times. You should cache your selectors, it is not necessary to query every time you call the function:
var select = document.getElementById('listDisplayer');
var items = document.getElementsByClassName('item');
function showListCategories() {
var selection = select.options[select.selectedIndex].value;
for (var i=0; i<items.length; i++) {
if (items[i].className.indexOf(selection) > -1) {
items[i].style.display = 'list-item';
} else {
items[i].style.display = 'none';
}
}
}
Demo: http://jsfiddle.net/E2DKh/28/
First there is no property in Css like display:hidden; it should be display: none;
here is the solution please not that i am doing it by targeting id finished
Js function
var selection = document.getElementById("listDisplayer");
var list = document.getElementsByTagName('li');
selection.onchange = function () {
var value = selection.options[selection.selectedIndex].value; // to get Value
for (var i = 0; i < list.length; i++) {
if (list[i].className.indexOf(value) > -1) {
list[i].style.display = "list-item";
} else {
list[i].style.display = "none"
}
}
}
css Code
.cats, .rats, .bats {
display: none;
}
JSFIDDLE
You have many things wrong in your code and a wrong setting in the jsFiddle. Here's a working version that also implements the "all" option:
Working demo: http://jsfiddle.net/jfriend00/5Efc5/
function applyToList(list, fn) {
for (var i = 0; i < list.length; i++) {
fn(list[i], list);
}
}
function hide(list) {
applyToList(list, function(item) {
item.style.display = "none";
});
}
function show(list) {
applyToList(list, function(item) {
item.style.display = "block";
});
}
function showListCategories() {
var value = document.getElementById("listDisplayer").value;
var itemList = document.getElementById("itemList");
var items = itemList.getElementsByTagName("li");
if (value === "all") {
show(items);
} else {
// hide all items by default
hide(items);
show(itemList.getElementsByClassName(value));
}
}
Changes made:
You have to fetch the .value of the select to see what the value was of the option that was picked. You were using the selectedIndex which is just a number.
A common technique for displaying only a set of objects is to hide all of them, then show just the ones you want. Since the browser only does one repaint for the entire operation, this is still visually seamless.
When finding items that match your class, you should be searching only the <ul>, not the entire document. I added an id to that <ul> tag so it can be found and then searched.
To save code, I added some utility functions for operating on an HTMLCollection or nodeList.
Tests for the "all" option and shows them all if that is selected
Changed the jsFiddle to the Head option so the code is available in the global scope so the HTML can find your change handler function.
Switched style settings to "block" and "none" since "visible" is not a valid setting for style.display.
I am trying to create a site where you select an option from a dropdown list called contactOptions. The options has values ranging from 0 to 8. When the option is selected, I wish for text to appear underneath -- this text is contained within div tags with ID's such as #contact0 for the text corresponding to option 0. These ID's all have display: none by default. I have some JavaScript (below) -- the select tag in my html includes the line onchange = "sortForm()". Unfortunately, the script does not do anything -- the #contact0 remains invisible.
function sortForm() {
var selection = document.getElementById("contactOptions");
var selectedValue = selection.options[selection.selectedIndex].value;
for (var i = 0; i <=8; i++) {
var subobjContact = document.getElementById("contact" + i);
if (i == selectedValue) {
subobjContact.style.display == "block"
} else {
subobjContact.style.display == "none"
}
}
}
Use single equal sign
subobjContact.style.display = "block"
and
subobjContact.style.display = "none"