Category: javascript
Category Added in a WPeMatico Campaign
How to update data based on select options in a React component?
I am encountering a problem in my code where I am creating a calculator which calculates the electricity consumption by appliances and suggesting them that which capacity of solar system will work for them. So the issue is I aim to map wattages onto my React component. However, I am unsure how to achieve this. I have attempted various methods, but I am only able to map using a specific index number (By hard coating the index number). What I desire is for the mapping to automatically update when a user switches the option.
App screenshot for better understanding
Here is the code which I have written…
The part where I am mapping the wattages
{Object.entries(summary).map(([applianceName, quantity]) => (
<p key={applianceName} className="text-sm">
{quantity *
appliances.appliances.find((a) => a.name === applianceName)
.options[0].wattage}
w
</p>
))}
And here is the select and input part
<select
name={`${applianceName}-type`}
id={applianceName}
className="p-1 border-2 border-gray-400 rounded-md ml-2 text-xs"
onChange={handleQuantityChange}
>
<option value="select">Please Select {applianceName} Type</option>
{applianceTypes.map((type) => (
<option key={type} value={type}>
{type}
</option>
))}
</select>
<input
type="number"
placeholder={`Enter ${applianceName} Quantity`}
min={0}
className="p-1 border-2 border-gray-400 rounded-md ml-2 text-xs"
onChange={handleQuantityChange}
/>
And just for the reference here is the Json data
"appliances": [
{
"name": "Fan",
"options": [
{ "option": "AC (110w)", "wattage": 110 },
{ "option": "DC (55w)", "wattage": 55 },
{ "option": "Inverter (30w)", "wattage": 30 }
]
},
{
"name": "Tube Light",
"options": [
{ "option": "18w", "wattage": 18 },
{ "option": "24w", "wattage": 24 },
{ "option": "36w", "wattage": 36 }
]
},
{
"name": "Led Bulb",
"options": [
{ "option": "5w", "wattage": 5 },
{ "option": "7w", "wattage": 7 },
{ "option": "12w", "wattage": 12 },
{ "option": "15w", "wattage": 15 },
{ "option": "18w", "wattage": 18 }
]
}
]
Now I’m not getting that how can I proceed
Need help on Python Web Application
I am currently building a project and running into issue that i can’t resolve. Im unable to update the totalSales content correctly and require help. This is a Web application that uses Flask, javascript and sqlite database. There are 2 buttons on the web. “SELL” which sells the hammers at a certain price. “Buyback” which buys back the hammer at 0.75 * initial cost. For when example when you sell a hammer at $5 and use the buyback feature it should subtract $5 – 3.75 and you have a left over of 1.25.
Models.py
from app import db
class Hammer(db.Model):
id = db.Column(db.Integer, primary_key=True)
type = db.Column(db.String(120), nullable=False)
price = db.Column(db.Float, nullable=False)
sold = db.Column(db.Integer, default=0)
class Buyback(db.Model):
id = db.Column(db.Integer, primary_key=True)
hammer_id = db.Column(db.Integer, db.ForeignKey('hammer.id'), nullable=False)
buyback_price = db.Column(db.Float, nullable=False)
timestamp = db.Column(db.DateTime, default=db.func.current_timestamp())
#create a string
def __repr__(self):
return '<Buyback {}>'.format(self.id)
backend:
from flask import request, jsonify, render_template
from . import app, db
from .models import Hammer, Buyback
@app.route("/")
def home():
return render_template("index.html") # Assuming you have an index.html template
@app.route("/hammers", methods=["POST"])
def add_hammer():
data = request.get_json()
hammer = Hammer(type=data["type"], price=data["price"])
db.session.add(hammer)
db.session.commit()
return jsonify(hammer_id=hammer.id), 201
@app.route("/hammers/<int:id>/sell", methods=["POST"])
def sell_hammer(id):
hammer = Hammer.query.get_or_404(id)
hammer.sold = 1 #mark the hammer as sold
# Check if there's an existing buyback entry for this hammer
buyback_entry = Buyback.query.filter_by(hammer_id=id).first()
if buyback_entry:
# If an entry exists, delete it from the database
db.session.delete(buyback_entry)
db.session.commit() # Commit changes to the database
return jsonify({"success": True}), 200
@app.route("/hammers/<int:id>/buy", methods=["POST"])
def buy_it_back(id):
hammer = Hammer.query.get_or_404(id)
if hammer.sold:
buyback_price = 0.75 * hammer.price
hammer.sold = 0 # Mark as not sold
#record buy buy back transactions
buyback = Buyback(hammer_id=hammer.id, buyback_price=buyback_price )
db.session.add(buyback)
db.session.commit()
return jsonify({"success": True, "buyback_price": buyback_price}), 200
else:
return jsonify({"error": "Hammer not sold, cannot buy back"}), 400
@app.route("/hammers", methods=["GET"])
def list_hammers():
hammers = Hammer.query.all()
hammer_list = [
{
"id": hammer.id,
"type": hammer.type,
"price": hammer.price,
"sold": hammer.sold,
}
for hammer in hammers
]
return jsonify(hammers=hammer_list)
@app.route("/buybacks", methods=["GET"])
def list_buybacks():
buybacks = Buyback.query.all()
buyback_list = [
{
"id": buyback.id,
"hammer_id": buyback.hammer_id,
"buyback_price": buyback.buyback_price,
"timestamp": buyback.timestamp
}
for buyback in buybacks
]
return jsonify(buybacks=buyback_list)
@app.errorhandler(500)
def handle_500(error):
return jsonify({"error": "Internal server error"}), 500
frontend:
// Utility Functions
function sellHammer(id) {
fetch('/hammers/' + id + '/sell', { method: 'POST' })
.then(response => response.json())
.then(data => {
console.log('Success:', data);
loadHammers();
})
.catch((error) => {
console.error('Error:', error);
});
}
function buyHammer(id) {
fetch('/hammers/' + id + '/buy', { method: "POST" })
.then(response => response.json())
.then(data => {
console.log("Buyback Success: ", data);
loadHammers();
})
.catch((error) => {
console.error('Error:', error);
});
}
// Utility Functions
function list_buybacks(hammerId) {
fetch('/buybacks')
.then(response => response.json())
.then(data => {
const buybacks = data.buybacks;
const filteredBuybacks = buybacks.filter(buyback => buyback.hammer_id === hammerId);
// Assuming you have a way to display these filtered buybacks. For simplicity, logging them:
console.log('Buybacks for hammer ' + hammerId + ':', filteredBuybacks);
// Here you could update the UI to display these buybacks, perhaps in a modal or a dedicated section next to the hammer.
})
.catch((error) => {
console.error('Error:', error);
});
}
function calculateTotalSales(hammers, buybacks) {
let totalSales = 0;
// Add to total sales for each sold hammer
hammers.forEach(hammer => {
if (hammer.sold) {
totalSales += parseFloat(hammer.price);
}
});
// Deduct from total sales for each buyback, but only if the hammer was previously sold
buybacks.forEach(buyback => {
// Find the hammer related to the buyback
const soldHammer = hammers.find(hammer => hammer.id === buyback.hammer_id);
// Deduct only if the hammer has been sold before
if (soldHammer && soldHammer.wasSold) {
totalSales -= parseFloat(buyback.buyback_price);
}
});
return totalSales;
}
function loadHammers() {
Promise.all([
fetch('/hammers').then(response => response.json()),
fetch('/buybacks').then(response => response.json())
]).then(([hammersData, buybacksData]) => {
const hammers = hammersData.hammers;
const buybacks = buybacksData.buybacks;
const tableBody = document.getElementById('hammersTable').getElementsByTagName('tbody')[0];
// Clear the table before repopulating it
tableBody.innerHTML = '';
// Update wasSold status based on buybacks
hammers.forEach(hammer => {
hammer.wasSold = hammer.sold || buybacks.some(buyback => buyback.hammer_id === hammer.id);
});
// Populate the table with hammers
hammers.forEach(hammer => {
const row = tableBody.insertRow();
row.insertCell(0).innerText = hammer.id;
row.insertCell(1).innerText = hammer.type;
row.insertCell(2).innerText = hammer.price;
row.insertCell(3).innerText = hammer.sold ? 'Yes' : 'No';
const actionCell = row.insertCell(4);
const sellButton = document.createElement('button');
sellButton.innerText = 'Sell';
sellButton.className = 'btn btn-success';
sellButton.onclick = () => sellHammer(hammer.id);
sellButton.disabled = hammer.sold;
actionCell.appendChild(sellButton);
const buybackButton = document.createElement('button');
buybackButton.innerText = 'Buy It Back';
buybackButton.className = 'btn btn-primary';
buybackButton.onclick = () => buyHammer(hammer.id);
buybackButton.disabled = !hammer.sold;
actionCell.appendChild(buybackButton);
});
// Calculate and display total sales
const totalSales = calculateTotalSales(hammers, buybacks);
document.getElementById('totalSales').innerText = `Total Sales: $${totalSales.toFixed(2)}`;
}).catch((error) => {
console.error('Error:', error);
});
}
// Initializes form submission event and loads hammers
function initApplication() {
// Setup form submission handler
document.getElementById('addHammerForm').addEventListener('submit', (e) => {
e.preventDefault();
const hammerType = document.getElementById('hammerType').value;
const hammerPrice = document.getElementById('hammerPrice').value;
fetch('/hammers', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ type: hammerType, price: hammerPrice }),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
loadHammers();
document.getElementById('addHammerForm').reset();
})
.catch((error) => {
console.error('Error:', error);
});
});
loadHammers();
}
// Execute the initialization function when the window is fully loaded
// This ensures that the DOM is fully loaded before attaching event listeners and executing initial functions.
window.onload = initApplication;
challenges issues
not sure if this is the righ place to ask this but I am stuck on two code challenges. One is called Which Repo? I have an error, see screenshot
see screenshot, this is the error I am not able to sort “should return the repo name from a URL with extra information
✕ AssertionError: expected ‘settings’ to equal ‘fe-katas'”
Handling Asynchronous Responses in Authentication Flow with React and Polling
I’m struggling with an authentication flow in a React application, which involves interacting with an external service. Here’s the process:
The user clicks a “load” button, which fetches an HTML from an external service. This HTML is a form with username and password fields, and a submit button.
The form is then loaded into an iframe within my React component.
Upon form submission, the application is supposed to “listen” for changes in the iframe response.
I need to detect these changes in response and extract values, specifically to determine if the operation has finished and if it has been approved.
Currently, I have a polling system that periodically checks the status of the operation by making requests to the backend. Although I have seen in the network tab of the browser that sometimes the backend responds with {“approved”:true,”operacionFinalizada”:true,”TransactionIdentifier”:”890826″}, the component does not react to this change as it should.
The catch is that I can’t modify the backend since it is an external service, so my solution has to be entirely on the frontend.
Here is the code for my React component where the polling takes place:
function App() {
const [iframeContent, setIframeContent] = useState('');
const [transactionIdentifier, setTransactionIdentifier] = useState('');
const [openModalPreAutorizacion, setOpenModalPreAutorizacion] = useState(false);
const [openModal, setOpenModal] = useState(false);
const [polling, setPolling] = useState(false);
// UseEffect to handle polling
useEffect(() => {
// If polling is true, set an interval to fetch the transaction status every second
const interval = polling ? setInterval(() => {
fetchTransactionStatus();
}, 1000) : null;
// Clean-up function to clear the interval when the component is unmounted or polling is stopped
return () => {
if (interval) {
clearInterval(interval);
}
};
}, [polling]); // Dependency array to re-run the effect when the polling state changes
// Function to handle the button click event
const handleButtonClick = async () => {
console.log('Load button clicked.'); // Log button click
try {
const response = await axios.post('http://localhost:8080'); // Post request to backend
console.log('Complete form response:', response); // Log the complete form response
const { RedirectData } = response.data; // Destructure RedirectData from the response
setIframeContent(RedirectData); // Set the iframe content with the RedirectData
setPolling(true); // Start the polling process
} catch (error) {
console.error('There was an error!', error); // Log error if the request fails
}
};
// Function to fetch the transaction status
const fetchTransactionStatus = async () => {
try {
console.log('Making request to verify the operation status.'); // Log status check
const response = await axios.post("http://localhost:8080/auth"); // Post request to check auth status
const { operacionFinalizada, approved, TransactionIdentifier } = response.data; // Destructure the response data
console.log(`Response received: ${JSON.stringify(response.data)}`); // Log the received response
// If the operation is finished
if (operacionFinalizada) {
console.log('Operation finished detected.'); // Log the completion of the operation
setTransactionIdentifier(TransactionIdentifier); // Set the transaction identifier state
setPolling(false); // Stop polling
// If the operation is approved
if (approved) {
console.log('Operation approved.'); // Log approval
setOpenModalPreAutorizacion(true); // Open pre-authorization modal
} else {
console.log('Operation not approved.'); // Log disapproval
setOpenModal(true); // Open the operation not approved modal
}
}
} catch (error) {
console.error('Error during polling:', error); // Log error during polling
setPolling(false); // Stop polling in case of error
}
};
// ... rest of the component
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>Edit <code>src/App.js</code> and save to reload.</p>
<button onClick={handleButtonClick}>Carga</button>
<iframe
title="Response Frame"
srcDoc={iframeContent}
style={{ width: '600px', height: '400px', border: '1px solid black', marginTop: '20px' }}
/>
{openModalPreAutorizacion && <div>Modal Resp.</div>}
{openModal && <div>Modal op NO apr</div>}
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;
And this is the backend function I’m polling (I can’t change this, but include it to give full context):
func loginHandler(w http.ResponseWriter, r *http.Request) {
// Define los valores que quieres enviar
response := Response{
TransactionType: 1,
Approved: false,
TransactionIdentifier: "c306aca4-47ef-412f-b894-3a4cd8a667ef",
IsoResponseCode: "SP4",
ResponseMessage: "SPI Preprocessing complete",
OrderIdentifier: "24000974",
RedirectData: `<html>
<head></head>
<body>
<form id='login_form'>
Username: <input type='text' name='username' id='username'><br>
Password: <input type='password' name='password' id='password'><br>
<input type='submit' value='Submit'>
</form>
<iframe id="response_frame" style="width:100%; height:200px;"></iframe>
<script>
document.getElementById('login_form').onsubmit = function(event) {
event.preventDefault(); // Prevenir el comportamiento por defecto de envío del formulario
// Capturar los valores de username y password
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
// Ocultar el formulario
document.getElementById('login_form').style.display = 'none';
// Codificar los datos para x-www-form-urlencoded
var formData = new URLSearchParams();
formData.append('username', username);
formData.append('password', password);
// Realizar una petición POST a /auth
fetch('http://localhost:8080/auth', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: formData
})
.then(response => response.json())
.then(data => {
// Convertir la respuesta JSON en una cadena para mostrarla en el iframe
var formattedData = JSON.stringify(data, null, 2); // Indenta para mejorar la legibilidad
document.getElementById('response_frame').srcdoc = '<pre>' + formattedData + '</pre>';
})
.catch((error) => {
console.error('Error:', error);
// Mostrar nuevamente el formulario en caso de error
document.getElementById('login_form').style.display = 'block';
document.getElementById('response_frame').srcdoc = '<p>Error: ' + error + '</p>';
});
};
</script>
</body>
</html>`,
SpiToken: "3578590rc9cmcw09t4ms5w846hdvkcr2tyazs3bwz0envwt0pr-3plyg9wt7wz",
}
// Establece la cabecera Content-Type a application/json
w.Header().Set("Content-Type", "application/json")
// Codifica la respuesta en JSON y la envía
json.NewEncoder(w).Encode(response)
}
func authHandler(w http.ResponseWriter, r *http.Request) {
// Asegúrate de que estamos recibiendo una solicitud POST
if r.Method != http.MethodPost {
http.Error(w, "Método no permitido", http.StatusMethodNotAllowed)
return
}
// Parsea el cuerpo de la solicitud
err := r.ParseForm()
if err != nil {
http.Error(w, "Error al parsear formulario", http.StatusBadRequest)
return
}
// Obtén los valores del usuario y la contraseña
username := r.FormValue("username")
password := r.FormValue("password")
log.Printf("Username: %sn", username)
log.Printf("Password: %sn", password)
// Crea la respuesta basada en las credenciales o la falta de ellas
var response AuthResponse
if username == "" || password == "" {
// En vez de enviar un error HTTP, envía una respuesta válida que indica la falta de parámetros
response = AuthResponse{Approved: false, OperacionFinalizada: false, TransactionIdentifier: ""}
} else if username == "Nico" && password == "123" {
response = AuthResponse{Approved: true, OperacionFinalizada: true, TransactionIdentifier: "890826"}
} else {
response = AuthResponse{Approved: false, OperacionFinalizada: true, TransactionIdentifier: ""}
}
// Establece la cabecera Content-Type a application/json
w.Header().Set("Content-Type", "application/json")
// Codifica la respuesta en JSON y la envía
json.NewEncoder(w).Encode(response)
}
My question is: How can I make my React component recognize and handle changing backend responses during polling to update the component’s state according to the authentication operation data?
I implemented a polling mechanism in my React application to check the status of a backend operation. The frontend should make a request every second, and when the backend operation is finished and approved, it should stop polling and update the UI accordingly.
After clicking the “Load” button, the frontend starts polling the backend for the status of the operation.
When the backend returns operacionFinalizada: true and approved: true, I expect the frontend to stop polling and show a pre-authorization modal.
If the operation is finished but not approved (approved: false), I expect it to show a “not approved” modal.
What actually happened:
The frontend starts polling as expected after the button click.
When the backend operation completes (I can see the correct response in the Network tab of the browser’s developer tools), the frontend does not seem to recognize this change. It does not stop polling or show any modal.
The responses from the backend when the operation is not finished look exactly the same as when it is finished, making it impossible to distinguish from the frontend if the operation has actually completed.
I am looking for suggestions to ensure that the frontend correctly recognizes the change in the backend response and updates the UI accordingly.
Chart.js V4 Toggle each bar in chart while having different labels under each bar. How?
I am trying to create a barchart with several different datasets but I’m struggling with getting labels below each bar. This is what I currently have.

I want to have labels below the bars as well, not just in the legend. Below is my data var.
{
"labels": [
""
],
"datasets": [
{
"label": "testname1",
"borderColor": "rgba(254, 112, 150, 1)",
"backgroundColor": "rgba(254, 112, 150, 1)",
"borderWidth": 1,
"categoryPercentage": 1,
"data": [
58
]
},
{
"label": "testname2",
"borderColor": "rgba(54, 215, 232, 1)",
"backgroundColor": "rgba(54, 215, 232, 1)",
"borderWidth": 1,
"categoryPercentage": 1,
"data": [
60
]
},
{
"label": "testname3",
"borderColor": "rgba(6, 185, 157, 1)",
"backgroundColor": "rgba(6, 185, 157, 1)",
"borderWidth": 1,
"categoryPercentage": 1,
"data": [
21
]
},
{
"label": "testname4",
"borderColor": "rgba(242, 197, 124, 1)",
"backgroundColor": "rgba(242, 197, 124, 1)",
"borderWidth": 1,
"categoryPercentage": 1,
"data": [
35
]
},
{
"label": "testname5",
"borderColor": "rgba(54,70,82, 1)",
"backgroundColor": "rgba(54,70,82, 1)",
"borderWidth": 1,
"categoryPercentage": 1,
"data": [
32
]
},
{
"label": "testname6",
"borderColor": "rgba(68, 94, 147, 1)",
"backgroundColor": "rgba(68, 94, 147, 1)",
"borderWidth": 1,
"categoryPercentage": 1,
"data": [
75
]
},
{
"label": "testname7",
"borderColor": "rgba(143, 57, 133, 1)",
"backgroundColor": "rgba(143, 57, 133, 1)",
"borderWidth": 1,
"categoryPercentage": 1,
"data": [
5
]
},
{
"label": "testname8",
"borderColor": "rgba(255, 209, 102, 1)",
"backgroundColor": "rgba(255, 209, 102, 1)",
"borderWidth": 1,
"categoryPercentage": 1,
"data": [
0
]
},
{
"label": "testname9",
"borderColor": "rgba(67, 129, 193, 1)",
"backgroundColor": "rgba(67, 129, 193, 1)",
"borderWidth": 1,
"categoryPercentage": 1,
"data": [
42
]
},
{
"label": "testname10",
"borderColor": "rgba(135, 61, 72, 1)",
"backgroundColor": "rgba(135, 61, 72, 1)",
"borderWidth": 1,
"categoryPercentage": 1,
"data": [
76
]
},
{
"label": "testname11",
"borderColor": "rgba(42, 71, 71, 1)",
"backgroundColor": "rgba(42, 71, 71, 1)",
"borderWidth": 1,
"categoryPercentage": 1,
"data": [
75
]
},
{
"label": "testname12",
"borderColor": "rgba(237, 191, 133, 1)",
"backgroundColor": "rgba(237, 191, 133, 1)",
"borderWidth": 1,
"categoryPercentage": 1,
"data": [
34
]
},
{
"label": "testname13",
"borderColor": "rgba(187, 40, 55, 1)",
"backgroundColor": "rgba(187, 40, 55, 1)",
"borderWidth": 1,
"categoryPercentage": 1,
"data": [
59
]
},
{
"label": "testname14",
"borderColor": "rgba(115, 92, 221, 1)",
"backgroundColor": "rgba(115, 92, 221, 1)",
"borderWidth": 1,
"categoryPercentage": 1,
"data": [
98
]
},
{
"label": "testname15",
"borderColor": "rgba(144, 0, 179, 1)",
"backgroundColor": "rgba(144, 0, 179, 1)",
"borderWidth": 1,
"categoryPercentage": 1,
"data": [
64
]
}
]
}
This is my options
{
"scales": {
"y": {
"ticks": {
"display": true
}
},
"x": {
"display": false
}
},
"plugins": {
"legend": {
"display": {
"displayLegend": true
},
"position": "top"
},
"tooltip": {
"callbacks": {}
},
"elements": {
"point": {
"radius": 0
}
}
}
}
I can manage to add the labels below the columns if I make it all 1 dataset but then all columns are the same color and you cant toggle them.
I also tried this link Chart.js manipulate each bar in chart with different labels. But this is for version two of chartjs and doesnt work in the current version anymore. The paths in the beforelayout plugin keep returning cant set on undefined and when I did find xAxes in the chart object it was undefined.
Does anyone know how to get labels under my barchart columns without making it all one dataset?
chrome tab id using puppeteer
In Linux servers I use Puppeteer with stable version of Google-Chrome, How Can I rename a tab or asign it an identifier to reuse it instead open another tab for the same page?
I should try some flag or use some code to achieve it?
if Angular signals are getter functions, why can we call them?
Take a look at the following commented code:
export class AppComponent {
count = 0
// our getter function
get itscount() {
return this.count
}
// setting a function equal to a getter function
itsCount2 = this.itscount
func() {
// this.itsCount2() --> error
this.itsCount2 // --> works fine
}
}
Now taking a look at Angular signals, which are also getter functions, we call them () which contradicts the previous example.
count = signal(0)
func() {
console.log(this.count) // returns the function reference
console.log(this.count()) // returns 0
}
Can anyone explain exactly why signals are getter functions if we call them like we call normal functions?
Any explanation would be great!
When I run a function to try and count the words in a text area, the function does not run
I have a function that counts words in a text area box(written in html), but when I try and run the function, though javascript or html, it does not run. I am new to javascript, so I might be missing something obvious.
I tried using onkeyup in my html file, but it doesnt run the function, and when i try it in my js file, it doesnt run either. Here is my js:
let textarea = document.getElementById("myWordsToCount").innerHTML;
textarea.onkeyup = function () {
let words = document.getElementById("myWordsToCount").value;
let count = 0;
let split = words.split(' ');
for (let i = 0; i < split.length; i++) {
if (split[i] != "") {
count += 1;
}
}
count = document.getElementById("wordcount").value;
}
Here is the HTML for the text area:
<p><textarea id="myWordsToCount" onkeyup="textarea()" rows="5" cols="60"></textarea><br>
Planning calendar appointments aggregation binding issue with filters
With the initial filters the planning calendar is loading with correct data for the first time. After the planningcalendar is loaded, when I try to filter with other fields, the appointments are not showing. The title field of the filtered value is correctly binding but not its corresponding appointments.
<rows>
<PlanningCalendarRow key="{ergGanttModel>Groupid}" id="PCRow" title="{ergGanttModel>Groupdesc}" appointments="{path : 'ergGanttModel>GRP_TO_STUFE/results/', templateShareable: false}">
<appointments>
<unified:CalendarAppointment title="{ergGanttModel>ObjectShortid}" text="{path : 'ergGanttModel>Shorttext'}" startDate="{path: 'ergGanttModel>IhstufDatum', formatter: '.formatter.StartDate'}" description="{ergGanttModel>Pvid}" key="{ergGanttModel>DbKey}" endDate="{path: 'ergGanttModel>IhstufDatum', formatter: '.formatter.EndDate'}">
<unified:customData>
<core:CustomData key="Sessionid" value="{AppGlobalModel>/SessionID}" />
</unified:customData>
</unified:CalendarAppointment >
</appointments>
</PlanningCalendarRow>
</rows>
Appointemts_Load: function (filters, SearchLoad) {
var that = this;
var requestUrl = "/IHSTU_GRPSet";
var onSuccess = function (data, response) {
ergGanttModel.setSizeLimit(10000);
this.getView().getModel().refresh();
ergGanttModel.setData(data.results);
this.getView().setModel(ergGanttModel, "ergGanttModel");
if (data.results.length > 0) {
for (var lv_stufgrp = 0; lv_stufgrp < data.results.length; lv_stufgrp++) {
if (this.getModel("ergGanttModel").oData[lv_stufgrp].GRP_TO_STUFE.results.length > 0) {
this.getModel("AppGlobalModel").setProperty("/SessionID", this.getModel("ergGanttModel").oData[lv_stufgrp].GRP_TO_STUFE.results[
0].Sessionid);
}
}
}
this.AppGlobalModel.setProperty("/BusyIndicator", false);
}.bind(this);
var onError = function () {
this.AppGlobalModel.setProperty("/BusyIndicator", false);
}.bind(this);
var parameter = {
filters: filters,
urlParameters: {
"$expand": "GRP_TO_STUFE"
},
success: onSuccess,
error: onError
};
this.PlanningViewModel.read(requestUrl, parameter);
},
tabulatotr, how can I Add data from the row to the context menu?
var rowMenu = [
{
label:row.getData().fname +" " + row.getData().lname,
disabled:true
},
{ separator:true },
{...
Using JS tabulator, This is not working, since it doesn’t know row element when building the menu.
How can it solved? Thanks
Full calendar module throws unexpected error randomly and events disappear
I was working on full calendar module. I am observing an issue where events disappear randomly sometimes below is my code
let calendar = new FullCalendar.Calendar(calendarelement, {
events: function (info, successCallback, failureCallback) {
$element.trigger(refreshevent, {
start_time: info.start.valueOf(),
end_time: info.end.valueOf(),
success: function (data) {
var eventsObject = data.parameters[0].events;
return successCallback(eventsObject);
}
});
}
Here I use start_time and end_time parameters to pass to backend to get the data everytime the page refresh. I am suspecting if it is because of asynchronous call. Before even data arises the event object is getting assigned with undefined value. Any suggestions to solve this? How can I handle this asynchronous call here
Note: I am getting events object value as undefined that mean it goes inside successcallback with data but that data does not have events in it so it comes undefined and it happens randomly
Make document.visibilityState===’visible’ using background.js in an extension
I want to keep a specific tab active even when I move to other tabs or other application.
I want to do this using an extension and only adding code to background.js.
Any ideas on how to do it?
console.log(“background.js running”);
// background console logs can be found by inspecting the extension in chrome://extensions > developer mode > then click on “service worker” > then go to console
javascript – querySelectorAll with addEventListener – how to get number of interacted element and variable from variable
I have HTML:
<form name="form" ..
<input type="text" name="title1" id="title1" class="f_title" value="smth LV">
<input type="text" name="title2" id="title2" class="f_title" value="smth EN">
<input type="text" name="title3" id="title3" class="f_title" value="smth DE">
<input type="text" name="url1" id="url1" class="f_url" value="smth-lv">
<input type="text" name="url2" id="url2" class="f_url" value="smth-en">
<input type="text" name="url3" id="url3" class="f_url" value="smth-de">
If user changes input “title”, i do some replacements with this value and i want to set it to the right input “url”.
In a “nice” way I can’t get the “number” of interacted field and can’t set it to the corresponding “url”… I guess i knew how to do if used for() and eval().
If i use [right] JS things like querySelectorAll and addEventListener:
let i = 1;
document.querySelectorAll('.f_title').forEach(el => {
el.addEventListener('change', () => {
if (typeof form.url[i] !== 'undefined') {
...
form.url[i] = form.title[i].value; // for example - if changes input "title2" - how to alert(2) and how to reference to form.url2 in this loop?
}
});
i++;
});
Is there a way to write a call to test for a keyboard event function with a specific parameter?
I have this function that has the keyboard event key property:
function sample(event){
let key = event.key;
if(key == "a"){
return False;
How do I write a call to test my function that is similar to something like
console.log(sample("a"))
I know that you’re not supposed to put “a” as the parameter but I don’t know what to put otherwise.
I tried to put console.log(event) in the function, then run the function, and then pressing the key letter “w”. However, gave me a long list composed of the properties:
isTrusted: true
altKey: false
bubbles: true
cancelBubble: false
cancelable: true
charCode: 0
code: "KeyW"
composed: true
ctrlKey: false
currentTarget: null
defaultPrevented: false
detail: 0
eventPhase: 0
isComposing: false
key: "w"
keyCode: 87
location: 0
metaKey: false
repeat: false
returnValue: true
shiftKey: false
sourceCapabilities: InputDeviceCapabilities {firesTouchEvents: false}
srcElement: body
target: body
timeStamp: 2405899.5999999996
type: "keydown"
view: Window {window: Window, self: Window, document: document, name: '', location: Location, …}
which: 87
[[Prototype]]: KeyboardEvent
I don’t know where to go after this

