Hi guys i am making calculator app and i have got a problem.
I made 3 radio buttons and want them to be checked with 'if statement' in JS file. It just does not work at all because 'main' does not get any class when input2 or 3 is clicked. Only the first one makes 'main' getting it but thats because of input1.checked defaultly set to true. Can anyone help me, pls?
Here is the link to the project on my github:
https://github.com/Adrian397/frontEndMentorChallenges/tree/master/calculator-app-main
Here is live site of it: https://adrian397.github.io/frontEndMentorChallenges/calculator-app-main/index.html
js file
html file
Really liked your idea with different themes.
Coming to your query.
Looks like you have been using const for the main variable. Hence you won't be able to change it.
It would help if you can change the variables to var or let.
Note : Always use const when you are sure that you are not going to change that variable.
Also, its a great habit if you can use :
if(document.getElementById('input1').checked) {
document.getElementById("main").innerHTML
= <Your code goes here>
}
This simplifies the process and keeps the source clean for one Page applications.
Hope this helps. May the source be with you !
Before all, at the first line of your js code you are declaring let main= document.querySelector('main');
This cannot works there because a variable declared as let can be visible only in the function where it is declared so
It's not in the scope of your function declared later (Not visible to it)
then you are declarig input as const and it could give some problem because a constant cannot update so the state checked should be always the same
your code corrected should be this
document.addEventListener("DOMContentLoaded", ()=>{
let main = document.getElementById("main");
let firstInput = document.getElementById("input1");
let secondInput = document.getElementById("input2");
let thirdInput = document.getElementById("input3");
if(firstInput.checked == true){
main.classList.add('dark');
}else {
main.classList.remove('dark');
}
});
Just add the other 'if' like this above.
Also give an id to the html element main to get it from id
I got help on another post so here im pasting corectly working code:
let input1 = document.getElementById("input1");
let input2 = document.getElementById("input2");
let input3 = document.getElementById("input3");
let main = document.getElementById("main");
input1.checked = true;
function setColorTheme() {
if (input1.checked == true) {
main.classList.add("dark");
} else {
main.classList.remove("dark");
}
if (input2.checked == true) {
main.classList.add("light");
} else {
main.classList.remove("light");
}
if (input3.checked == true) {
main.classList.add("saturated");
} else {
main.classList.remove("saturated");
}
}
setColorTheme();
document.querySelectorAll('input[name="theme"]').forEach((e) => {
e.addEventListener("change", setColorTheme);
});
The problem was solved by adding these lines and making variables declarations using 'let':
document.querySelectorAll('input[name="theme"]').forEach((e) => {
e.addEventListener("change", setColorTheme);
});
Related
First, please check out my code.
There might be some misspell! ( I rewrote my code )
const test = () => {
const [files, setFiles] = useState([]);
const handleFile = (e) => {
for(let i=0; i<e.target.files.length; i++){
setFiles([...files, e.target.files[i]
}
}
return (
{
files.map((file, index) => (
<div key={index}>
<p> {file[index].name} </p>
<button> Delete </button>
</div>
))
}
<label onChange={handleFile}>
<input type='file' mutiple /> Attach File
</label>
)
}
When I render with this code, makes errors,
TypeError: Cannot read Properties of undefined (reading 'name')
{file[index].name}
like this.
When I delete .name, only buttons are being rendered. ( as I didn't specify what to render of file's property. )
Moreover, I'm trying to render multiple files at once. As I set my input type as multiple, I can select multiple files when I choose to upload things.
However, even though I selected two or three, It only renders just one.
I hope my explanation describes my situation well. If you have any questions, please ask me!
I'm looking forward to hearing from you!
If you update the same state multiple time in the same handler function only the last call will work for performance issue. You have to change your onChange handler to something like:
const handleFile = (e) => {
const newFiles = []
for(let i = 0; i < e.target.files.length; i++){
newFiles.push(e.target.files[i])
}
setFiles(newFiles)
}
also as mentioned in another answer, change the "name" line to this:
<p>{file.name}</p>
For anyone who has the same trouble as me, Here is a stopgap.
const [files, setFiles] = useState([]);
const handleFile = (e) => {
setFiles([...files, e.target.files[0], e.target.files[1], e.target.files[2]])
if(e.target.files[1] == null) {
setFiles([...files, e.target.files[0]])
} if (e.target.files[1] && e.target.files[2] == null) {
setFiles([...files, e.target.files[0], e.target.files[1]])
}
};
Using conditional statement, you can control the index of files. However, I still don't know what is the other way to deal with the problem.
Anyway, I hope my answer helps you some!
You dont need the [index] part inside the map so should look like this
<p>{file.name}</p>
Should work now :)
UPDATE FOR MULTIPLE UPLOADS
const handleFile = (e) => {
const newSelectedArray = files;
newSelectedArray.push({
...e.target.files[0],
identifier: e.target.filename //check this please i cant remember what the array name is called for filename. You dont need this yet but once we get the first bit working we can include it in something cool.
});
setFiles(newSelectedArray)
}
Let me know on this one as it was a nightmare for me too so hopefully that will work
I am not sure if i am missing out something, but I think looping like this is redundant when instead you can simply do
const handleFile = (e) => {
setFiles(e.target.files)
}
Also, when you want to access the previous state value you should probably access the previous state value by using a callback function inside setFiles like this
for(let i=0; i<e.target.files.length; i++){
setFiles((prevfiles)=>[...prevFiles,e.target.files[i]])
}
EDIT:
I am also mentioning a fix not included in the original answer since it had already been stated by #Matt at the time of posting.I am editing this answer only for the sake of providing the complete answer
file[index].name had to be changed to file.name
I have a few lines of JavaScript code that pick up heading texts from separate sections and place them into their respective input fields. They are also executed on single pages using wp_enqueue_script.
It works absolutely fine when setTimeout() is used:
function passengerElevator() {
var getProductName = document.querySelectorAll('[data-id="6657316"]');
getProductName.forEach(function(item) {
var productName = item.querySelector('.lift');
var inputArea = item.querySelector('input[name=product]');
inputArea.value = productName.innerText;
});
var getProductName = document.querySelectorAll('[data-id="e9c06d5"]');
getProductName.forEach(function(item) {
var productName = item.querySelector('.lift');
var inputArea = item.querySelector('input[name=product]');
inputArea.value = productName.innerText;
});
setTimeout(function() { passengerElevator() },3000);
However, there is problem of page size (some pages have more than 10 input fields) and I don't want to set an astronomically high ms to delay the script. So I decided to fire it on DOMContentLoaded:
document.addEventListener("DOMContentLoaded", passengerElevator);
function passengerElevator() {
var getProductName = document.querySelectorAll('[data-id="6657316"]');
getProductName.forEach(function(item) {
var productName = item.querySelector('.lift'); // heading text (ex:Panoramic Lift)
var inputArea = item.querySelector('input[name=product]');
inputArea.value = productName.innerText; //ouput here
});
var getProductName = document.querySelectorAll('[data-id="e9c06d5"]');
getProductName.forEach(function(item) {
var productName = item.querySelector('.lift'); // Heading text (ex:Home Lift)
var inputArea = item.querySelector('input[name=product]');
inputArea.value = productName.innerText; // Output here
});
}
As you may have already guessed, it is not working. Is my code too messy to be executed faster or is there any other problem I am missing?
I know similar questions have been asked previously, however, no existing answer I found was able to help me.
It seems like you try to loop through elements that are still not loaded. Perhaps they are being appended to the page via Ajax, so DOMContentLoaded can't help there.
You can create your own check for those elements using setInterval, so use something like this:
let dataIdCheck = setInterval(() => {
if (document.querySelectorAll('[data-id="6657316"]').length > 0 && document.querySelectorAll('[data-id="e9c06d5"]').length > 0) {
clearInterval(dataIdCheck);
// your code here
}
}, 500);
This code will run every 500 milliseconds and check if those two elements exists, using .length. Once they do exists, we stop the interval and run the code.
I also suggest to do console.log('in') to check that our interval stop running once the elements are found.
Although there are several same questions, I'm very curious regarding this specific case.
jQuery(document).ready(function () {
if ($('#msg').val() != '' && $('#msgSuccess').val() == 'true') {
var msg = $('#msg').val();
var t = $('#msg').val().toString();
toastr.success("#_localizer[t]");
}
});
variable t has some message which represents the key for my localization file.
I have issue to pass that variable (string) to my mvc _localizer.
Where I go wrong with this?
If I add simple console.log(t) it works. So Im guessing that is the localizer is a problem.
I'm using #inject IViewLocalizer _localizer from AspNetCore.Mvc.Localization
I’m in the process of creating a simple application in Electron that allows you to add tasks to a list. However, it shouldn’t allow you to add empty tasks.
The following script is a minimum, verifiable version of what I’m using inside the Renderer JS file.
const taskForm = document.querySelector('form');
taskForm.addEventListener('submit', addTask);
function addTask(event)
{
const formInput = taskForm.querySelector('input[type="text"]');
const taskName = formInput.value;
formInput.value = "";
if (!taskName || taskName.length === 0)
{
console.log("Empty");
return; //It doesn't seem to like this return. No idea why.
}
//Task element is created and added
event.preventDefault();
}
I’ve also put together a JSFiddle, for those who want to mess around with the issue in code: https://jsfiddle.net/bts22a34/ It seems to throw an issue here too, despite being outside Electron.
Whenever it hits the return function, it throws the following error:
"Error: No such module: atom_renderer_v8_util"
From adding a breakpoint just before the "if" statement, it seems to successfully complete the return, hit the end of the function, and then throw the error.
If I send in a non-empty string, it skips past the if statement successfully and completes the function with no error.
From messing around with it again just now, it seems to be an issue with regards to “event.preventDefault” not being run if you go through the if statement.
const taskList = document.querySelector('div');
const taskForm = document.querySelector('form');
taskForm.addEventListener('submit', addTask);
id = -1;
function addTask(event)
{
const formInput = taskForm.querySelector('input[type="text"]');
const taskName = formInput.value;
formInput.value = "";
if (!taskName || taskName.length === 0)
{
console.log("Empty");
}
else
{
//Task element is created and added
}
event.preventDefault();
}
JSFiddle: https://jsfiddle.net/bts22a34/
I'm relatively new to JavaScript, although I have recently turned a corner. I just wrote this code block to validate an email field that's generated by a CMS, but I'm getting a message that invalidEmailMsg is undefined. I have tried placing the variable declaration inside the function, outside the function, inside the if statement (basically flailing my arms around), but the message persists. Can anyone help? Please and thank you.
var email = document.getElementById("trouble-tickets-email");
email.addEventListener("keyup", function() {
var invalidEmailMsg = document.forms[1].getElementsByClassName("form-error-msg")[3];
var emailValue = email.value;
var emailPattern = /.+#.+\..+/;
if(emailPattern.test(emailValue) === false) {
invalidEmailMsg.css.style("display","block");
invalidEmailMsg.innerHTML = "custom message";
}
});