Category: javascript
Category Added in a WPeMatico Campaign
Stop previous JavaScript execution after fetching a new page?
I am making a web app using vanilla JavaScript. I have multiple Html and JavaScript pages. In index.html I am fetching code from pages (body tag including script tag) after the corresponding link has been clicked. The problem I am facing is that whenever I revisit a page (go back and forth ) the JavaScript code runs as usual but the previously ran JavaScript is still running. It is causing the error The variable has already been declared
What is the solution for this? I do not want to combine all my JavaScript code into a single file and I want to use pure JavaScript. For fetching HTML files I am using push.js (a small library created by me). Thank you.
Here’s my code-
index.html
<body>
<!-- replaceable part -->
<div class="state">
<!-- title bar -->
<header class="bar bar-nav">
<a href="#addAccountPage" class="pull-right icon icon-compose"></a>
<h1 class="title">Records</h1>
</header>
<!-- main content -->
<main class="content">
....
</main>
<script src="daily-account.js"></script>
</div>
<!-- navigation bar -->
<nav class="bar bar-tab">
<a xpush="daily-account.html" x-target=".state" class="tab-item active">
<span class="icon icon-home"></span>
<span class="tab-label">Account</span>
</a>
<a xpush="to-do.html" x-target=".state" class="tab-item">
<span class="icon icon-list"></span>
<span class="tab-label">To-do</span>
</a>
<a xpush="my-debt.html" x-target=".state" class="tab-item">
<span class="icon icon-bars"></span>
<span class="tab-label">Debts</span>
</a>
</nav>
<script src="active.js"></script>
</body>
<!-- additional scripts -->
<script src="push.js"></script>
daily-account.html
<body>
<!-- title bar -->
<header class="bar bar-nav">
<a href="#addAccountPage" class="pull-right icon icon-compose"></a>
<h1 class="title">Records</h1>
</header>
<!-- main content -->
<main class="content">
.....
</main>
<!--<script src="daily-account.js"></script>-->
</body>
Avoid global css getting overridden in PROD – REACT-NEXT app
I’ve no clue how to fix this as am new to REACT-NEXT (am an Angular guy). Below is element that am utilizing from another resource like
import example-custom-ele-parent, {example-custom-ele-child} from 'custom-tags/example-custom'
<example-custom-ele-parent>
<example-custom-ele-child></example-custom-ele-child>
</example-custom-ele-parent>
when I see css for example-custom-ele-child in my localhost:3008 , in chrome browser, it is like
.cqAcqQ {
padding: 0.25rem;
}
I want to add one rule so added in globals.css file, like
.cqAcqQ {
padding: 0.25rem;
margin: 2rem !important; // newly added by me
}
Everything was working in my localhost fine. But after i deployed, the changes i made overridden with new random class and its became
.kXIDVb {
padding: 0.25rem;
}
Current package versions are
"next": "13.0.7",
"next-transpile-modules": "10.0.0",
"react": "18.2.0",
"react-dom": "18.2.0",
I tried override by doing <example-custom-ele-child className={style['my-change']}></example-custom-ele-child> but getting error like className={style[‘my-change’] is not allowed
Could someone please guide me on this?
Thanks
Im using next.js new app router and in the code bellow I get a TypeError: Cannot read properties of undefined (reading ‘headers’)
export async function POST(req: NextRequest) {
await dbConnect()
const res = await req.json()
bcrypt.hash(res.passwd, 10)
.then((hashedPassword: any) => {
//create a new user instance and collect the data
const user = new User({
firstname: res.firstname,
lastname: res.lastname,
company: res.company,
phone: res.phone,
email: res.email,
password: hashedPassword,
})
user.save()
//return succes if the new user is added to the database
.then((result: string) => {
return NextResponse.json({message: "User created successfully /"+result},{status : 201})
})
.catch((err: string) => {
return NextResponse.json({message: "Error creating user :"+ err },{status : 500})
})
})
.catch((err: string) => {
return NextResponse.json({message: "Password was not hashed successfully "+ err },{status : 500})
})
}
I cant find out why i get this error:
- error TypeError: Cannot read properties of undefined (reading ‘headers’)
at eval (webpack-internal:///(rsc)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:265:61) at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
Ive seen similar error but the answer to the problem was to return the NextResponse.json() but im already doing it and I still get the error.
Cypress Code Coverage: Merge E2E and Component Testing into same coverage report
I have configured Cypress on my React Application and am using both E2E and Component Testing. Code Coverage is setup on both the tests using istanbul and @cypress/code-coverage.
The report is being generated for the individual tests. The issue comes up when I run once test type after the other.
For example, if I run E2E test the coverage report is generated. Then when I run component test, a new coverage report is generated that replaces the previous report.
Here is my cypress configuration,
Cypress version: 12.17.2
cypress.config.js
const { defineConfig } = require("cypress");
module.exports = defineConfig({
e2e: {
baseUrl: "http://localhost:3000",
setupNodeEvents(on, config) {
// implement node event listeners here
require("@cypress/code-coverage/task")(on, config);
return config;
},
},
component: {
devServer: {
framework: "create-react-app",
bundler: "webpack",
webpackConfig: {
mode: "development",
devtool: false,
module: {
rules: [
// application and Cypress files are bundled like React components
// and instrumented using the babel-plugin-istanbul
// (we will filter the code coverage for non-application files later)
{
test: /.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["@babel/preset-env", "@babel/preset-react"],
plugins: [
// we could optionally insert this plugin
// only if the code coverage flag is on
"istanbul",
],
},
},
},
],
},
},
},
setupNodeEvents(on, config) {
require("@cypress/code-coverage/task")(on, config);
return config;
},
},
});
cypress/support/e2e.js
import "./commands";
import "@cypress/code-coverage/support";
cypress/support/component.js
import "./commands";
import "@cypress/code-coverage/support";
.nycrc.json
{
"all": true,
"excludeAfterRemap": true,
"include": ["src/**/*.js"],
"exclude": ["cypress/**/*.js"]
}
Is there configuration that will make the 2 reports merge rather than replace each other?
How to pass variable to the page from background script
While the following does set the page title.
chrome.tabs.executeScript(1857434626, { code: `document.title = "newtitle."` });
The following doesn’t set document.foobar on the page.
chrome.tabs.executeScript(1857434626, { code: `document.foobar = "foobar."` });
On the page open devtools, console tab, document.foobar, it shows undefined. While document.title shows newtitle..
I need to pass a data/parameter/variable to a page from Chrome background script, so it later will be accessible from the page or from Tampermonkey for example.
The title way, I have no idea why but somehow works, is not a very good solution since 1. title length is limited 2. title may change by the site/app 3. I prefer keep the title as is.
You may suggest modifying the html on the page, just adding a script tag with a stringified json. But no, I prefer keep the html as is, and I believe that there should be a better/smarter way.
Thanks.
showing 5 rows instead of default 10 rows in datatable, when “pageLength” , “lengthMenu” is not suit
Usually will showing default 10 datas in a single page, but mine is 14 !?
I want to show 1 to 5 of 14 entries so i tried to put max:5 but it is not working.
the output table still more than 5
var select_server_table = $("#select_server_table_example").DataTable({
processing: true,
lengthChange: false,
serverSide: true,
pageLength : 5,
lengthMenu: [[5, 10, 20, -1], [5, 10, 20, 'Todos']],
ajax: {
url: "http://192.168.03.30:8000/api/ipc/all", // fake api
type: "GET",
// dataType : 'json',
contentType : 'application/json',
data: function(d) {
d.search = d.search.value
console.log(d)
return JSON.stringify(d)
},
headers: {
Authorization: "Bearer " + getToken,
},
dataSrc: function (response) {
console.log("DATA", response);
return response.ipcs;
}
},
columns: [
{ data: "device_id", title: "device_id" },
{ data: "name", title: "name" },
{ data: "group", title: "group" },
],
error: function(response){
console.log("ERROR",response);
}
});
select_server_table.draw();
I tried the discussion discussion , and <table id="table" class="" data-page-length='15' > but not apply to mine, pls take a look
Angular block array of http post consecutive calls
I have and array of Http post in angular
peticionesI3.push( ...dataArrayI3.map( data => this.httpService.doPost(url, data, '')) );
and call like this
return this.httpService.doPost(url, data1, '')
.pipe(
switchMap( r => combineLatest( peticionesI2 )),
switchMap( r => combineLatest( peticionesI3 )),
)
This array, peticionesI3, is too bigger and exceeded the maximum calls allowed.
How can I divide in blocks of 50, and called each block after the previous one is finished?
Thanks in advance
Using Ajax to populate HTML tab content
I don’t know how to explain (not good with English), but I believe my code does justice, so I want to populate an Input select option using Ajax. So I was able to do it for a single tab. But the issue now is I have 4 tabs with the same form; a hidden value is passed to Ajax to fetch their different content, but it only works for the first tab, and others don’t work.
So based on the code you are seeing, it is only fetching data for the first tab, “MTN” Other tabs are not working; what are the possible issues? Please help
<li class="nav-item">
<a class="nav-link network-tab" data-bs-toggle="pill" href="#mtn" role="tab" aria-controls="mtn" aria-selected="true">
<img class="img-fluid" src="assets/images/network/mtn.jpg" alt="" width="50px" height="100px">
</a>
</li>
<li class="nav-item">
<a class="nav-link active network-tab" data-bs-toggle="pill" href="#glo" role="tab" aria-controls="glo" aria-selected="false">
<img class="img-fluid" src="assets/images/network/glo.jpg" alt="" width="50px" height="100px">
</a>
</li>
<li class="nav-item">
<a class="nav-link network-tab" data-bs-toggle="pill" href="#airtel" role="tab" aria-controls="airtel" aria-selected="false">
<img class="img-fluid" src="assets/images/network/airtel.jpg" alt="" width="50px" height="100px">
</a>
</li>
<li class="nav-item">
<a class="nav-link network-tab" data-bs-toggle="pill" href="#mobile" role="tab" aria-controls="mobile" aria-selected="false">
<img class="img-fluid" src="assets/images/network/9mobile.jpeg" alt="" width="50px" height="150px">
</a>
</li>
</ul>
</div>
<div class="card-body px-0 pb-0">
<div class="tab-content" id="j-pills-tabContent">
<div class="tab-pane fade" id="mtn" role="tabpanel" aria-labelledby="mtn-tab">
<div class="col-xxl-8 box-col-12">
<div class="card">
<div class="card-header py-4">
<h5>Buy MTN Data </h5>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-7">
<form class="theme-form mega-form">
<input type="hidden" id="network_provider" name="network_provider" value="MTN">
<div class="mb-3">
<select class="form-control" id="data_type" name="data_type">
<option value="">Select Data Type</option>
<option value="SME">SME</option>
<option value="Direct">Direct</option>
<option value="CG">CG</option>
<option value="SME2">SME2</option>
</select>
</div>
<div class="mb-3">
<div class="form-group">
<select class="form-control" id="plan_id" name="plan_id">
<option value="">Select Data Type First</option>
</select>
</div>
</div>
<div class="mb-3">
<input class="form-control" type="text" placeholder="Phone Number">
</div>
<!-- <div class="mb-3">
<input class="form-control" type="date">
</div> -->
<!-- <div class="mb-3">
<input class="form-control" type="text" placeholder="bla bla">
</div> -->
<button type="button" class="btn btn-pill btn-outline-warning">Submit</button>
</form>
</div>
<div class="col-md-5 text-center order-md-last order-first"><img class="img-fluid"
src="assets/images/network/mtn.jpg" alt=""></div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane fade show active" id="glo" role="tabpanel" aria-labelledby="glo-tab">
<div class="col-xxl-8 box-col-12">
<div class="card">
<div class="card-header py-4">
<h5>Buy Glo Data </h5>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-7">
<form class="theme-form mega-form">
<input type="hidden" id="network_provider" name="network_provider" value="GLO">
<div class="mb-3">
<select class="form-control" id="data_type" name="data_type">
<option value="">Select Data Type</option>
<option value="SME">SME</option>
<option value="Direct">Direct</option>
<option value="CG">CG</option>
<option value="SME2">SME2</option>
</select>
</div>
<div class="mb-3">
<div class="form-group">
<select class="form-control" id="plan_id" name="plan_id">
<option value="">Select Data Type First</option>
</select>
</div>
</div>
<div class="mb-3">
<input class="form-control" type="text" placeholder="Phone Number">
</div>
<!-- <div class="mb-3">
<input class="form-control" type="date">
</div> -->
<!-- <div class="mb-3">
<input class="form-control" type="text" placeholder="bla bla">
</div> -->
<button type="button" class="btn btn-pill btn-outline-warning">Submit</button>
</form>
</div>
<div class="col-md-5 text-center order-md-last order-first"><img class="img-fluid"
src="assets/images/network/glo.jpg" alt=""></div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane fade" id="airtel" role="tabpanel" aria-labelledby="airtel-tab">
<div class="col-xxl-8 box-col-12">
<div class="card">
<div class="card-header py-4">
<h5>Buy Airtel Data </h5>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-7">
<form class="theme-form mega-form">
<input type="hidden" id="network_provider" name="network_provider" value="AIRTEL">
<div class="mb-3">
<select class="form-control" id="data_type" name="data_type">
<option value="">Select Data Type</option>
<option value="SME">SME</option>
<option value="Direct">Direct</option>
<option value="CG">CG</option>
<option value="SME2">SME2</option>
</select>
</div>
<div class="mb-3">
<div class="form-group">
<select class="form-control" id="plan_id" name="plan_id">
<option value="">Select Data Type First</option>
</select>
</div>
</div>
<div class="mb-3">
<input class="form-control" type="text" placeholder="Phone Number">
</div>
<!-- <div class="mb-3">
<input class="form-control" type="date">
</div> -->
<!-- <div class="mb-3">
<input class="form-control" type="text" placeholder="bla bla">
</div> -->
<button type="button" class="btn btn-pill btn-outline-warning">Submit</button>
</form>
</div>
<div class="col-md-5 text-center order-md-last order-first"><img class="img-fluid"
src="assets/images/network/airtel.jpg" alt=""></div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane fade" id="mobile" role="tabpanel" aria-labelledby="mobile-tab">
<div class="col-xxl-8 box-col-12">
<div class="card">
<div class="card-header py-4">
<h5>Buy 9Mobile Data </h5>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-7">
<form class="theme-form mega-form">
<input type="hidden" id="network_provider" name="network_provider" value="9MOBILE">
<div class="mb-3">
<select class="form-control" id="data_type" name="data_type">
<option value="">Select Data Type</option>
<option value="SME">SME</option>
<option value="Direct">Direct</option>
<option value="CG">CG</option>
<option value="SME2">SME2</option>
</select>
</div>
<div class="mb-3">
<div class="form-group">
<select class="form-control" id="plan_id" name="plan_id">
<option value="">Select Data Type First</option>
</select>
</div>
</div>
<div class="mb-3">
<input class="form-control" type="text" placeholder="Phone Number">
</div>
<!-- <div class="mb-3">
<input class="form-control" type="date">
</div> -->
<!-- <div class="mb-3">
<input class="form-control" type="text" placeholder="bla bla">
</div> -->
<button type="button" class="btn btn-pill btn-outline-warning">Submit</button>
</form>
</div>
<div class="col-md-5 text-center order-md-last order-first"><img class="img-fluid"
src="assets/images/network/9mobile.jpeg" alt=""></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>```
And here is the javascript
```<script>
const data_typeSelect = document.getElementById('data_type');
const plan_idSelect = document.getElementById('plan_id');
const networkProviderInput = document.getElementById('network_provider'); // Hidden input field
data_typeSelect.addEventListener('change', function () {
const selectedType = data_typeSelect.value;
const networkProvider = networkProviderInput.value; // Get the value of the hidden input field
if (selectedType !== '') {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
// Update the options in the second select box with the retrieved data
plan_idSelect.innerHTML = xhr.responseText;
}
};
xhr.open('POST', 'partial/processor.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send('data_type=' + encodeURIComponent(selectedType) + '&network_provider=' + encodeURIComponent(networkProvider)); // Include the network provider value in the POST data
} else {
// If no data type is selected, reset the second select box to its default state
plan_idSelect.innerHTML = '<option value="">Select Data Type First</option>';
}
});
</script>```
How to get raw SQL query from MySQL X DevAPI SQL CRUD functions?
I am using MySQL X DevAPI. That is working fine for relational tables.
// Working with Relational Tables
var mysqlx = require('@mysql/xdevapi');
var myTable;
// Connect to server using a connection URL
mysqlx
.getSession({
user: 'user',
password: 'password',
host: 'localhost',
port: 33060
})
.then(function (session) {
// Accessing an existing table
myTable = session.getSchema('test').getTable('my_table');
// Insert SQL Table data
return myTable
.insert(['name', 'birthday', 'age'])
.values(['Laurie', '2000-5-27', 19])
.execute()
})
.then(function () {
// Find a row in the SQL Table
return myTable
.select(['_id', 'name', 'birthday'])
.where('name like :name && age < :age)')
.bind('name', 'L%')
.bind('age', 30)
.execute();
})
.then(function (myResult) {
console.log(myResult.fetchAll());
});
In the above code how can I see raw SQL query generated from .insert() and .select() CRUD functions which is finally getting executed?
Sharepoin, new Ribbon appears immediately after loading the page
Good afternoon. I am using Sharepoint 2019 on premise Classic view. I need to create a new tab page using only Javascript as visual studio is not possible. I made one code, it works, only a new tab appears only after selecting a file in the library. and should be visible immediately. how to do it?
Quellcode
<script type="text/javascript" language="javascript">
// Hauptfunktion, um den Ribbon-Tab zu erstellen und die SharePoint-Bibliotheken zu laden
function initializeRibbon() {
// Warten, bis die SharePoint-Bibliotheken geladen sind, und dann die Ribbon-Initialisierung durchführen
ExecuteOrDelayUntilScriptLoaded(function () {
// Zugriff auf die SharePoint Ribbon-PageManager-Instanz
var pm = SP.Ribbon.PageManager.get_instance();
// Wenn das Ribbon initialisiert wurde, rufen Sie die Funktion zum Erstellen des Tabs auf
pm.CommandUIVisible = true;
pm.add_ribbonInited(function () {
var ribbon = pm.get_ribbon();
createTab(ribbon);
ribbon.selectTabById(TAB_ID, true);
});
SP.Ribbon.PageManager.get_instance().get_commandDispatcher().executeCommand(Commands.CommandIds.ApplicationStateChanged, null);
}, 'sp.ribbon.js');
}
// Konstanten für den Ribbon-Tab
const TAB_ID = "Your.Tab.Id";
const TAB_GROUP_ID = "Your.Tab.Group.Id";
const TAB_TEXT = "Your Tab Text";
const TAB_GROUP_TEXT = "Your Tab group text";
// Funktion zum Erstellen des Ribbon-Tabs
function createTab(ribbon) {
// Tab erstellen und zum Ribbon hinzufügen
var tab = new CUI.Tab(ribbon, TAB_ID, TAB_TEXT, "Tab Description", 'Tab.Attach.Command', false, '', null, null);
ribbon.addChild(tab);
// Gruppe erstellen und zum Tab hinzufügen
var group = new CUI.Group(ribbon, TAB_GROUP_ID, TAB_GROUP_TEXT, "Group Description", 'Tab.Attach.Group.Command', null);
tab.addChild(group);
// Layout erstellen und zur Gruppe hinzufügen
var layout = new CUI.Layout(ribbon, 'Tab.AttachNews.Layout', 'The Layout');
group.addChild(layout);
// Sektion erstellen und zum Layout hinzufügen
var section = new CUI.Section(ribbon, 'Tab.AttachNews.Section', 2, 'Top'); //2==OneRow
layout.addChild(section);
// Erstelle die Buttons für die Sektion
createButton(ribbon, section, group, TAB_ID, 'Tab.AttachNews.Button.Command', 'Tab.AttachNews.ControlProperties', 'o1', 'Google', '_layouts/15/images/discoveryExport_32x32.png', function () {
openLink("https://www.google.de");
});
createButton(ribbon, section, group, TAB_ID, 'Tab.AttachNews.Button2.Command', 'Tab.AttachNews.ControlProperties2', 'o1', 'Bing', '_layouts/15/images/bing.png', function () {
openLink("https://www.bing.de");
});
}
// Funktion zum Erstellen der Buttons
function createButton(ribbon, section, group, tabId, command, id, templateAlias, labelText, image32by32, onClickHandler) {
// Eigenschaften für die Button-Komponente festlegen
var controlProperties = new CUI.ControlProperties();
controlProperties.Command = command;
controlProperties.Id = id;
controlProperties.TemplateAlias = templateAlias;
controlProperties.ToolTipDescription = labelText;
controlProperties.Image32by32 = image32by32;
controlProperties.ToolTipTitle = labelText;
controlProperties.LabelText = labelText;
// Button erstellen
var button = new CUI.Controls.Button(ribbon, id, controlProperties);
// Button aktivieren
// Button-Komponente für den Modus "Large" erstellen
var controlComponent = button.createComponentForDisplayMode('Large');
// Button zur Sektion hinzufügen
var row1 = section.getRow(1);
row1.addChild(controlComponent);
// Layout für die Gruppe auswählen und den neuen Tab als ausgewählt markieren
group.selectLayout('The Layout');
SelectRibbonTab(tabId, true); //Mark new tab as selected
// Button aktivieren
controlComponent.set_enabled(true);
// Klick-Eventhandler für den Button festlegen
$(button.getDOMElementForDisplayMode("Large")).click(onClickHandler);
}
// Funktion zum Öffnen eines Links in einem neuen Browser-Tab
function openLink(url) {
window.open(url, "_blank");
}
// Aufruf der Funktion zum Laden der SharePoint JavaScript-Bibliotheken und zum Initialisieren des Ribbon-Tabs
initializeRibbon();
</script>
I tried several options, nothing helped. thank you in advance
What is the best way to render component by condition in React?
I have a component that needs to render by condition, I’m confused between the two ways like the code below and I am figuring out the recommended way of React. What is the best way to set render conditions for a component? I’m new to React and would love some help.
The first way:
const MyComponent1 = () => {
return (
<div>This is my component 1</div>
)
}
{isRender && <MyComponent />}
The second way:
const MyComponent2 = ({ isRender }) => {
if (!isRender) return null;
return (
<div>This is my component 2</div>
)
}
<MyComponent isRender/>
I feel the second approach will redundancy the logic code inside this component if the component is not rendered (e.g: hooks, handle function, …)
The first way will not affect the CPU because the component is not rendered so the internal logic will not be executed. Is that true?
How to vba code for save file from cell value
Sub CopyAndSaveSelectedDataFromCells()
Dim wbNew As Workbook
Dim wsActive As Worksheet
Dim wsCopy As Worksheet
Dim selectedRange As Range
Dim newFilePath As String
Dim newFileName As String
' Store references to the active workbook and worksheet
Set wsActive = ActiveSheet
Set selectedRange = Selection
' Check if any range is selected
If selectedRange Is Nothing Then
MsgBox "Please select a range of data before running this macro.", vbExclamation
Exit Sub
End If
' Get the file path and name from specific cells (change "A1" and "B1" to the desired cell addresses)
newFilePath = wsActive.Range("A1").Value
newFileName = wsActive.Range("B1").Value
' Check if the file path and name are provided
If Len(newFilePath) = 0 Or Len(newFileName) = 0 Then
MsgBox "Please enter valid file path and name in the specified cells.", vbExclamation
Exit Sub
End If
' Combine the file path and name
newFilePath = newFilePath & "" & newFileName
' Create a new workbook
Set wbNew = Workbooks.Add
Set wsCopy = wbNew.Sheets(1)
' Copy the selected range to the new workbook
selectedRange.Copy wsCopy.Range("A1")
' Save the new workbook with the user-provided file path and name
Application.DisplayAlerts = False ' Disable prompt for saving changes
wbNew.SaveAs newFilePath
Application.DisplayAlerts = True ' Enable prompt for saving changes
' Clean up
Application.CutCopyMode = False ' Clear the clipboard
Set wsCopy = Nothing
Set wsActive = Nothing
Set wbNew = Nothing
' Inform the user that the data has been copied and saved
MsgBox "Selected data has been copied and saved to a new workbook." & vbNewLine & "File saved as: " & newFilePath, vbInformation
End Sub
Sub CopyAndSaveSelectedDataFromCells()
Dim wbNew As Workbook
Dim wsActive As Worksheet
Dim wsCopy As Worksheet
Dim selectedRange As Range
Dim newFilePath As String
Dim newFileName As String
' Store references to the active workbook and worksheet
Set wsActive = ActiveSheet
Set selectedRange = Selection
' Check if any range is selected
If selectedRange Is Nothing Then
MsgBox "Please select a range of data before running this macro.", vbExclamation
Exit Sub
End If
' Get the file path and name from specific cells (change "A1" and "B1" to the desired cell addresses)
newFilePath = wsActive.Range("A1").Value
newFileName = wsActive.Range("B1").Value
' Check if the file path and name are provided
If Len(newFilePath) = 0 Or Len(newFileName) = 0 Then
MsgBox "Please enter valid file path and name in the specified cells.", vbExclamation
Exit Sub
End If
' Combine the file path and name
newFilePath = newFilePath & "" & newFileName
' Create a new workbook
Set wbNew = Workbooks.Add
Set wsCopy = wbNew.Sheets(1)
' Copy the selected range to the new workbook
selectedRange.Copy wsCopy.Range("A1")
' Save the new workbook with the user-provided file path and name
Application.DisplayAlerts = False ' Disable prompt for saving changes
wbNew.SaveAs newFilePath
Application.DisplayAlerts = True ' Enable prompt for saving changes
' Clean up
Application.CutCopyMode = False ' Clear the clipboard
Set wsCopy = Nothing
Set wsActive = Nothing
Set wbNew = Nothing
' Inform the user that the data has been copied and saved
MsgBox "Selected data has been copied and saved to a new workbook." & vbNewLine & "File saved as: " & newFilePath, vbInformation
En
TypeError: Cannot read properties of undefined (reading ‘user’) POST CARD.js
i am working on a social media app made wih MERN STACK and i got this error continuosly, first i thought its a scope problem which keeps on poping up but now its doesn’t seems like one
this is my POST CARD FILE JS which is giving the error, also there were previously i used poster instead of user but i realized it does match the scope so i replaced it with user
now it is giving me the error
const { preview, removePost } = props;
let postData = props.post;
const [loading, setLoading] = useState(false);
const navigate = useNavigate();
const user = isLoggedIn();
const isAuthor = user && user.username === post.user.username;
const theme = useTheme();
const iconColor = theme.palette.primary.main;
const [editing, setEditing] = useState(false);
const [confirm, setConfirm] = useState(false);
const [post, setPost] = useState(postData);
const [likeCount, setLikeCount] = useState(post.likeCount);
let maxHeight = null;
if (preview === "primary") {
maxHeight = 250;
}
const handleDeletePost = async (e) => {
e.stopPropagation();
if (!confirm) {
setConfirm(true);
} else {
setLoading(true);
await deletePost(post._id, isLoggedIn());
setLoading(false);
if (preview) {
removePost(post);
} else {
navigate("/");
}
}
};
const handleEditPost = async (e) => {
e.stopPropagation();
setEditing(!editing);
};
const handleSubmit = async (e) => {
e.preventDefault();
const content = e.target.content.value;
await updatePost(post._id, isLoggedIn(), { content });
setPost({ ...post, content, edited: true });
setEditing(false);
};
const handleLike = async (liked) => {
if (liked) {
setLikeCount(likeCount + 1);
await likePost(post._id, user);
} else {
setLikeCount(likeCount - 1);
await unlikePost(post._id, user);
}
};
How to listen for button clicks with C# instead of JavaScript in Asp.net core?
I have a calculator grid on my asp.net core Razor page. I can listen for the button click with JavaScript and display the text of the clicked button inside an input text box. I was wondering if there is a way I can achieve a similar outcome with C#? I am using the JavaScript code below to capture click events
let buttons = document.getElementsByTagName("button");
let textBox = document.getElementsByTagName("input")[0];
let numbers = [];
for(let i=0;i<buttons.length;i++){
//add a click event listener to the button
buttons[i].addEventListener('click',function(){
//get the text inside a button
let text = buttons[i].innerText;
//check if it's an equal sign
if(text=='='){
//check if the array has two numbers else throw a syntax error
if(numbers.length !=2){
textBox.innerText = "Syntax Error";
}
}
//make sure it's a number
if(text=='+' || text == '-' || text =='/' || text == '*'){
//add the number to array
numbers.push(parseFloat(text));
//clear the text box
textBox.innerText = '';
}
});
}
