I wanna add an if/else statement that prints "Only Number are accepted", for older browsers, where they allow you to add a string in a input with type=number.
var bttn = document.getElementById("agebttn");
bttn.addEventListener("click", bttnClicked);
function calculate(startingYear) {
var dateObj = new Date()
var currentYear = dateObj.getFullYear()
return currentYear - startingYear;
}
function bttnClicked() {
console.log("bttn clicked");
var age = parseInt(document.getElementById('age').value);
var yearsAlive = calculate(age);
var html = "You entered " + age;
html += "<br />You have been alive for " + yearsAlive + " years";
document.getElementById('answer').innerHTML = html;
}
<body>
<h1>Age Calculator</h1>
<input type="number" id="age" placeholder="Enter your birthyear">
<input type="button" id="agebttn" value="Calc" />
<div id="answer">
</div>
</body>
You can check if you were able to parse int or not using isNaN function here:
function bttnClicked() {
console.log("bttn clicked");
var age = parseInt(document.getElementById('age').value);
if(isNaN(age)){
document.getElementById('answer').innerHTML = "<b>Only Numbers Accepted</b>";
return;
}
var yearsAlive = calculate(age);
var html = "You entered " + age;
html += "<br />You have been alive for " + yearsAlive + " years";
document.getElementById('answer').innerHTML = html;
}
CMIIW
from what i see , you want to print that result from your script logic into your
div tag with ID = answer right? and you want to get only number input?
you would want to use !isNan(age) function to validate your input so when they validate and got not a number input , it will throw you back error message on your else condition
Related
I am creating a note pad that is to help keep notes consistent between users. I am unable to copy the multiple text boxes to a string. I have attached all of my Java Script.
The copy button that I would like to use to link the multiple text boxes into one string of text. the reset button works at clearing the page and the copy button follows the not empty text box checks. Please help with my copy string to the clipboard.
I have tried a bunch of different sites on the java script with no success. I have also reviewed Stack Overflow to see if I could find a close project.
input type="button" id="BtnSupSubmit" value="Copy" onclick="notEmptySup()" style="width: 87px"
function settime() {
var curtime = new Date();
var curhour = curtime.getHours();
var curmin = curtime.getMinutes();
var time = "";
if (curhour == 0) curhour = 12;
time = (curhour > 12 ? curhour - 12 : curhour) + ":" +
(curmin < 10 ? "0" : "") + curmin + ":" +
(curhour > 12 ? "PM" : "AM");
document.date.clock.value = time;
clock = time
window.status = time
}
function notEmptySup() {
var myTextField = document.getElementById('TxtBoxCallersName');
if (myTextField.value != "") notEmptySup2()
else
alert("Please enter callers name.")
}
function notEmptySup2() {
var myTextField = document.getElementById('TxtBoxSupIssue');
if (myTextField.value != "") notEmptySup3()
else
alert("Please enter the reason for the escalation.")
}
function notEmptySup3() {
var myTextField = document.getElementById('TxtBoxSupAction');
if (myTextField.value != "") notEmptySup4()
else
alert("Please enter the action you took to help the customer.")
}
function notEmptySup4() {
var myTextField = document.getElementById('TxtBoxSupResolution');
if (myTextField.value != "") CreateMessage()
else
alert("Please enter the resolution of the call.")
}
function CreateMessage() {
strMessage =
"Time: " + clock + "\|" +
"***Supervisor Escalation" + "\***|" +
"Caller: " + document.getElementById("TxtBoxCallersName").value + " \| " +
"Reason: " + document.getElementById("TxtBoxSupIssue").value + " \| " +
"Action: " + document.getElementById("TxtBoxSupAction").value + " \| " +
"Resolution: " + document.getElementById("TxtBoxSupResolution").value + " \| " +
"Ticket Number: " + document.getElementById("TxtBoxSupTicketNumber").value + " \| " +
"Addl Notes: " + document.getElementById("TxtBoxSupNotes").value;
document.getElementById("hdnBuffer").value = strMessage;
var buffer = document.getElementById("hdnBuffer").createTextRange();
buffer.execCommand("Copy");
}
Most of what you have is redundant. See comments inline below:
// Get a reference to the form
let frm = document.querySelector("form")
// Set up a sumbit event handler for the form
frm.addEventListener("submit", function(evt){
// Just get the locally formatted time
var message = "Time: " + new Date().toLocaleTimeString() +
"\n***Supervisor Escalation***\n\n";
// Get all the input elements
let inputs = document.querySelectorAll("input");
// Loop over them
for(let i = 0; i < inputs.length; i++){
if(inputs[i].value === ""){
alert("Please enter the " + inputs[i].dataset.message);
inputs[i].focus(); // Put focus on bad element
evt.preventDefault(); // Cancel the form submit
break; // Exit the loop
} else {
// Update the message
message += inputs[i].dataset.message + ": " +
inputs[i].value + " \n";
}
}
alert(message); // Do whatever you want with the message
});
<form action="https://example.com" method="post">
<div><label>Name:<input data-message="callers name"></label></div>
<div><label>Issue: <input data-message="reason for the escalation"></label></div>
<div><label>Action: <input data-message="action you took to help the customer"></label></div>
<div><label>Resolution: <input data-message="resolution of the call"></label></div>
<button type="submit">Submit Ticket</button>
</form>
I'm having problems with this bit of code. For some reason it won't capture the radSize, and it's giving me problems. Any ideas?
The page is supposed to capture the values, then add the base and size together to output total.
$(function() {
$("#btnMessage").click(function() {
var name = $("input[name=txtName]").val();
var phone = $("input[name=txtPhone]").val();
var basePizza = $("#cboBase").val();
var size = $("input[name=radSize]").is(":checked").val;
// alert(name +" "+ phone +" "+ basePizza +" "+ size);
var message = "";
var calculation = parseInt(basePizza) + parseInt(size);
//test each value
if (name == "")
message += "--Enter a first name";
if (phone == "")
message += "\n--Provide a number";
if (basePizza == "0")
message += "\n--Pick Base Pizza";
if (size == "")
message += "\n--Pick a Size";
else
message += name + "," + " " + "Your total for the pizza will be " + "$" + calculation;
alert(message);
// $('#output').html(message);
});
});
This line isn't really valid:
var size = $("input[name=radSize]").is(":checked").val;
The .is(":checked") part is a jQuery filtering utility that will return true or false.
Instead, you want to do something like this:
var size = $("input[name='radName']:checked").val();
Assuming only one of the "radSize" checkboxes can be checked, $("input[name='radName']:checked") will return the checked checkbox and val() will return its value.
I want to print a multiplication table of user input number. But nothing's happening in the click But what's the mistake? or have I jump into this program early?
<body>
<p>Multiplication table</p>
<input placeholder="Enter the number" type="text" name="number" id="quest"/>
<br />
<button onclick="multFunction()">Process</button>
<br />
<p id="multiply"></p>
<script>
function multFunction() {
var a = document.getElementsById("quest").value;
var i = 1;
for (i = 1 ; i < 11 ; i++) {
var c = parseInt(a) * parseInt(i);
document.getElementById("multiply").innerHTML = a + "x" + i + "=" + c;
}
}
</script>
There's a couple of mistakes in your code:
var a = document.getElementsById("quest").value;
Should be:
var a = document.getElementById("quest").value;
// ^ No "s" there.
Next, you don't want to replace the innerHTML each time, you want to add a new row to it, instead. However, writing to innerHTML that often isn't a good idea. (each write to it causes your browser to re-parse the DOM)
Replace:
document.getElementById("multiply").innerHTML = a + "x" + i + "=" + c;
With:
result += a + " x " + i + " = " + c + '</br>';
And add result = ''; at the front of your function. Then, after the loop, write result to the innerHTML
Here's a working demo:
function multFunction() {
var a = document.getElementById("quest").value;
var i = 1;
var result = '';
for (i = 1 ; i < 11 ; i++) {
var c = parseInt(a) * parseInt(i);
result += a + " x " + i + " = " + c + '</br>';
}
document.getElementById("multiply").innerHTML = result;
}
<p>Multiplication table</p>
<input placeholder="Enter the number" type="text" name="number" id="quest"/>
<br />
<button onclick="multFunction()">Enter the number</button>
<br />
<p id="multiply"></p>
Fix getElementsById at the first line in multFunction() it should be
getElementById
using browser console or plugins like Firebug will make it easier for you to catch such errors
My program needs to consist of a for loop, use both input functions already created ( name and number) and totals need to be acquired. I also need to be able to CANCEL and go to my doc.write where i would input name and number. I also need to give the user another chance to type in their name or number if they accidentally typed in number where letters should be and vise-versa. I think i have majority of the structure right, any help would be greatly appreciated!
function inputName() {
var nameIn = prompt("Enter your Name");
while(!isNaN(nameIn)) {
nameIn = prompt("Must contain only letters");
}
return nameIn;
}
/* INPUT NUMBER */
function inputNum(){
var numIn=parseFloat(prompt("Enter the number of hours worked \n 0-60 hours"));
var min=0;
var max=60;
while(numIn>min && numIn>max ){
numIn=prompt("Enter a valid number between 0-60");
return numIn;
}
</script>
<body>
<script type="text/javascript">
//DECLARATIONS
var wage=10.00;
var earned; // hrsWrked*wage
var totHrsWrked=0;
var totEarning=0;
var BR= "
";
var howMany;
var loopControl;
//INPUT & PROCESSING
howMany=parseFloat(prompt("How many employees are you inputing?"));
for(loopControl=1 ; loopControl <= howMany; ++loopControl){
var inpNam=inputName();
var inpNumber=inputNum();
earned= inpNumber*wage;
totEarning+=earned;
totHrsWrked+=inpNumber;
//OUTPUT
document.write("Name: "+ inpNam+ BR);
document.write("Hours Worked: " + inpNumber + BR);
document.write("Money Earned: $ " + earned + BR +BR);
}
document.write("Total Hours Worked: " + totHrsWrked.toFixed(2) + BR);
document.write("Total Earnings: " + "$"+totEarning.toFixed(2)+ BR+BR);
</script>
</body>
</html>
Here's the edited version of your code. :)
<! doctype html>
<html>
<body>
<script>
//DECLARATIONS
var wage=10.00, earned, totHrsWrked=0, totEarning=0, howMany;
//INPUT & PROCESSING
howMany=parseFloat(prompt("No of employees"));
for( var loopControl=1 ; loopControl <= howMany; ++loopControl)
{
var inpNam=inputName();
var inpNumber=inputNum();
earned= inpNumber*wage;
totEarning+= (+earned);
totHrsWrked+= (+inpNumber);
//OUTPUT
document.write("Name: "+ inpNam+ "<br>");
document.write("\n Hours Worked: " + inpNumber + "<br>");
document.write("Money Earned: $ " + earned + "<br><br>");
}
document.write("Total Hours Worked: " + totHrsWrked.toFixed(2)+ "<br>");
document.write("Total Earnings: " + "$"+totEarning.toFixed(2)+ "<br>");
//INPUT NAME
function inputName() {
var nameIn = prompt("Enter your Name");
while(!isNaN(nameIn)) {
nameIn = prompt("Must contain only letters");
}
return nameIn;
}
//INPUT NUMBER
function inputNum(){
var numIn=parseFloat(prompt("Enter the number of hours worked \n 0-60 hours"));
var min=0;
var max=60;
while(numIn<=min || numIn>=max ){
numIn=prompt("Enter a valid number between 0-60");
}
return numIn;
}
</script>
</body>
</html>
I'm writing a script that parses an XML file and displays it in html. Here it is:
<script>
$.get("api.xml", function (xml) {
$(xml).find("row").each(function () {
var date = $(this).attr('date');
var amount = $(this).attr('amount');
var balance = $(this).attr('balance');
document.write("A: " + date + "<br />B: " + amount + " ISK<br />C: " + balance + " ISK<br /><br /><br /><br />");
});
});
</script>
I want to modify the output of "document.write", so that if the value "amount" is positive, enter the word "green", otherwise, if negative, enter the word "red". I tried to write it as follows:
<script>
$.get("api.xml", function (xml) {
$(xml).find("row").each(function () {
var date = $(this).attr('date');
var amount = $(this).attr('amount');
var balance = $(this).attr('balance');
document.write("<script> if (amount >= 0) { document.write("green"); } else{ document.write("red"); } </scri" + "pt>");
});
});
</script>
But in that piece, I get a syntax error in "document.write". What I have written wrong and how could fix it?
I think you can compute the color before writing the output with document.write.
Something like this should work:
<script>
$.get("api.xml", function (xml) {
$(xml).find("row").each(function () {
var date = $(this).attr('date');
var amount = $(this).attr('amount');
var balance = $(this).attr('balance');
var color = "green";
if (amount < 0) {
color = "red";
}
document.write("A: " + date + "<br />B: <span style='color:" + color + "'>" + amount + " ISK</span><br />C: " + balance + " ISK<br /><br /><br /><br />");
});
});
</script>
(syntax unchecked)
To get an answer just look, how this code is highlighted. The words 'green' and 'red' are outside the quotes. You should use single quotes (or escape the double quotes).
The other question is why do you use metaprogramming for such a simple task. Just write a condition with two different document.write statements.
<script>
$.get("api.xml", function (xml) {
$(xml).find("row").each(function () {
var date = $(this).attr('date');
var amount = $(this).attr('amount');
var balance = $(this).attr('balance');
document.write(amount >= 0 ? "green" : "red");
});
});
</script>