When the user clicks on the button, you need to compare the values in certain fields and display the values according to the template.
I know this is a very stupid question, but I can't make it so that all values are "true" and the function is considered executed and the button works out the correct values
I try like this
function serviceCheck() {
function serviceCheck1() {
var CasePageServiceSelector = document.getElementById('CasePageServicePact00d7746a-0675-49ac-8608-323407985e07ComboBoxEdit-el').value;
var ServiceDocument = 'Case';
if (CasePageServiceSelector === ServiceDocument){
console.log('1')
}
}
function serviceCheck2() {
var CasePageServiceCategSelector = document.getElementById('CasePageServiceCategoryComboBoxEdit-el').value;
var ServiceCateg = 'Talker';
if (CasePageServiceCategSelector === ServiceCateg){
console.log('2!')
}
}
function serviceCheck3() {
var CasePageServiceItemSelector = document.getElementById('CasePageServiceItemComboBoxEdit-el').value;
var ServiceItem = '4. Problem';
if (CasePageServiceItemSelector === ServiceItem){
console.log('3')
}
}
}
function ChangeSecondTA() {
let Theme = $('#CasePageSubjectTextEdit-el').val('template');
let Symptoms = $('#CasePageSymptomsHtmlEdit-el').val('template2 ');
}
function onButtonClick(event) {
try {
alert(serviceCheck)
} catch (error) {
console.error("error: ", error);
}
};
At first, you write the function serviceCheck() and you call it using: alert(serviceCheck)
Why do you use alert, if your function does not return anything?
Secondly, you write three functions serviceCheck1-3() however you newer call these functions.
you need write something like this:
function serviceCheck() {
let in1 = document.getElementById('input1').value;
let in2 = document.getElementById('input2').value;
if (in1 == in2) {
alert('true');
} else {
alert('false');
}
}
function onButtonClick() {
serviceCheck();
};
<html>
<head></head>
<body>
<button onclick="onButtonClick()">input1 == input2 ?</button>
<br><input id='input1' type="text" value="55">
<input id='input2' type="text" value="55">
</body>
</html>
Related
I'm trying to change inputX[0] from false to true, then get an alert if it worked. Unfortunately I don't get the message that inputX[0] was set to true. Do you have any ideas?
<body>
<div>
<button id="S1" onclick="btnManager(this);"></button>
</div>
<script>
var inputX = new Array();
definedInputs();
btnManager();
question();
function definedInputs() {
inputX[0] = false;
}
function btnManager(pressedBtn) {
if (pressedBtn.id == (id = "S1")) {
inputX[0] = true;
}
}
function question() {
if (inputX[0] == true) {
alert("inputX is set to true");
}
}
</script>
</body>
try with this:
<body>
<div>
<button id="S1" onclick="btnManager(this);"></button>
</div>
<script>
var inputX = new Array();
inputX[0] = false;
function btnManager(pressedBtn) {
inputX[0] = !inputX[0];
alert(inputX[0]);
}
</script>
</body>
With this, every you push the button the value will be set by the negation of the current value, hope it helps.
It is important that you understand the Js lifecycle.
First javascript objects and functions are built and
then the code is executed, in this case it happens as follows:
The array "inputX" is created
Using the function "definedInputs()" defines "inputX[0] = false"
"btnManager()" is executed but since it is not assigned a parameter, the value of "pressedBtn.id" is "undefined" so the state of "inputX[0]" does not change
The status of "inputX[0]" is queried using "question()", but since "inputX[0]" is still false, no alert is fired.
All of this happens before you can press the button.
Pressing the button executes "btnManager(this)" and since the id is equal to "S1" the state of "inputX[0]" changes to true.
But you can't see this change because the "question()" function has already been executed.
Try:
<!DOCTYPE html>
<html>
<body>
<div>
<button id="S1" onclick="btnManager(this);">Test</button>
</div>
<script>
var inputX = new Array();
definedInputs();
function definedInputs() {
inputX[0] = false;
}
function btnManager(pressedBtn) {
if (pressedBtn.id == "S1") {
inputX[0] = true;
}
question();
}
function question() {
if (inputX[0] == true) {
alert("inputX is set to true");
}
}
</script>
</body>
</html>
Add some console logs to see what is happening. If you do, you'll see that all of your functions are executing immediately. When you click the button and enter the btnManager() function what happens next? As you'll see, your code is executing the btnManager() function but then what about checking for your alert?
If you call question() after your if statement, then you'll run your check again.
You could do this with less lines, but for the sake of keeping your exact code and making it work, this is how you would achieve your goal:
<body>
<div>
<button id="S1" onclick="btnManager(this);"></button>
</div>
<script>
var inputX = new Array();
// You could really remove these and do it like Lucretius's Answer
definedInputs();
btnManager();
question();
function definedInputs() {
inputX[0] = false;
}
function btnManager(pressedBtn) {
if (pressedBtn.id == (id = "S1")) {
inputX[0] = true;
}
question();
}
function question() {
if (inputX[0] == true) {
alert("inputX is set to true");
}
}
</script>
</body>
You're comparing the value of pressedBtn.id which is a text string S1 to a true/false Boolean evaluation (id == "S1") which will always be false because text strings and boolean values are not the same. Since (id = "S1") is an assignment, and you can't compare an assignment, this is what I am guessing you're trying to do.
'S1' == true will always be false
'S1' == false will also always be false.
Instead of:
function btnManager(pressedBtn) {
if (pressedBtn.id == (id == "S1")) {
inputX[0] = true;
}
}
Just evaluate the id and then log it to console to make sure the input array is updated.
<body>
<div>
<button id="S1" onclick="btnManager(this);">Click</button>
</div>
<script>
var inputX = new Array();
definedInputs();
function definedInputs() {
inputX[0] = false;
}
function btnManager(pressedBtn) {
if (pressedBtn.id == "S1" ) { //fixed
console.log( pressedBtn.id == (id == "S1") ); // breaks, undefined
}
}
function question() {
if (inputX[0] == true) {
alert("inputX is set to true");
}
}
</script>
</body>
Here is your code fixed.
You don't need to call btnManager(); or question(); immediately since these are called in a cascading fashion after the button click event is fired. The only "pre-work" your code needs to do on load is to defineInputs(); so those two lines were removed.
<body>
<div>
<button id="S1" onclick="btnManager(this);">Click</button>
</div>
<script>
var inputX = new Array();
definedInputs();
function definedInputs() {
inputX[0] = false;
}
function btnManager(pressedBtn) {
if (pressedBtn.id == "S1") {
inputX[0] = true;
console.log( "true" );
}
}
function question() {
if (inputX[0] == true) {
alert("inputX is set to true");
}
}
</script>
</body>
Hi I have the following HTML and javascript code for an ATM withdrawl machine. The code works but the balance does not decrease (starts at 400$) after each withdrawl from the user.I can't find what is the problem or how to get around this issue. Any help would be appreciated.
<!DOCTYPE html>
<html>
<head>
<title>ATM</title>
<style>
#bank {
text-align: center;
}
button {
padding-left: 6px;
padding-right: 6px;
}
</style>
<script type="text/javascript" src="Q2.js">
</script>
</head>
<body>
<form id="bank">
<h2> Question 2 </h2>
<h5>ATM Machine</h5>
<input type="text" id="cash" placeholder="Enter withdrawal amount" size="25">
<button type="submit" onclick="validateAmount()" id="button">Submit</button>
</form>
</body>
</html>
Here is the javascript
balance = 400.00;
function validateAmount() {
a = document.getElementById("cash");
amount = a.value;
if (isNaN(amount)) {
alert("Please enter a numeric value");
} else {
withdrawlAmount();
}
}
function withdrawlAmount() {
if (amount >= balance)
alert("Insufficent Funds");
else if (amount % 20 != 0)
alert("Incorrect withdrawl amount");
else if (amount < balance) {
alert("Succeful transaction\nCurrent Balance: " + (balance - amount) + "$");
balance -= amount;
} else {
return;
}
}
Your HTML submit button will refresh the page every time you press it, thus re-running your javascript and resetting the balance to 400. To fix this, change the button type from "submit" to "button".
Some things to address:
Prevent the default action. When capturing a submit event, you're going to want to prevent the default action from occurring using event.preventDefault() inside the event listener so that the page doesn't redirect.
Declare your identifiers. When you don't declare an identifier using var, let, or const, it becomes a global identifier and pollutes the global scope. Dealing with globals and undeclared identifiers will result in code that is less readable, and will probably result in confusion for you. I'll leave further explanation of this to the countless other articles on the topic.
Encapsulate your code. Your code might be the only code running on the page in this specific example, but largely it won't be in real life. Encapsulate your code, and keep it safe from other scripts while keeping other scripts safe from your script.
Above and beyond that, this is how I would go about it:
function ATM(balance, amount) {
this.receiver = document.createElement('template');
this.build();
this.balance = balance || 0;
this.amount = amount || 0;
}
ATM.prototype = {
build() {
this.receiver.insertAdjacentHTML('beforeend', `
<form id="atm-form">
<h1>ATM</h1>
<p><label>Balance: <input id="balance" value="0.00" readonly></label></p>
<p><label>Amount: <input id="amount" value="0.00"></label></p>
<p><button type="submit">Withdraw</button></p>
</form>
`);
this.nodes = {
form: this.receiver.querySelector('#atm-form'),
balance: this.receiver.querySelector('#balance'),
amount: this.receiver.querySelector('#amount')
};
this.nodes.form.addEventListener('submit', event => {
event.preventDefault();
const result = this.withdraw();
this.receiver.dispatchEvent(new CustomEvent('withdraw', { detail: { result } }));
});
this.nodes.balance.addEventListener('change', event => {
this.balance = this.nodes.balance.value;
});
this.nodes.amount.addEventListener('change', event => {
this.amount = this.nodes.amount.value;
});
},
attach(node) {
if(!(node instanceof Node)) return false;
node.appendChild(this.nodes.form);
return true;
},
validate() {
const result = { valid: false, error: null };
if(isNaN(this.amount)) {
result.error = 'Please enter a numeric value.';
} else if(this.amount > this.balance) {
result.error = 'Please enter a value less than the balance.';
} else if(this.amount <= 0) {
result.error = 'Please enter a value greater than 0.';
} else {
result.valid = true;
}
return result;
},
withdraw() {
let result = { success: false, error: null, amount: this.amount, balance: this.balance };
const { valid, error } = this.validate();
if(valid) {
this.balance = this.balance - this.amount;
result.balance = this.balance;
result.success = true;
} else {
result.error = error;
}
return result;
},
addEventListener(type, callback) {
this.receiver.addEventListener(type, callback);
},
removeEventListener(type, callback) {
this.receiver.removeEventListener(type, callback);
},
formatCurrency(value) {
return Number.parseFloat(value).toFixed(2);
},
set amount(value) {
this.nodes.amount.value = this.formatCurrency(value);
},
get amount() {
return this.formatCurrency(this.nodes.amount.value);
},
set balance(value) {
this.nodes.balance.value = this.formatCurrency(value);
},
get balance() {
return this.formatCurrency(this.nodes.balance.value);
}
}
const atm = new ATM(400.00);
atm.attach(document.body);
atm.addEventListener('withdraw', ({ detail: { result } }) => {
console.log('Withdraw event: ', result)
});
I'm trying to create error messages for labels on a form. Problem is that it's not working. The submitted input must be a number. Whenever it is not, clicking on the button should return a error message on the specific label.
Problem is - it only works OK if the first thing you submit is a correct set of numbers. I can't seem to get the combinations right. Do you know how I can solve this?
let coordValues = document.getElementsByClassName("input-card__input");
let submitBtn = document.getElementsByClassName("input-card__button");
let inputLabel = document.getElementsByClassName("input-card__label");
let weatherArray = [];
let labelArray = [];
for(let j=0;j<inputLabel.length;j++) {
labelArray.push(inputLabel[j].innerHTML);
}
submitBtn[0].addEventListener("click", function checkInputs() {
for(let i = 0; i<coordValues.length;i++) {
for(let k = 0; k<inputLabel.length;k++) {
if(coordValues[i].value === "" || isNaN(Number(coordValues[i].value))) {
inputLabel[k].classList.add("input-card__label--error");
inputLabel[k].innerHTML = "Oops! Write a number here."
console.log("nop");
break;
} else {
inputLabel[k].classList.remove("input-card__label--error");
inputLabel[k].innerHTML = labelArray[k];
console.log("yep");
break;
}
}
}
});
.input-card__label--error {
color: red;
}
<head>
</head>
<body>
<div class="input-card">
<h1 class="input-card__title">Where are you?</h1>
<h3 class="input-card__label">LONGITUDE</h3>
<input type="text" placeholder="Longitude" class="input-card__input">
<h3 class="input-card__label">ALTITUDE</h3>
<input type="text" placeholder="Altitude" class="input-card__input">
<button class="input-card__button">Show me weather ⛅</button>
</div>
</body>
There's a few errors in your code, here's a version I modified:
submitBtn[0].addEventListener("click", function checkInputs() {
for(let i = 0; i<coordValues.length;i++) {
if(coordValues[i].value === "" || isNaN(Number(coordValues[i].value))) {
inputLabel[i].classList.add("input-card__label--error");
inputLabel[i].innerHTML = "Oops! Write a number here."
console.log("nop");
return;
}
inputLabel[i].classList.remove("input-card__label--error");
inputLabel[i].innerHTML = labelArray[i];
}
console.log("yep");
});
One issue is the double for loop, it over complicates what you're trying to do.
Then once removed your code is left with a for loop then a test which all end up with a break so you never do more than one iteration.
The code above basically says log yes unless you find a reason to log nop.
In this case we need a flag to remember the error state:
submitBtn[0].addEventListener("click", function checkInputs() {
let allInputValid = true
for(let i = 0; i<coordValues.length;i++) {
if(coordValues[i].value === "" || isNaN(Number(coordValues[i].value))) {
inputLabel[i].classList.add("input-card__label--error");
inputLabel[i].innerHTML = "Oops! Write a number here."
console.log("nop");
allInputValid = false
}
else {
inputLabel[i].classList.remove("input-card__label--error");
inputLabel[i].innerHTML = labelArray[i];
}
}
if ( allInputValid )
console.log("yep");
});
Whenever an error is spotted, allInputValid is set to false. If there's two errors you set allInputValid to false twice.
I am having tough time in understanding why my element shows ng-dirty after updating the model.
I have a collection of bridges which need to be rendered on UI. On each tab click, I am changing the index and rendering the data.
If my first tab data has changed and moved to second tab why are input elements still dirty on second tab. (Function - $scope.changeIndex)
After executing calculate, the model gets updated but still the input elements are still dirty
UI
<td style="padding:10px;text-align:center">
<label>Length:</label>
<input type="text" class="currencyLabel-editable" ng-model="bridgeModel.bridges[currentIndex].length" />
</td>
<td style="padding:10px;text-align:center">
<label>Width:</label>
<input type="text" class="currencyLabel-editable" ng-model="bridgeModel.bridges[currentIndex].width" />
</td>
<td style="padding:10px;text-align:center">
<label> Skew:</label>
<input type="text" class="currencyLabel-editable" ng-model="bridgeModel.bridges[currentIndex].skew" />
</td>
Controller
(function () {
var bridgeCtrl = function ($scope, $bootstrapBridgeData, $crudService,$log) {
$scope.bridgeModel = $bootstrapBridgeData.bridgeModel;
var onCalculateComplete = function (data) {
$scope.bridgeModel.bridges[$scope.currentIndex] = angular.copy(angular.fromJson(data));
}
var onCalculateError = function (reason){
$scope.error = "Unable to perform calculation";
$log.error(reason);
}
var onError = function (reason) {
$scope.error = "Unable to fetch data";
}
//function to null the values which needs to be re-computed
var removeCalculatedValues = function () {
$scope.bridgeModel.bridges[$scope.currentIndex].foundation_PreBoringCalculated = null;
$scope.bridgeModel.bridges[$scope.currentIndex].foundation_DrilledShaftsCalculated = null;
}
//function to compute the bridge values
$scope.calculate = function (url) {
if (!preValidation()) {
return false;
}
removeCalculatedValues();
$crudService.postAndGetData(url, $scope.bridgeModel.bridges[$scope.currentIndex])
.then(onCalculateComplete, onCalculateError)
}
//function to select the bridge and change the index of the bridge
$scope.changeIndex = function (bridgeName,index) {
$scope.selectedBridge = bridgeName;
$scope.currentIndex = index;
}
$scope.save = function (index, url) {
$scope.currentIndex = index;
crudService.postAndGetData(url, $scope.bridges[index])
.then(onUserComplete, onError);
}
//$scope.enableSave = function isFormDirty() {
// if ($(".ng-dirty").length) {
// return false;
// }
// else { return true; }
//}
//Behaviour Changes
//function which changes the css
$scope.isBridgeSelected = function (bridge) {
return $scope.selectedBridge === bridge;
}
var preValidation = function () {
if ($(".ng-invalid").length) {
alert("Please correct the errors.")
return false;
}
else { return true;}
}
}
//Get the module and add a controller to it
var module = angular.module("bridgeModule");
module.controller("bridgeCtrl", bridgeCtrl);
}());
From the documentation
ng-dirty is set if the form is dirty.
This is a check for whether the form itself has been interacted with in any way. It doesn't care what the underlying object binding is. So this is the expected behavior, since you are using the same form but changing the ng-model behind the scenes.
Dunno if this is the problem or not, but the line $scope.$setPristine; is not doing anything. It should be: $scope.$setPristine();
I have a TS code like this:
class MicrositeRequest {
micrositeName: string;
micrositeTemplate: string;
constructor() {
this.micrositeName = $("#micrositeNameId").val();
this.micrositeTemplate = $("#templateId option:selected").text();
}
public IsMicrositeRequestValid() {
if (this.checkForName() && this.checkForTemplate()) {
return true;
}
else {
return false;
}
}
checkForName() {
if (this.micrositeName != null && this.micrositeName.length != 0) {
return true;
}
else {
return false;
}
}
checkForTemplate() {
if (this.micrositeTemplate != null && this.micrositeTemplate.length != 0) {
return true;
}
else {
return false;
}
}
}
Here's the converted JS:
/// <reference path="scripts/typings/jquery/jquery.d.ts" />
var MicrositeRequest = (function () {
function MicrositeRequest() {
this.micrositeName = $("#micrositeNameId").val();
this.micrositeTemplate = $("#templateId option:selected").text();
}
MicrositeRequest.prototype.IsMicrositeRequestValid = function () {
if (this.checkForName() && this.checkForTemplate()) {
return true;
}
else {
return false;
}
};
MicrositeRequest.prototype.checkForName = function () {
if (this.micrositeName != null && this.micrositeName.length != 0) {
return true;
}
else {
return false;
}
};
MicrositeRequest.prototype.checkForTemplate = function () {
if (this.micrositeTemplate != null && this.micrositeTemplate.length != 0) {
return true;
}
else {
return false;
}
};
return MicrositeRequest;
})();
//# sourceMappingURL=Microsite.js.map
On Click of a button I want to call the IsMicrositeRequestValid() method.
Here's the HTML:
<div>
<input type="submit" name="submit" value="Get" onclick="IsMicrositeRequestValid()" />
</div>
The Console says IsMicrositeRequestValid is not defined.
Any clues why this is happening and how I can fix it?
The call to IsMicrositeRequestValid in the onclick attribute requires that the function be part of the global namespace (window). Further, I'm pretty sure you'll need to instantiate MicrositeRequest object before the call to IsMicrositeRequestValid work (because it relies on this).
function validateRequest() { // declare a function in the global namespace
var mr = new MicrositeRequest();
return mr.IsMicrositeRequestValid();
}
<input type="submit" name="sumbit" value="Get" onclick="validateRequest()" />
is the quick & dirty way which should get it working.
You could also do this:
window.validateRequest = function () { // declare a function in the global namespace
var mr = new MicrositeRequest();
return mr.IsMicrositeRequestValid();
}
which I think is more readable.
Also, look into the Element.addEventListener method. It allows much more flexibility.
var submit = document.getElementById('my-submit');
submit.addEventListener('click', function () {
var mr = new MicrositeRequest();
return mr.IsMicrositeRequestValid();
});
<input type="submit" id="my-submit" name="sumbit" value="Get" />
In addition to pete's answer here an object oriented solution:
Alex works with jQuery, so i feel free to use it in this answer.
1.
You can't call methods of a class but only methods of objects, so you have to instantiate a object of class MicrositeRequest somewhere. Usually you do this after the DOM is fully populated, so you write:
$(() => {
new MicrositeRequest();
});
You may place this code beneath your class definition so that it starts after the browser loaded your script.
2.
Give your input element an id:
<div>
<input id="myInputElement" type="submit" name="submit" value="Get" onclick="IsMicrositeRequestValid()" />
</div>
Register method IsMicrositeRequestValid of the MicrositeRequest-object as onClick-handler for your input-element. To achieve this add these lines to the constructor method of class MicrositeRequest:
let that = this;
$('#myInputElement').on('click', () => {
that.IsMicrositeRequestValid();
});
You need variable that because inside the event handler this points to the input element.