I am learning JavaScript and I’d like to see the written codes behind some of the functions and methods. I’ve been researching, but I don’t know where to look, and not typing the correct query in google – I’m guessing.
Category: javascript
Category Added in a WPeMatico Campaign
How to make a datepicker the minimum day in javascript
I want that the user can’t choose previous dates, I’m using the .min function but it doesn’t do anything. If you could help me.
function deshabilitarFechasAnterior(){
const inputFecha=document.querySelector('#fecha');
const fechaAhora= new Date();
const year=fechaAhora.getFullYear();
const mes=fechaAhora.getMonth()+1;
const dia=fechaAhora.getDate()+ 1;
const fechaDeshabilitar=`${year}-${mes}-${dia}`;
inputFecha.min=fechaDeshabilitar;
}
if select2 is null, make input field required
I have a text field and a select2 field. The user can input something in the input field, but can also select a predefined choice from the select2 field.
I want to do the following: if the select2 is selected, then the form goes through, if not, the input field will be required and the form cannot pass through.
I already made a logic in the backend (Django) that copies the value of the select2 to the text field just to make sure all data is valid, but if I leave the frontend without validation, the user could leave everything empty and submit an empty form.
Here’s my html:
<table id="myTable" class="table order-list">
<thead>
<tr>
<td>Médicament</td>
<td>Dosage</td>
<td>Posologie</td>
<td>Durée</td>
<td></td>
</tr>
</thead>
<tbody>
<tr>
<td class="col-5">
<div class="row">
<div class="col-6">
<input class="form-control mb-4" placeholder="Nom du médicament" type="text" name="medicament0">
</div>
<div class="col-6">
<div class="form-group">
<select class="form-control select2-show-search form-select" id="medicament-id0" name="listemedicament0">
<option value="0">Ou choisir de la liste</option>
{% for d in drugs %}
<option value="{{ d.id }}">{{ d }}</option>
{% endfor %}
</select>
</div>
</div>
</div>
</td>
<td>
<input class="form-control mb-4" placeholder="20mg" type="text" name="dosage0">
</td>
<td>
<input class="form-control mb-4" placeholder="2 / j avant repas" type="text" name="posologie0">
</td>
<td>
<input class="form-control mb-4" placeholder="7 jours" type="text" name="duree0">
</td>
<td><a class="deleteRow"></a>
<input type="button" class="btn btn-lg btn-secondary " id="addrow" value="Ajouter élément" />
</td>
</tr>
</tbody>
</table>
I also have this javascript to have a dynamic row adding if the user wants to submit multiple entries:
<script>
$(document).ready(function () {
var counter = 1;
$("#addrow").on("click", function () {
var newRow = $("<tr>");
var cols = "";
cols += '<td class="col-5"><div class="row"><div class="col-6">' +
'<input class="form-control medic-field mb-4" placeholder="Nom du médicament" type="text" name="medicament'+ counter +'">' +
'</div><div class="col-6"> <div class="form-group">' +
'<select class="form-control select2-show-search form-select" id="medicament-id0" name="listemedicament'+ counter +'">' +
'<option value="0">Ou choisir de la liste</option> {% for d in drugs %} <option value="{{ d.id }}">{{ d }}</option>' +
'{% endfor %} </select> </div></div></div>' +
'</td>' +
'<td><input class="form-control mb-4" placeholder="20mg" type="text" name="dosage'+ counter +'"></td>' +
'<td><input class="form-control mb-4" placeholder="2 / j avant repas" type="text" name="posologie'+ counter +'"></td>' +
'<td><input class="form-control mb-4" placeholder="7 jours" type="text" name="duree'+ counter +'"></td>' +
'<td><a href="javascript:void(0);"><i class="ibtnDel fa fa-2x fa-close" style="color: red;"></i></a></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
//Initialize Select2 Elements
$('.select2-show-search').select2();
$("table.order-list").append('<input type="hidden" name="counter" value="' + counter + '"/>');
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function (event) {
$(this).closest("tr").remove();
counter -= 1
});
});
</script>
These are the two fields:
<input class="form-control mb-4" placeholder="Nom du médicament" type="text" name="medicament0">
...
<select class="form-control select2-show-search form-select" id="medicament-id0" name="listemedicament0">
<option value="0">Ou choisir de la liste</option>
{% for d in drugs %}
<option value="{{ d.id }}">{{ d }}</option>
{% endfor %}
</select>
So my problem is if I leave the input (with id medicament-id0) empty, and the select field is not empty, the form goes through, if the select field is empty, then the input should be required.
Javascript – if statement not returning correct image from array (always behind) [duplicate]
I have an array of images:
const characterImages = ["images/jerry-senfeld.png", "images/george-costanza.png", "images/elaine-benes.png", "images/cosmo-kramer.png"]
I have another function which pulls some data from a basic API and updates a simple HTML page. An if statement looks at the innerHTML to determine which character is there and based on that, set the src attribute of an image. Everything is working as expected, however the image shown is always 1 index spot behind the quote. So for instance if they innerHTML of <h2> says “George” I can expect the jerry-seinfeld.png image to show. I have been going around in circles on this, any help would be appreciated. Code below.Thank you!
//Define our variables
const headerTag = document.querySelector("h2");
const quoteTag = document.querySelector(".quote");
let characterImage = document.querySelector(".characterImage");
const characterImages = [
"images/jerry-senfeld.png",
"images/george-costanza.png",
"images/elaine-benes.png",
"images/cosmo-kramer.png",
];
var x;
const getQuote = () => {
fetch("https://seinfeld-quotes.herokuapp.com/quotes")
.then((response) => response.json())
.then((jsonData) => {
quoteTag.innerHTML = jsonData.quotes[x].quote;
headerTag.innerHTML = jsonData.quotes[x].author;
});
};
// images function to go below:
const getImage = () => {
if (headerTag.innerHTML == "Jerry") {
characterImage.setAttribute("src", characterImages[0]);
} else if (headerTag.innerHTML == "George") {
characterImage.setAttribute("src", characterImages[1]);
} else if (headerTag.innerHTML == "Elaine") {
characterImage.setAttribute("src", characterImages[2]);
} else if (headerTag.innerHTML == "Kramer") {
characterImage.setAttribute("src", characterImages[3]);
} else {
characterImage.setAttribute("src", "images/placeholder-image.png");
}
};
document.querySelector("button").addEventListener("click", function (event) {
x = Math.floor(Math.random() * 422);
getQuote();
getImage();
});
HTML (relevant parts):
<div class="main-quote">
<h2></h2>
<img src="images/placeholder-image.png" class="characterImage" alt="character image">
<p class="quote"></p>
<button class="button2">Click!</button>
</div>
React JSX rendering with map
I’m attempting to return content dynamically using the map() method in React. usersList is an array of objects.
return (
<div>
{usersList.map((user) => {
return (
<div>
<h1>{user.username}</h1>
<h2>{user.age}</h2>
</div>
);
})}
</div>
);
However, nothing is showing up as output. What am I doing wrong here? Help is very much appreciated.
Geological articles on Data Science
looking for scientists interested in developing a microfossil analyzer and scanning electron microscope images? Opportunity for all types of programming language
How can I wait for server response?
Inside a method (code below) I am trying to set an array of strings called ‘outerURL’ in the promise. and when the promise is resolved, I am pushing the values of ‘outerURL’ to an array called ‘tableValues’ to be displayed in a .pdf.
When I try to download the .pdf file in the first attempt after the page loads, I get ‘undefined’ in the place where the content of ‘outerURL’ should be displayed. When I try to download the .pdf file the second time, I can see the ‘outerURL’ content are being displayed.
In the first attempt to download the .pdf it seems the method is returning ‘filePrintList’ before the promise completes and by the second time I download the .pdf, the promise is already completed and ‘outerURL’ values are set.
My question is, how can I wait for the promise to finish before returning ‘filePrintList’?
Below is my code:
let promise = new Promise((resolved, rejected) => {
this.fileDetails.forEach(async file => {
const rowValue: any = [];
this.coreService.viewFileNew(file, false).subscribe(
fileData => {
this.showProgress(false);
if (fileData.size > 0) {
const url = URL.createObjectURL(fileData);
this.outerURL.push(url);
} else {
file.isActive = false;
}
},
err => {
console.log(err);
}
);
});
resolved(this.outerURL);
});
promise.then(urls => {
urls.forEach(url => {
rowValue[this.FILE_PRINT_TABLE_COLUMN_NAME] = value;
rowValues.push(rowValue);
tableValues.push(url);
});
});
fileTableList.rowDataList = rowValues;
fileTableList.tableListData = tableValues;
fileTableHeaderList.push(fileTableList);
fileTable.tableList = fileTableHeaderList;
fileTables.push(fileTable);
filePrintList.tableList = fileTables;
return filePrintList;
How can I count a PWA app number of users
I’ve been building a web app which will be served to users via a native webview. I have been using This monitoring Tool to monitor visits and page views but it really does not provide the stats that I need, which is the real number of people actually using my app.
I think, If I could create a js code and serve it withing the index page of the app, so this js code can collect some unique device “something” and create a database with that info, so, everytime a user uses the app this same js code, or something else, could recieve that unique device “somethig” and compare it to the database, if it already exists is not counted as a new user as it has been counted before. But if it does not exist then it would be a new user.
I must state that the app would be hosted on a shared hosting and the webiew app will not be at Google Play but delivered to users in different ways. So, what I really need to know is:
1- Is it the logic I am using correct? Can it be done?
2- Which could be that unique device “something” other than IMEI, phone number or unique device ID?
I know it’s not the usually accepted kind of question used to post here but I do not want to dive into some coding without beeing sure it will be usefull. So, depending on the answers I would try it out in practice and reshape this question to fit the Site’s guidelines.
Thank you all in advance.
Why is this function working on second click only?
I have a simple function that hides text on click. However it only works on the second click. I tried rewording the conditional statement but nothing has worked so far. jsfiddle https://jsfiddle.net/Montinyek/293hmpu1/18/
let btn = document.getElementById('btn');
let hello = document.getElementById('hello');
function test() {
if (hello.style.display !== 'block') {
hello.style.display = 'block';
} else {
hello.style.display = 'none';
}
}
btn.addEventListener('click', test)
<div id='hello'>
hello
</div>
<div id='btn'>
button
</div>
How to fix this “Uncaught SyntaxError:”?
I keep getting the following error:
Uncaught SyntaxError: Unexpected token u in JSON at position 1
at JSON.parse ()
at script.js:9:18
Here is my code:
const num1 = Math.ceil(Math.random() * 10);
const num2 = Math.ceil(Math.random() * 10);
const questionE1 = document.getElementById("question");
const inputE1 = document.getElementById("input");
const formE1 = document.getElementById("mult-form");
const scoreE1 = document.getElementById("score");
let score = JSON.parse(localStorage.getItem("score"));
if (!score) {
score = 0;
}
scoreE1.innerText = `score: ${score}`;
questionE1.innerText = `What is ${num1} multiplied by ${num2}?`;
const correctAns = num1 * num2;
formE1.addEventListener("submit", () => {
const userAns = +inputE1.value;
if (userAns === correctAns) {
score++;
updateLocalStorage();
} else {
score--;
updateLocalStorage();
}
});
function updateLocalStorage() {
localStorage.setItem("score", JSON.stringify(score));
}
The issue is with this line:
let score = JSON.parse(localStorage.getItem("score"));
Insert element in specific index of dynamic array with different lengths
Excuse the beginners question, I am still very new to javascript.
Background:
I am building a chart that needs to have 2 different arrays but their length must match. In order to get these arrays to match in length, I need to determine values that match and values that don’t using dates (this is already accomplished – just giving insight!)
Problem:
I need to create a new array that has the same length as array 2 (example below), while keeping the existing data from array 1.
For example:
The array that I want to append to looks something like this:
[1, 5, 10, 35, ...etc]
And has a length of 20.
The other array (the one where I’ve mapped values that match/do-not) looks like this:
[{date, matched: false}, {date, matched: true}, {date, matched: true}, {date, matched: false}, ...etc]
And has a length of 30.
Basically, what I am trying to do is for every value where matched = false, I wish to insert a 0 in the first array (or create a new array where the value = 0). However, where matched is true, I wish to keep the existing value in the first array.. I am struggling with using loops as the lengths and indexes are different amongst the two.
Can anyone please provide some insight on how to achieve this?
Thanks! 😀
put notification in site navbar with javascript when something happens on a certain page
I created a code that checks if there is an element on one of the pages of my site and creates an element with createElement, in this script a notification (badge) is created in the navbar. The problem is that the notification only appears when I’m on this page, does anyone know a way to put it in the navbar of all other pages?
the script:
if ( $( "#noti" ).length ){
var noti = document.createElement("span");
var icon = document.createElement("i");
noti.appendChild(icon);
document.getElementById("ticket").appendChild(noti) ;
noti.classList.add("badge");
icon.classList.add("far") ;
icon.classList.add("fa-bell");
};
I’ve tried to solve it with the iframe leaving its display at none, but I couldn’t.
Video is playing in chrome,but it is not playing in safari browser
I have 2 videos as a background / z-index = 1.
2 columns divided the screen in 50/50 ratio z-index = 3. if mouse is hovering over first column, then first video is playing in background, when mouse is hovering in second column, first video is hidden and second video is playing in background.
It is working in CHROME browser, but it is not working in safari-doesnt play video nor sound.
Can you show me how to fix it please?
// html
<video src="video1.mp4" width="100%" data-id="1" class="video1" type="video/mp4" autoplay="true"></video>
<video src="video2.mp4" data-id="2" width="100%" class="hiddn video2" type="video/mp4" autoplay="true"></video>
// js
const boxes = document.querySelectorAll('.boxes')
const video1 = document.querySelector('.video1')
const video2 = document.querySelector('.video2')
boxes.forEach( box => {
box.addEventListener('mouseover', (e)=> {
e.preventDefault()
const a = e.currentTarget.dataset.set
console.log(a)
if (a === '1') {
var promise1 = video1.play();
if (promise1 !== undefined) {
promise1.catch(error => {
console.log(error);
}).then(() => {
video1.classList.remove('hiddn')
video2.classList.add('hiddn')
video2.pause()
})}
} else if(a ==='2'){
var promise2 = video2.play();
if (promise2 !== undefined) {
promise2.catch(error => {
console.log(error);
}).then(() => {
video1.classList.add('hiddn')
video1.pause()
video2.classList.remove('hiddn')
})}
}
})
})
I try to delete a targeted element front-end side and have it removed from the db as well but doesn’t work [Vue.js + vuetify + firestore]
I created a to-do list kind of app that is connected to a db on firestore.
I have a form that adds a new document to the list, both front-end and db and it works,
I have a method that listens to the changes in the db and updates the document in the browser and it works.
So I see that I manage to refer to the collection in the db and save it in variables, but it is only reactive to deleting documents if I do it manually from firebase website.
Here is the method that I am trying to use
removeObject(id){
const db = getFirestore(app);
console.log("test")
deleteDoc(doc(db, "Listify", doc(id));
}
And here is the way I’m calling it in HTML
<v-card flat v-for="project in projects" :key="project.id">
<v-layout row justify-end wrap :class="`pa-3 project ${project.status}`">
...
...
<v-flex xs6 sm4 md2 class="text-center-xs">
<div class="right text-center">
<v-chip small :class="`${project.status} white--text caption my-2`"> {{project.status}}</v-chip>
<v-btn flat fab small dark class="red" @click="removeObject(project.id)">
<v-icon small class="pa-0">delete</v-icon>
</v-btn>
</div>
</v-flex>
</v-layout>
<v-divider></v-divider>
</v-card>
I tried to refer to the doc id in the method in many ways, but it only works when I hard code the id for that document, and even in that case it deletes the last item of the array “projects” that I defined in the data section of the app, and then when I refresh the page, that last item comes back and the one with the id that I hardcoded is actually deleted.
I tried calling “removeObject(id)” as async and use await on “deleteDoc(…..)”
but still does not work,
I thought about looping the collection but I would not know the right way to do it,
and finally in firebase official repo in githhub I only found this syntax "await deleteDoc(doc(db, "cities", "DC"));"
Which did not help me as it only works with specific Ids or doc names;
How could I delete, clicking on the button that calls the delete method, remove that specific item I targeted both client and db side?
What is the Comment (native) function?
In console, in both Firefox and Chrome, typing Comment outputs
ƒ Comment() { [native code] }
What is it?