JS Empty focused Input - javascript

If the user enters an invalid number, I want to empty the input. Negative numbers and numbers that are decimal are not allowed.
This is my Js Function:
function calcPrice() {
var count = $('#placeCount').val();
if(count%1 == 0 && count > 0) {
if(count == 0) {
var output = "";
} else if(count == 1) {
var output = "€ 2,49";
} else if(count > 1 && count != 0) {
var output = ("€ " + (2*count-0.01));
}
}
else {
$('#placeCount').html("");
}
$('#priceOutput').html(output);
}
But somehow the input is not empty if I enter a count that goes into the else section.

change the value of the input with val() instead of html():
function calcPrice() {
var count = $('#placeCount').val();
if(count%1 == 0 && count > 0) {
if(count == 0) {
var output = "";
} else if(count == 1) {
var output = "€ 2,49";
} else if(count > 1 && count != 0) {
var output = ("€ " + (2*count-0.01));
}
}
else {
$('#placeCount').val("");
}
$('#priceOutput').html(output);
}

Related

Prevent checkbox from being selected in Javascript

I have a JavaScript function that checks if a checkbox is selected.
If yes, It count how many check boxes are selected and checks if the max number of selected (4) is reached.
The thing is:
How can I make that the function show an alert and disable all the unchecked check boxes when I try to check a fifth?
Even the one that was tried to be checked as the 5 one.
function ChkValidate() {
var chkDytLek = document.getElementById("ChkDytLek");
var chkDytUSD = document.getElementById("ChkDytUSD");
var chkDytEU = document.getElementById("ChkDytEU");
var chkDytCAD = document.getElementById("ChkDytCAD");
var chkDytCHF = document.getElementById("ChkDytCHF");
var chkDytAUD = document.getElementById("ChkDytAUD");
var chkDytGBP = document.getElementById("ChkDytGBP");
var MaxCount = 0
var unCheckedCount = 0
if (chkDytLek.checked == true) {
MaxCount = MaxCount + 1
if (MaxCount == 4) {
disableIfNotChecked();
}
} else {
unCheckedCount = unCheckedCount + 1
}
if (ChkDytUSD.checked == true) {
MaxCount = MaxCount + 1
if (MaxCount == 4) {
disableIfNotChecked();
}
} else {
unCheckedCount = unCheckedCount + 1
}
if (ChkDytEU.checked == true) {
MaxCount = MaxCount + 1
if (MaxCount == 4) {
disableIfNotChecked();
}
} else {
unCheckedCount = unCheckedCount + 1
}
if (ChkDytCAD.checked == true) {
MaxCount = MaxCount + 1
if (MaxCount == 4) {
disableIfNotChecked();
}
} else {
unCheckedCount = unCheckedCount + 1
}
if (ChkDytCHF.checked == true) {
MaxCount = MaxCount + 1
if (MaxCount == 4) {
disableIfNotChecked();
}
} else {
unCheckedCount = unCheckedCount + 1
}
if (ChkDytGBP.checked == true) {
MaxCount = MaxCount + 1
if (MaxCount == 4) {
disableIfNotChecked();
}
} else {
unCheckedCount = unCheckedCount + 1
}
if (ChkDytAUD.checked == true) {
MaxCount = MaxCount + 1
if (MaxCount == 4) {
disableIfNotChecked();
}
} else {
unCheckedCount = unCheckedCount + 1
}
if (unCheckedCount >= 4) {
enableIfNotChecked();
}
}
The current code displays an alert and disables the checkboxes when the count is 4.
When I want this to happen at the 5 one, but if I change this:
if (MaxCount == 4) {
disableIfNotChecked();
to:
if (MaxCount == 5) {
disableIfNotChecked();
The code will disable the check boxes but will also check the one that was selected as the 5.
Any idea how can I give a solution to this situation?
I think that you need some sort of control when to try to select a checkbox.
Try this:
$('input[type="checkbox"]').on('click', function(event) {
if(maxCount == 5) {
event.preventDefault();
alert('So many checkboxes');
}
});
Here is the fiddle:
http://jsfiddle.net/DrKfE/817/
Add this to the function call inside your checkbox ChkValidate(this)
<asp:CheckBox ID="ChkDytCAD" runat="server" GroupName="Monedha" Text="CAD" CssClass="radioMarginLeft" onClick="ChkValidate(this)" ClientIDMode="Static" />
Add the parameter to the function and at the end of the function uncheck it when you have 4 boxes ticked
function ChkValidate(checkbox) {
...
if (MaxCount > 4) {
checkbox.checked = false;
}
}
this is a fiddle with an example, that does pretty much what you want, it will only let you check a maximum of 4 boxes at once https://jsfiddle.net/2p069wvb/8/

Create a MR and MC in a javascript calculator

Idealy, I would like my little project to have the memory functions M-, M+, MR and MC.
I was thinking of separate functions and variables to hold the M- and M+.
Is this a normal approach or there is a better one ?
Any idea what might be wrong with my script ? if there is something wrong ?
the number-display ID is the actual calculator screen
the code is :
$(document).ready(function(){
var display = "";
var operators = ["/", "*", "-", "+"];
var decimalAdded = false;
$("button").click(function() {
var key = $(this).text();
//update screen by adding display string to screen with maximum 19 numbers viewable
function updateDisplay() {
if (display.length > 19) {
$("#number-display").html(display.substr(display.length - 19, display.length));
} else {
$("#number-display").html(display.substr(0, 19));
}
}
//clear all entries by resetting display and variables
if (key === "AC" || key === "ON" || key === "MC") {
decimalAdded = false;
display = "";
$("#number-display").html("0");
}
else if (key === "OFF") {
decimalAdded = false;
display = "";
$("#number-display").html("");
}
//clear previous character and reset decimal bool if last character is decimal
else if (key === "CE") {
if (display.substr(display.length - 1, display.length) === ".") {
decimalAdded = false;
}
display = display.substr(0, display.length - 1);
updateDisplay();
}
//add key to display if key is a number
else if (!isNaN(key)) {
display += key;
updateDisplay();
}
//check that . is the first in the number before adding and add 0. or just .
else if (key === ".") {
if (!decimalAdded) {
if(display > 0){
display += key;
}
else {
display += "0" + key;
}
decimalAdded = true;
updateDisplay();
}
}
//if key is basic operator, check that the last input was a number before inputting
else if (operators.indexOf(key) > -1) {
decimalAdded = false;
//first input is a number
if (display.length > 0 && !isNaN(display.substr(display.length - 1, display.length))) {
display += key;
updateDisplay();
}
// allow minus sign as first input
else if (display.length === 0 && key === "-") {
display += key;
updateDisplay();
}
}
// calculate square root of number
else if ( $(this).id === "sqrt") {
var tempStore = display.html();
$("#number-display").html(eval(Math.sqrt(tempStore)));
decimalAdded = false;
}
// change sign of number
else if ($(this).id === "plusmn") {
var newNum = display * -1;
$("#number-display").html(newNum);
}
// create memory plus and minus and calculate MR
else if (key === "M-") {
}
else if (key === "M+") {
}
// percentage function
else if (key === "%"){
}
else if (key == "=") {
//if last input is a decimal or operator, remove from display
if (isNaN(display.substr(display.length - 1, display.length))) {
display = display.substr(0, display.length - 1);
}
var calc = display;
calc = eval(calc);
display = String(calc);
if (display.indexOf('.')) {
decimalAdded = true;
} else {
decimalAdded = false;
}
$("#number-display").html(display);
}
});});
One alternative is a switch statement, which would look something like:
switch (key) {
case "M-":
// do stuff
break;
case "M+":
// do stuff
break;
case "%":
// do stuff
break;
case "=":
// do stuff
break;
}
More documentation on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

Nothing happens after Prompt

Sorry, I wasn't clear enough. I need it to list all the numbers from 0 to the number inputted by the prompt into the HTML. I made some suggested changes but now I only get the result for the specific number inputted, not all the numbers up to that number. I am just starting out so please be gentle. Thanks!
$(function() {
var number = parseInt(prompt("Let me see a number:"));
var result;
for(var i = 0; i <= number; i++) {
if ( i %15 == 0) {
result = "Ping-Pong";
}
else if (i %5 == 0) {
result = "Pong";
}
else if (i %3 == 0) {
result = "Ping";
}
else {
result = number;
}
document.getElementById("show").innerHTML = result;
};
});
You can do either:
for(var i = 0; i <= number; i++) {
var digit = number[i]; // or any other assigment to new digit var
if ( digit % 5 == 0) {
return "Ping-Pong";
}
.... rest of your code here.
or
if ( number % 5 == 0) {
return "Ping-Pong";
}
.... rest of your code here.
Problem is you did nothing after the return keyword. Also you didn't declared variable as digit. I hope this is what you are looking for.
With loop:
$(function() {
var number = parseInt(prompt("Let me see a number:"));
var result;
for (var i = 0; i <= number; i++) {
if (i % 15 == 0) { // replaced `digit` with `i`
result = "Ping-Pong";
} else if (i % 5 == 0) {
result = "Pong";
} else if (i % 3 == 0) {
result = "Ping";
} else {
result = number;
}
alert(result);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Without loop:
$(function() {
var number = parseInt(prompt("Let me see a number:"));
var result;
if (number % 15 == 0) { // replaced `digit` with `number`
result = "Ping-Pong";
} else if (number % 5 == 0) {
result = "Pong";
} else if (number % 3 == 0) {
result = "Ping";
} else {
result = number;
}
alert(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Ok, I figured it out. For future reference, this is what I was trying to do:
$(function() {
var number = parseInt(prompt("Let me see a number:"));
var i
var text = "";
for(i = 1; i <= number; i++) {
if ( i %15 == 0) {
text += "<br>" + "Ping Pong" + "<br>";
}
else if (i %5 == 0) {
text += "<br>" + "Pong" + "<br>";
}
else if (i %3 == 0) {
text += "<br>" + "Ping" + "<br>";
}
else {
text += "<br>" + i + "<br>";
}
};
document.getElementById("show").innerHTML = text;
});

Javascript: Mathfloor still generating a 0

In my script to generate a playing card, it's generating a 0, even though my random generator is adding a 1, so it should never be 0. What am I doing wrong?! If you refresh, you'll eventually get a "0 of Hearts/Clubs/Diamonds/Spades":
var theSuit;
var theFace;
var theValue;
var theCard;
// deal a card
function generateCard() {
var randomCard = Math.floor(Math.random()*52+1)+1;
return randomCard;
};
function calculateSuit(card) {
if (card <= 13) {
theSuit = "Hearts";
} else if ((card > 13) && (card <= 26)) {
theSuit = "Clubs";
} else if ((card > 26) && (card <= 39)) {
theSuit = "Diamonds";
} else {
theSuit = "Spades";
};
return theSuit;
};
function calculateFaceAndValue(card) {
if (card%13 === 1) {
theFace = "Ace";
theValue = 11;
} else if (card%13 === 13) {
theFace = "King";
theValue = 10;
} else if (card%13 === 12) {
theFace = "Queen";
theValue = 10;
} else if (card%13 === 11) {
theFace = "Jack";
theValue = 10;
} else {
theFace = card%13;
theValue = card%13;
};
return theFace;
return theValue
};
function getCard() {
var randomCard = generateCard();
var theCard = calculateFaceAndValue(randomCard);
var theSuit = calculateSuit(randomCard);
return theCard + " of " + theSuit + " (this card's value is " + theValue + ")";
};
// begin play
var myCard = getCard();
document.write(myCard);`
This line is problematic:
} else if (card%13 === 13) {
Think about it: how a remainder of division to 13 might be equal to 13? ) It may be equal to zero (and that's what happens when you get '0 of... '), but will never be greater than 12 - by the very defition of remainder operation. )
Btw, +1 in generateCard() is not necessary: the 0..51 still give you the same range of cards as 1..52, I suppose.
card%13 === 13
This will evaluate to 0 if card is 13. a % n will never be n. I think you meant:
card % 13 === 0
return theFace;
return theValue
return exits the function; you'll never get to the second statement.

If variable is null set the value to 0 with jQuery?

I am validating some fields and check if the length of a select element is larger than 0. I get the error "'length' is null or not an object" because id$=SelectResult is a listbox and can have no values and therefor return null and var val = $(this).val(); doesn't like that.
function checkControls() {
var itemLevel = $("select[title='Item Level']").val();
switch (itemLevel) {
case 'Strategic Objective':
var controlsPassed = 0;
$("input[id$=UserField_hiddenSpanData],input[title=Title],select[id$=SelectResult]").each(function(){
var val = $(this).val();
if(val != 0 && val.length != 0) {
//add one to the counter
controlsPassed += 1;
}
});
return (controlsPassed == 3)
case 'Milestone Action':
var controlsPassed = 0;
$("input[title=Target Date],select[id$=SelectResult],input[title=Title],input[id$=UserField_hiddenSpanData],input[title=Start Date],select[title=Strategic
Objective],select[title=Strategic Priority]").each(function(){
var val = $(this).val();
if(val != 0 && val.length != 0) {
//add one to the counter
controlsPassed += 1;
}
});
return (controlsPassed == 7)
case 'Performance Measure':
var controlsPassed = 0;
$("select[title=Strategic Objective],input[title=Title],select[id$=SelectResult],select[title=Strategic Priority]").each(function(){
var val = $(this).val();
if(val != 0 && val.length != 0) {
//add one to the counter
controlsPassed += 1;
}
});
return (controlsPassed == 4)
case 'Strategic Priority':
var controlsPassed = 0;
$("input[title=Target Date],select[id$=SelectResult],input[title=Title],input[id$=UserField_hiddenSpanData],input[title=Start Date],select[title=Strategic
Objective]").each(function(){
//var ResponsibleBusiness = $("select[id$=SelectResult]").val();
var val = $(this).val();
if(val != 0 && val.length != 0) {
//add one to the counter
controlsPassed += 1;
}
});
return (controlsPassed == 6)
}
}
function PreSaveItem() {
return checkControls()
}
If I'm understanding your goal correctly, you can shorten it down to this:
if(!$("select[id$=SelectResult]").val()) return false;
return $("input[title=Target Date],input[title=Title],input[id$=UserField_hiddenSpanData],input[title=Start Date],select[title=Strategic Objective]").filter(function(){
return $(this).val() == '';
}).length > 0;
Change this line:
if(val != 0 && val.length != 0) {
to
if ( !!val && val.length > 0) {

Categories

Resources