Check if display is none using Javascript - javascript

I'm using javascript and want to hit a button however if the button is "display:none" then I would like to skip it.
So currently I have this code:
var sf = document.querySelectorAll(input.button")[0];
Now as an example there may be other "input.buttons" on the page that are set to "display:none", I would like to skip these and only click on the visible one.
I appreciate any advice.

var sf = document.querySelectorAll(input.button")[0];
There is problem in above statement. document.querySelectorAll(input.button")[0] will return an empty array if you want to select an input of type button use the following
var sf = document.querySelectorAll("input[type='button']"); // array of button
var sf = document.querySelectorAll("input[type='button']").[0]; // first index element
assume you sf is an array
for (var i = 0; i < sf.length; i++) {
if (sf[i].style.display != "none") {
console.log(elem[i])
}
}

To check for display: none in jquery is using sub-selectors (usually called) :visible.
if(document.getElementById("id").is(':visible')){
// YES, ITS WORKING..!
}

Related

Using loop to determine which group of radios is "visible" and getting value of checked

i have select on my page that allows me to dynamically create rodio groups. When I change select options I remove old radios and append new ones to the same form. Now I need to read the value of the selected radio from the given group that is currently 'visible'. Radio groups have unique names. When I try execute a function with the code below i get Uncaught TypeError: document.querySelector(...) is null. What I'm trying to get with these loops is to find the right radios group and get value (most important) from the selected one. If there is a simpler or diffrent way of doing this i'm open to good word, preferably in js.
This is what i have at this point of time
for (let key in glowne_klasy_radio) {
let wartosc = document.querySelector('input[type="radio"][name="' + key + '"]:checked').value;
}
and also this
let group_radios_names = ["rzut", "podanie", "faul", "strata", "swobodny_ruch_pilki"];
for (let i = 0; i < group_radios_names.length; i++) {
let wartosc = document.querySelector('input[type="radio"][name="' + group_radios_names[i] + '"]:checked').value;
}
Your problem is caused by unchecked or non-existing radio buttons. It can easily be avoided by introducing a more tolerant way of asking for the .value attribute, see here:
const radios = ["rzut", "podanie", "faul", "strata", "swobodny_ruch_pilki"];
function getAttr(obj,attr){
return obj && obj.closest('div').style.display!=="none" && obj[attr]; }
function showHide(){
document.querySelectorAll('input[type="radio"]').forEach(q=>q.closest("div").style.display=Math.random()>.5?"":"none")
}
function getValues(){
const values={};
radios.forEach(r=>
values[r]=getAttr(
document.querySelector('input[type="radio"][name="'+r+'"]:checked'),"value"));
console.log(values);
}
// Create radio buttons:
document.querySelector("div").innerHTML=radios.map(r=>'<div>'+r+':'+["A","B","C"].map(v=>'<br><label><input type="radio" name="'+r+'" value="'+v+'"> '+v+'</label>').join('')+'</div>').join("<hr>")
// Connect getValues function to button:
document.querySelectorAll("button").forEach((b,i)=>b.onclick=[showHide,getValues][i]);
<button>show/hide some</button>
<button>check values</button>
<div style="height:650px"></div>
In this revised version of the script I also check for the visibility of a radio button group by looking at the parent's visibility:
obj.closest('div').style.display!=="none"
Only if this is true then then value of obj will be returned.
Working code, i used element.querySelector, where let parent is parent element to my radio buttons.
let parent = document.querySelector("form[id='glowneRadios']");
let wartosc = parent.querySelector("input[type='radio']:checked").value;

My js file keeps on repeating my the previous list item. for example if i add a text on my form, the previoius list item repeat itself with new one

let leadTracker = [];
const inputText = document.getElementById("input-text");
const inputButton = document.getElementById("input-button");
const Listing = document.getElementById("listings");
inputButton.addEventListener("click", function () {
leadTracker.push(inputText.value);
clicker();
});
function clicker() {
for (let i = 0; i < leadTracker.length; i++) {
Listing.innerText += leadTracker[i];
console.log(leadTracker);
}
}
I added bro to the array and then back but bro is repeated. This is exactly the same code I read online but it is still not working fine for me.
Each time you call clicker it's going to add the whole array to Listing, including stuff that's already there.
Did you mean to clear out Listing at the beginning of clicker, before the for loop?
Listing.innerText = ""
You have to ways to do this :
first you have to not use for loop in the function
function clicker() {
Listing.innerText += leadTracker[leadTracker.length-1];
console.log(leadTracker);
}
or you can remove all innerText from the element then re-write it again :
function clicker() {
Listing.innerText = "";
for (let i = 0; i < leadTracker.length; i++) {
Listing.innerText += leadTracker[i];
console.log(leadTracker);
}
}
Each time you click the button you take the content of the text field and add it to the leadTracker array. So the array grows with each click, longer and longer. So far so good.
But in the the clicker function, which also runs on every click, you take the entire content of the array and append it to Listing. They array is not cleared in between clicks, so old items in it will be printed again.
You can either skip using an array at all:
inputButton.addEventListener("click", function () {
Listing.innerText += inputText.value;
});
or replace the inner text of Listing instead of appending it, as suggested in other answers.

Am I using indexof correctly?

I'm trying to use indexof to tell me if a string appears on page.
The function below should cycle through all checkboxes (name="comment") in my form checking for each checkbox's value within the rest of the document (only because I can't figure out how to search just one span). If the string value is found to exist elsewhere on the page, that checkbox will change css style.
function loop() {
var comment=document.forms[0].comment;
var ii;
for (ii=0;ii<comment.length;ii++) {
str=comment[ii].value;
id = comment[ii].id;
if(document.body.innerHTML.toString().indexOf(str) !=-1)
{
document.getElementById(id).style.visibility = "hidden";
}
}
}
The result is that all checkboxes turn "hidden". I thought the problem was the checkbox finding its own value in the HTML, but the same happens when I search for nonsense.
Am I using indexof incorrectly? Can anyone point out how and where? I don't want to use window.find.
To elaborate:
Checkbox 1 value is "A IS FOR APPLE". Check the page for the string "A IS FOR APPLE". If found, make checkbox 1 hidden. Go to checkbox 2 and repeat.
If I understood what are you trying to do, I think a better approach should be something like this:
function loop() {
var inputs = document.getElementsByTagName("input");
var span = document.getElementsById("txtHint");
for(var i = 0; i < inputs.length; i++) {
//Let's check only the checkbox with the name comment
if(inputs[i].name == "comment" && inputs[i].value == span.innerText) {
inputs[i].style.visibility = "hidden";
}
}

How to detect if a user input has been repeated?

I'm trying to make hangman in javascript and I want to check if the user has used a letter already. I made a var letterGuessValue = to 0 and if they add an input it = 1. I know this would say know to everything if i got it to work (it doesn't even do anything) but am I on the right track maybe? Here's my code. http://jsbin.com/aWOnAfe/5/edit
I would say add an input to a list and whenever they add another input (aka letter), check this list to see if it is already in there. If it is, then its because they've already used that letter before. If not, then it is a new letter.
I don't see where the difficult part is.
http://jsfiddle.net/DerekL/jgqQ9/
Sample code
var used = {};
$("input").keyup(function(){
var val = this.value;
alert( used[val] ? "Used" : "Not used" );
this.value = "";
used[val] = true;
});
How it works
Assign true to used.LETTER when a letter is entered. Before assigning it though, if it was undefined then it hasn't been used. If it is true then it is used.
Sometimes developers tend to use an Array to record pressed keystrokes when doing key combinations, but in this case, iterating an Array would require both more memory and computation power. A simple object is an enough fit.
Use an array to store all of the used letters and function like this to add new ones.
var inputs = []
function addLetter(letter){
var used = false;
for(var i = 0; i < inputs.length; i++){
if(inputs[i] == letter){
used = true;
break;
}
}
if(!used){
inputs.push(letter);
}
}
The easiest way is to append each letter to a string, like this:
var letters = '';
var letterPressed = 'X'; // uppercase it if appropriate for your language
if (letters.indexOf(letterPressed) > -1)
{
// you already pressed it
}
else
{
letters += letterPressed;
}
You can also use an array to store your list of presses, although IMO that's overkill.

Get all files for all .uploadedFiles

Im looking for a javascript/jquery (doesn't matter which way) to collect all the files i've uploaded.
I have the following code, where .afbeelding is the class for a couple of file input fields
var geuploadeAfbeeldingen = $('.afbeeldingen').files;
for (var i = 0; i < geuploadeAfbeeldingen.length; i++) {
}
This somehow doesnt seem to work. When i try document.getElementsByClassName it also doesn't work. The funny thing however is, that document.getElementById seem to work on one input field
Any ideas?
This should do what you want
var files = [],
geuploadeAfbeeldingen = $('.afbeeldingen').each(function(){
for (var i = 0; i < this.files.length; i++){
files.push(this.files[i]);
}
});
You end up with an array (files) that holds each file you have selected through the input elements..
Demo at http://jsfiddle.net/gaby/GJW7Y/1/
If you only want the filenames then change
files.push(this.files[i]);
with
files.push(this.files[i].name);
Try this way :
var geuploadeAfbeeldingen = $('.afbeeldingen');
for (var i = 0; i < geuploadeAfbeeldingen.length; i++) {
alert(geuploadeAfbeeldingen[i].files[0].name);
}
This may help you.
Edit :
$('.afbeeldingen').files is not work and document.getElementById().files is worked because first one return JQuery object( array of objects) and second one return DOM object.The jQuery object (created by the $ method) is a wrapper around a DOM element or a set of DOM elements. The normal properties and methods are not available with JQuery object.
You need to loop through each input element and return the files property.
Something like this is probably the shortest way, using map to iterate through an array:
var geuploadeAfbeeldingen = $('.afbeeldingen').map(function(k, v) { return v.files[0]; }).get();

Categories

Resources