|
Hi,
What are the (Human Understandable) Rules for Scope and Type declarations, etc. for Java Script. I come from a C/CPP/MFC background, where all these things are clearly defined. Is it like early Basic, with a global scope? or what. a reference to a site, or a small book would be much appreciated.
Kind Regards,
Bram van Kampen
|
|
|
|
|
As far as I recall, Javascript is loosely typed. I am not sure the specifics of scope, but take a look at JavaScript | MDN[^].
|
|
|
|
|
Scope depends on what declaration you use. The old "var" declaration gives you function scope, where everything in a given function and sub function can refer to that scope (because "this" can mess that up big time, and is likely one of the hardest things to get used to in JS). ES 2016+ introduces the "let" declaration, which has proper block scope.
Global scope comes from either declaring a var outside of a function block, or the cleaner approach of attaching it to the window object:
var variable = value;
window.variable = value;
In classically-driven approaches to JS, the window object is effectively the global namespace.
"Never attribute to malice that which can be explained by stupidity."
- Hanlon's Razor
|
|
|
|
|
I have 3 nav bars on my angular page and need to stick 3rd nav bar when window is scroll. It behave weird on different browsers.
Is there any way to pick the top position of 3rd nav bar when window is scrolled and reached top of browser window? I tried with offsetTop and scrollTop but these values are fixed always.
modified 20-Sep-20 21:01pm.
|
|
|
|
|
|
I have a put method in web api as below:
[HttpPut("{id}")]
public int Edit(int id, TblEmployee employee)
{
return objemployee.UpdateEmployee(employee);
}
My Web Api methods are as follows, for some reason I am not able to call these Web Api methods, am I doing anything wrong these methods, please let me know:
[Produces("application/json")]
[Route("api/Employee")]
public class EmployeeController : Controller
{
EmployeeDataAccessLayer objemployee = new EmployeeDataAccessLayer();
[HttpGet("[action]")]
public IEnumerable<TblEmployee> Index()
{
return objemployee.GetAllEmployees();
}
[HttpPost]
public int Create(TblEmployee employee)
{
return objemployee.AddEmployee(employee);
}
[HttpGet("{id}")]
public TblEmployee Details(int id)
{
return objemployee.GetEmployeeData(id);
}
[HttpPut("{id}")]
public int Edit(int id, TblEmployee employee)
{
return objemployee.UpdateEmployee(employee);
}
[HttpDelete("{id}")]
public int Delete(int id)
{
return objemployee.DeleteEmployee(id);
}
[HttpGet("[action]")]
public IEnumerable<TblCities> GetCityList()
{
return objemployee.GetCities();
}
}
I am trying to call this method using reactjs component, I am not able to call this method, can you please help me where am I making mistake
Here is my Table rendering component:
private renderEmployeeTable(empList: EmployeeData[]) {
return <table className='table'>
<thead>
<tr>
<th></th>
<th>EmployeeId</th>
<th>Name</th>
<th>Gender</th>
<th>Department</th>
<th>City</th>
</tr>
</thead>
<tbody>
{empList.map(emp =>
<tr key={emp.employeeId}>
<td></td>
<td>{emp.employeeId}</td>
<td>{emp.name}</td>
<td>{emp.gender}</td>
<td>{emp.department}</td>
<td>{emp.city}</td>
<td>
<a className="action" onClick={(id) => this.handleEdit(emp.employeeId)}>Edit</a> |
<a className="action" onClick={(id) => this.handleDelete(emp.employeeId)}>Delete</a>
</td>
</tr>
)}
</tbody>
</table>;
}
Now I am calling it as below the Edit method as below
private handleEdit(id: number) {
this.props.history.push("api/employee/edit/" + id);
}
And I have Delete Web Api method that's not being called too from the above ts script file
[HttpDelete("{id}")]
public int Delete(int id)
{
return objemployee.DeleteEmployee(id);
}
And I have Create method which is supposed to be called by ts file at the time of save button click that's not being called as well:
[HttpPost]
public int Create(TblEmployee employee)
{
return objemployee.AddEmployee(employee);
}
The ts script for the create call is as below on the save button click:
import * as React from 'react';
import { RouteComponentProps } from 'react-router';
import { Link, NavLink } from 'react-router-dom';
import { EmployeeData } from './FetchEmployee';
interface AddEmployeeDataState {
title: string;
loading: boolean;
cityList: Array<any>;
empData: EmployeeData;
}
export class AddEmployee extends React.Component<RouteComponentProps<{}>, AddEmployeeDataState> {
constructor(props) {
super(props);
this.state = { title: "", loading: true, cityList: [], empData: new EmployeeData };
fetch('api/Employee/GetCityList')
.then(response => response.json() as Promise<Array<any>>)
.then(data => {
this.setState({ cityList: data }
);
console.log(data);
});
var empid = this.props.match.params["empid"];
if (empid > 0) {
fetch('api/Employee/Details/' + empid)
.then(response => response.json() as Promise<EmployeeData>)
.then(data => {
this.setState({ title: "Edit", loading: false, empData: data });
});
}
else {
this.state = { title: "Create", loading: false, cityList: [], empData: new EmployeeData };
}
this.handleSave = this.handleSave.bind(this);
this.handleCancel = this.handleCancel.bind(this);
}
public render() {
let contents = this.state.loading
? <p>Loading...</p>
: this.renderCreateForm(this.state.cityList);
return <div>
<h1>{this.state.title}</h1>
<h3>Employee</h3>
<hr />
{contents}
</div>;
}
private handleSave(event) {
event.preventDefault();
const data = new FormData(event.target);
if (this.state.empData.employeeId) {
fetch('api/Employee/Edit', {
method: 'PUT',
body: data,
}).then((response) => response.json())
.then((responseJson) => {
this.props.history.push("/fetchemployee");
})
}
else {
fetch('api/Employee/Create', {
method: 'POST',
body: data,
}).then((response) => response.json())
.then((responseJson) => {
this.props.history.push("/fetchemployee");
})
}
}
private handleCancel(e) {
e.preventDefault();
this.props.history.push("/fetchemployee");
}
private renderCreateForm(cityList: Array<any>) {
return (
<form onSubmit={this.handleSave} >
<div className="form-group row" >
<input type="hidden" name="employeeId" value={this.state.empData.employeeId} />
</div>
< div className="form-group row" >
<label className=" control-label col-md-12" htmlFor="Name">Name</label>
<div className="col-md-4">
<input className="form-control" type="text" name="name" defaultValue={this.state.empData.name} required />
</div>
</div >
<div className="form-group row">
<label className="control-label col-md-12" htmlFor="Gender">Gender</label>
<div className="col-md-4">
<select className="form-control" data-val="true" name="gender" defaultValue={this.state.empData.gender} required>
<option value="">-- Select Gender --</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
</div >
<div className="form-group row">
<label className="control-label col-md-12" htmlFor="Department" >Department</label>
<div className="col-md-4">
<input className="form-control" type="text" name="Department" defaultValue={this.state.empData.department} required />
</div>
</div>
<div className="form-group row">
<label className="control-label col-md-12" htmlFor="City">City</label>
<div className="col-md-4">
<select className="form-control" data-val="true" name="City" defaultValue={this.state.empData.city} required>
<option value="">-- Select City --</option>
{cityList.map(city =>
<option key={city.cityId} value={city.cityName}>{city.cityName}</option>
)}
</select>
</div>
</div >
<div className="form-group">
<button type="submit" className="btn btn-default">Save</button>
<button className="btn" onClick={this.handleCancel}>Cancel</button>
</div >
</form >
)
}
}
Basically all the Get Api methods are being called but not the put or post methods, any help would be very very helpful, thanks in advance
modified 25-Dec-18 19:04pm.
|
|
|
|
|
What i did:
function countDown(start) {
if(start>0)
var sum = start-1;
consolelog(sum);
|
|
|
|
|
Is there supposed to be a question there?
|
|
|
|
|
My psychic abilities tell me that something like this was requested
const countDown = (start) => {
for (let i = start; i >= 0; i--) {
console.log(i)
}
}
Although what I really would like to recommend is to explore this article and tutorials section in the left of the page. Because what you've requested is some really basic programming and if you can't handle it yourself there is not much to do for you.
|
|
|
|
|
function getHTMLTag(tagName) {
var tag = '<tagName>'+ '</tagName>';
return tag;
this is what i said, i'm stuck and dont know what else to try. I know its novice stuff but i just started a week ago.
|
|
|
|
|
Input parameter tagName is a variable value so needs to be outside of any quote characters. Your method should be something like:
function getHTMLTag(tagName) {
var tag = '<' + tagName + '></' + tagName + '>';
return tag;
[edit]
See also JavaScript Tutorial[^]
[/edit]
modified 23-Dec-18 7:21am.
|
|
|
|
|
|
How to Get an html table multiple rows as a string URL for Ajax to insert row values in database
|
|
|
|
|
You want to get the table, or insert the rows? Ajax can easily do both, and since we are talking about JavaScript, chances are you will have more libraries for this than most men have hair on their head.
Try this, DataTables example - Ajax sourced data
Elaborate your question a bit more, in order to get a proper answer.
The sh*t I complain about
It's like there ain't a cloud in the sky and it's raining out - Eminem
~! Firewall !~
|
|
|
|
|
Hello guys,
My final project is almost complete. It is a sub website and the goal is to add items to the cart and calculate if the items has been added or not etc.
Here is what I have so far:
window.addEventListener("load", setupCart);
function setupCart() {
var addButtons = document.getElementsByClassName("addButton");
for (var i = 0; i < addButtons.length; i++) {
addButtons[i].addEventListener(addItem);
}
}
function addItem(e) {
var foodItem = e.target.nextElementSibling;
var foodID = foodItem.getAttribute("id").value;
var foodDescription = foodItem.cloneNode(true);
var cartBox = document.getElementById("cart");
var duplicateOrder = false;
for (var i = 0; i < cartBox.childNodes.length; i++) {
if (cartBox.childNodes[i].id === foodID) {
cartBox.firstElementChild.value + 1;
}
}
if (duplicateOrder === false) {
var orderCount = document.createElement("span");
orderCount.textContent = 1;
foodDescription.appendChild(orderCount);
cartBox.appendChild(foodDescription);
}
}
I am getting an error on the browsers debug window saying: Quote: SCRIPT65535: SCRIPT65535: Argument not optional
For the following code:
addButtons[i].addEventListener(addItem);
Thanks !
***EDIT***
Found a bug:
addButtons[i].addEventListener(addItem);
Updated to:
addButtons[i].addEventListener("click", addItem);
Now items are loading onto cart, but repeat items are NOT simply being added by number, rather a duplicate fills the cart if the original is already there.
Working on this now. Debugger shows no error however.
modified 13-Dec-18 22:27pm.
|
|
|
|
|
Hey guys,
I am finishing up a project. I am getting some errors that I need help with. I posted the questions as comments within the code. Thanks !
function buttonClick(e) {
var calcValue = document.getElementById("calcWindow").value;
var calcDecimal = document.getElementById("decimals").value;
var buttonValue = e.target.value;
switch(buttonValue) {
case "del":
calcValue = "";
break;
case "bksp":
calcValue = eraseChar(calcValue);
break;
case "enter":
calcValue = " = " + evalEq(calcValue, calcDecimal) + "\n";
break;
case "prev":
calcValue = + lastEq(calcValue) ;
calcValue = calcValue + buttonValue;
break;
}
document.getElementById("calcWindow").value = calcValue;
document.getElementById("calcWindow").focus();
}
EDIT
The directions for the buttonValue are:
Quote: Each calculator button has a value attribute that defines what should be done with that button. Declare the buttonvalue attribute equal to the value attribute of the event object target.
|
|
|
|
|
var buttonValue = e.target.value;
What is e and what are its attributes?
calcValue = + lastEq(calcValue) ;
What is that + sign supposed to do?
|
|
|
|
|
 Richard, good question. I am following the example shown in the text. E is the buttonValue(e) function's parameter ?
I am guessing the operator required is a + operator to add the value? I also thought I did not need an operator there.
Here is the whole JS file code:
window.onload = init();
function init() {
var calcButtons = document.getElementsByClassName("calcButton");
for (var i = 0; i < calcButtons.length; i++) {
calcButtons[i].onclick = buttonClick();
}
document.getElementById("calcWindow").addEventListener(onkeydown, calcKeys());
}
function buttonClick(e) {
var calcValue = document.getElementById("calcWindow").value;
var calcDecimal = document.getElementById("decimals").value;
var buttonValue = e.target.value;
switch(buttonValue) {
case "del":
calcValue = "";
break;
case "bksp":
calcValue = eraseChar(calcValue);
break;
case "enter":
calcValue = " = " + evalEq(calcValue, calcDecimal) + "\n";
break;
case "prev":
calcValue = lastEq(calcValue);
calcValue = calcValue + buttonValue;
break;
}
}
document.getElementById("calcWindow").value = calcValue;
document.getElementById("calcWindow").focus();
function calcKeys(e) {
var calcValue = document.getElementById("calcWindow").value;
var calcDecimal = document.getElementById("decimals").value;
switch(e) {
case "Delete":
calcValue = "";
break;
case: "Enter":
calcValue = " = " + evalEq(calcValue, calcDecimal);
break;
case "ArrorUp":
calcValue = lastEq(calcWindow.value);
break;
e.preventDefault();
}
document.getElementById("calcWindow").value = calcValue;
}
function eraseChar(textStr) {
return textStr.substr(0, textStr.length - 1);
}
function evalEq(textStr, decimals) {
var lines = textStr.split(/\r?\n/);
var lastLine = lines[lines.length-1];
var eqValue = eval(lastLine);
return eqValue.toFixed(decimals);
}
function lastEq(textStr) {
var lines = textStr.split(/\r?\n/);
var lastExp = lines[lines.length-2];
return lastExp.substr(0, lastExp.indexOf("=")).trim();
}
modified 7-Dec-18 9:53am.
|
|
|
|
|
The problem with homework questions is that we have no idea what your teacher has set as the problem, or what they expect in return.
ghazabaz wrote: I am following the example shown in the text. E is the buttonValue(e) function's parameter ? Well you need to go back to whatever text you are referring to and check that you are following it correctly. And perhaps talk to your teacher also.
|
|
|
|
|
ghazabaz wrote:
window.onload = init();
...
calcButtons[i].onclick = buttonClick();
...
document.getElementById("calcWindow").addEventListener(onkeydown, calcKeys());
Those are likely candidates for your error. You're setting the event handler to the value returned from calling the function with no parameters, rather than the function itself.
When you call buttonClick with no parameters, e will be undefined , and you will get your error.
Remove the parentheses from the event handlers. You should probably use addEventListener consistently as well.
window.addEventListener("load", init);
...
calcButtons[i].addEventListener("click", buttonClick);
...
document.getElementById("calcWindow").addEventListener("keydown", calcKeys);
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Both Richards, thanks a bunch.
After making changes to the function parentheses, the enter, delete and backspace of the calculator are now fully functional. However, none of the digits are keying in when clicked on the webpage?
Works fine if entered through the keyboard however. I am guessing it has something to do with:
for (var i = 0; i < calcButtons.length; i++) {
calcButtons[i].addEventListener("click", buttonClick);
}
document.getElementById("calcWindow").addEventListener("keydown", calcKeys);
}
OR
function buttonClick(e) {
var calcValue = document.getElementById("calcWindow").value;
var calcDecimal = document.getElementById("decimals").value;
var buttonValue = e.target.value;
switch(buttonValue) {
case "del":
calcValue = "";
break;
case "bksp":
calcValue = eraseChar(calcValue);
break;
case "enter":
calcValue = " = " + evalEq(calcValue, calcDecimal) + "\n";
break;
case "prev":
calcValue = + lastEq(calcValue) ;
calcValue = calcValue + buttonValue;
break;
}
document.getElementById("calcWindow").value = calcValue;
document.getElementById("calcWindow").focus();
}
Actually getting an error on:
calcValue = + lastEq(calcValue); which handles the previous button. But my main focus now are the number digits of the calculator.
|
|
|
|
|
ghazabaz wrote: calcValue = + lastEq(calcValue) ;
You're missing an operand there. It should look like one of these:
calcValue = SOMETHING + lastEq(calcValue);
calcValue += lastEq(calcValue);
calcValue = lastEq(calcValue);
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Assuming your number buttons are in the calcButtons array, you'll need a default case in your switch statement to handle them:
switch (buttonValue) {
...
case "prev":
calcValue = ??? + lastEq(calcValue) ;
calcValue = calcValue + buttonValue;
break;
default:
calcValue = calcValue + buttonValue;
break;
}
JavaScript Switch Statement[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Richard, thank you very much.
After implementing the suggested corrections (added "append" operator to line 95 in mt_calc.js file) the buttons are functional except the "previous" calculator buttons. Also, enter, delete and up arrow (supposed to copy & yield previous equation) are not working when used on keyboard.
Also getting a "NaN" along with the answer?
These are the instructions for the enter, delete and up up arrow buttons:
Quote: . Click within the calculator window and, using the keyboard, directly type a mathematical expression. Verify that pressing the Enter key evaluates the current expression and moves the cursor to a new line. Show that you can copy the previous expression by pressing the Enter key followed by the up-arrow key on your keyboard. Finally verify that pressing the Delete key clears the contents of the calculator window. Note: Keyboard commands might not work in the Safari browser since Safari does not support the key property at the time of this writing.
I added the append operator to calcValue = calcValue + buttonValue; as the instructions require:
Quote: Otherwise, append the calculator button character to the calculator window by letting, calcValue equal calcValue plus buttonValu
But when a calculator digit is entered and entered again it multiplies itself infinitely.
I was hinted at these sections as the answer:
switch(buttonValue) {
case "del":
calcValue = "";
break;
case "bksp":
calcValue = eraseChar(calcValue);
break;
case "enter":
calcValue = + " = " + evalEq(calcValue, calcDecimal);
break;
case "prev":
calcValue = lastEq(calcValue);
default:
calcValue = calcValue + buttonValue;
break;
}
switch(e) {
case "Delete":
calcValue = "";
break;
case "Enter":
calcValue = + " = " + evalEq(calcValue, calcDecimal);
break;
case "ArrowUp":
calcValue += lastEq(calcWindow.value);
break;
case "ArrowUp":
e.preventDefault();
break;
}
Here is the entire code for reference:
"use strict";
window.addEventListener("load", init);
function init() {
var calcButtons = document.getElementsByClassName("calcButton");
for (var i = 0; i < calcButtons.length; i++) {
calcButtons[i].addEventListener("click", buttonClick);
}
document.getElementById("calcWindow").addEventListener("keydown", calcKeys);
}
function buttonClick(e) {
var calcValue = document.getElementById("calcWindow").value;
var calcDecimal = document.getElementById("decimals").value;
var buttonValue = e.target.value;
switch(buttonValue) {
case "del":
calcValue = "";
break;
case "bksp":
calcValue = eraseChar(calcValue);
break;
case "enter":
calcValue = + " = " + evalEq(calcValue, calcDecimal) + "\n";
break;
case "prev":
calcValue = lastEq(calcValue);
default:
calcValue = calcValue + buttonValue;
break;
}
document.getElementById("calcWindow").value = calcValue;
document.getElementById("calcWindow").focus();
}
function calcKeys(e) {
var calcValue = document.getElementById("calcWindow").value;
var calcDecimal = document.getElementById("decimals").value;
switch(e) {
case "Delete":
calcValue = "";
break;
case "Enter":
calcValue = + " = " + evalEq(calcValue, calcDecimal);
break;
case "ArrowUp":
calcValue += lastEq(calcWindow.value) ;
break;
case "ArrowUp":
e.preventDefault();
break;
}
document.getElementById("calcWindow").value = calcValue;
}
function eraseChar(textStr) {
return textStr.substr(0, textStr.length - 1);
}
function evalEq(textStr, decimals) {
var lines = textStr.split(/\r?\n/);
var lastLine = lines[lines.length-1];
var eqValue = eval(lastLine);
return eqValue.toFixed(decimals);
}
function lastEq(textStr) {
var lines = textStr.split(/\r?\n/);
var lastExp = lines[lines.length-2];
return lastExp.substr(0, lastExp.indexOf("=")).trim();
}
|
|
|
|
|
ghazabaz wrote:
calcValue = + " = " + evalEq(calcValue, calcDecimal) + "\n";
You're still missing an operand there.
calcValue = ??? What goes here ??? + " = " + ...
ghazabaz wrote:
case "prev":
calcValue = lastEq(calcValue);
default:
You're missing a break; statement in that switch case, so control "falls through" to the default case.
JavaScript Switch Statement[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|