<!DOCTYPE html>
<html>
<body>
Please enter a number:<BR>
<input type="text" id="amount_input">
<button onclick="other_amount_input()">Submit</button>
<script>
var balance=502.73;
function other_amount_input() {
var input = document.getElementById("amount_input").value;
var new_total = parseInt(input) + balance;
alert("The amount deposited is: $" + input + ".00\n" + "This is the old balance: $" + balance + "\n" + "The new total is : $" + new_total);
}
</script>
</body>
</html>
I am trying to make an input box with html and javascript that takes an input (a positive number, can be a decimal but only to the hundredth place) I have the web page working to where it will take a whole number and add it to a hard coded number and display the output which is "hard_coded_number + input_number = output_number"
all I had to do was change parseInt to parseFloat and it worked for me
Related
I am populating a telephone input field with data from an API call when the page loads.
I have a function that formats phone numbers to look like this: +1 (888) 333 4444. But the function is only working when there is a keyup event. I am trying to get this pre-populated input value to be formatted with this same function. I've tried changing the event from keyup to load, onload, but it has no affect. I tried wrapping the function in a setTimeout delay, but that didn't work either.
I know I'm missing something simple...
<!DOCTYPE html>
<html>
<body>
<form>
<label>Telephone</label>
<input type="tel" onload="phoneMask()" value="<?= data.phone ?>"/>
</form>
<script>
//Format telephone numbers
function phoneMask() {
var num = $(this).val().replace(/\D/g,'');
$(this).val('+' + num.substring(0,1) + ' (' + num.substring(1,4) + ') ' + num.substring(4,7) + ' ' + num.substring(7,18));
};
$('[type="tel"]').keyup(phoneMask)
</script>
</body>
</html>
At the bottom of the page, in the script section add this:
function phoneMask() {
var num = $("input[type=tel]").val().replace(/\D/g,'');
$("input[type=tel]").val('+' + num.substring(0,1) + ' (' + num.substring(1,4) + ') ' + num.substring(4,7) + ' ' + num.substring(7,18));
};
$(document).ready(function() {
phoneMask();
} );
I have edited your phoneMask function.
This will call your phoneMask function once the page has loaded.
This works on the assumption that there is only going to be one box of type tel. Otherwise you will need to wrap the code in phoneMask areound an each with the selector using each.
I have just begun to learn how to use jQuery I need to validate an input field and test the range of numbers entered. I have written what I believe would be the correct way to do it but it doesn't work, in fact if you do enter a number between the range nothing occurs in the game. I would also like to have the input box turn "red" if the number entered isn't in the range, as well as put the output message I have included in my code if it doesn't fit.
This is my code:
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js">
</script>
<link rel="stylesheet" type="text/css" href="dice.css">
<title>Dice Game</title>
</head>
<body>
<script type="text/javascript">
$(document).ready(function () {
$('#guess').focus();
$('#roll').click(function () {});
$("#guess").validate({
rules: {
guess: {
required: true,
range: [2, 12]
}
}, //end of rules
message: {
guess: {
required: "Please enter a number.",
range: "You must enter a number between 2 and 12."
}
}
}); //end of validate()
var count = 3;
function startover() {
count = 3;
alert("Make a guess and click the Roll button.");
}
function roll(guess) {
if (count == 0) {
alert("Click the Play Again button.");
return;
}
var die1 = Math.floor(1 + 6 * Math.random());
var die2 = Math.floor(1 + 6 * Math.random());
var sum = die1 + die2;
if (guess == sum) {
alert("You rolled a " + die1 + " and a " + die2 +
" which adds up to " + sum + ". Your guess is " +
guess + ". Congratulations, you win!");
count = 0;
} else {
--count;
if (count == 0) {
alert("You rolled a " + die1 + " and a " + die2 +
" which adds up to " + sum + ". Your guess is " +
guess + ". You have no rolls left. " +
"Sorry... the computer won.");
} else {
alert("You rolled a " + die1 + " and a " + die2 +
" which adds up to " + sum + ". Your guess is " +
guess + ". You have " + count + " rolls left. " +
"Click Roll to try again.");
}
}
}
}); // end ready </script>
<form id="game">
<h1>Welcome to the dice game!</h1>
<p>Here's how it works! If you roll two dice and add up the values, you will get a minimum of 2 and a maximum of 12.</p>
<p>Enter a number between 2 and 12:
<input type="text" name="guess" id="guess" min="2" max="12" />
<br>The computer will roll the dice for you up to three times. If the dice match your guess, you win!</p>
<input type="button" value="Roll" onclick="roll(guess.value);" />
<input type="button" value="Play Again" onclick="startover();" />
</p>
</form>
</body>
</html>
There are these problems with your code:
javascript functions for button event handler should NOT be placed inside $(document).ready();
jQuery validate plugin should be run on your form element ($("#game").validate), NOT on your input text element ($("#guess").validate).
In order for invalid input to be highlighted, you need to add 'error' and 'valid' css styles.
In order to stop the game from proceeding, you can disable submit buttons when form validation fails, using:
onkeyup: function (element, event ) {
if(!$("#game").valid()) {
$(":button").attr("disabled", "disabled");
} else {
$(":button").removeAttr("disabled", "disabled");
}
}
Please see Plunker with working code.
Note: I haven't looked at your game logic, and haven't modified it, I have fixed the validation part.
validate is not a method in the jQuery core API and you are not linking to any other jQuery plugins. Looks like you are missing a SCRIPT tag for your validation plugin
You can do this with JavaScript. There's no need to specifically use jQuery for this.
With JavaScript, all you need to do is handle the 'roll' button click event:
var btnButton = document.getElementById('roll');
btnButton.addEventListener("click", function () {
var txtValue = document.getElementById('guess').value;
if (txtValue.length > 0) {
if (!isNaN(+txtValue)) {
if (txtValue > 2 && txtValue < 12) {
document.getElementById('spanValidationMsg').className = "hide";
//WRITE YOUR CUSTOM CODE HERE
//WRITE YOUR CUSTOM CODE HERE
}
else {
document.getElementById('spanValidationMsg').innerHTML = "You must enter a number between 2 and 12.";
}
}
}
else
{
document.getElementById('spanValidationMsg').innerHTML = "Please enter a number";
document.getElementById('spanValidationMsg').className = "show";
}
});
See this here: http://jsfiddle.net/jL26k/2/
EDIT: There was a small error. Check the link now.
The problem is your selector is wrong, you should be selecting the form element not the guess element.
e.g. it should be $('#game').validate({ ...
To get the form inputs to change color read the documentation here: http://jqueryvalidation.org/validate#errorclass
Trying to take two input values from text boxes, click a button, and then return the answer as text
The two input names are "weight" and "reps". I want it so once you click the button it will do the calculation and be added to div "result"
HTML:
<div>
Weight lifted: <input name="weight" type="text" value="?">
</div>
<div>
Reps attained: <input name="reps" type="text" value="?">
</div>
<button>Calculate One-Rep Max</button>
<div id="result"></div>
what i have now for jquery:
$(document).ready(function() {
$('button').click(function() {
var weight = $('input[name=weight]').val();
var reps = $('input[name=weight]').val();
var max = $('input[name=weight]').val() * $('input[name=reps]').val() * 0.0333 + $('input[name=weight]').val();
$('#result').append("<p>" + max + "</p>");
});
});
The problem is that .val() returns a string, and while the * operator implicitly converts strings to numbers (e.g. "5.0" * "5.0" → 25), the + operator does not. The + at the end isn't adding the two numbers together, it's concatenating them as strings (e.g. "5.0" + "5.0" → "5.05.0"). You'll want to parse the inputs first, and then work with the results as numbers.
Try this:
var weight = Number($('input[name=weight]').val());
var reps = Number($('input[name=reps]').val());
var max = weight * reps * 0.0333 + weight ;
$('#result').append("<p>" + max + "</p>");
// or $('<p>').text(max).appendTo("#result");
Demonstration
When I run the following code in the browser.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to loop through a block of code five times.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x="";
for (var i=0;i<5;i++)
{
x = x + "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>
It displays the following
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
below the "Try it" button when it is clicked. My problem is with this part of the code x=x + "The number is " + i + "<br>";. When it is replaced with x="The number is " + i + "<br>"; it only display The number is 4. Some please explain why this is so.
Because x is the string which is displayed. At each increment of the loop, when the "x" on the right-hand side of the equals sign is kept all the old "The number is " + i + "< br >" are kept as well. When the "x" on the right-hand side of the equals sign is deleted, the old strings are overwritten to only show the larger number i.
What you need is a closure. Inside your for loop, try this script
(function(x, i){
x=x + "The number is " + i + "<br>";
})(x, i);
I am trying to populate a certain text area with a string in java script. I have defined the string as the variable "result" in my function and said for the function to return the variable result. When it returns "result" I want it to be returned in a specific text area. So I called the text area by using document.getElementByID but it wont populate the text area. I am unsure where where I went wrong or where to go from here. Any help would be greatly appreciated. I have included the code for the form and function below.
JavaScript
function newVerse(form1) {
var objects = form1.objects.value;
var destination = form1.destination.value;
var result = "Where have all the" + objects + "gone?" + "Long time passing." + "Where have all the" + objects + "gone?" + "Long time ago." + "Where have all the" + objects + "gone?" + "Gone to" + destination + ", everyone." + "When will they ever learn?" + "When will they ever learn?";
document.getElementByID(textarea).value += result
return result;
}
HTML
<form name=form1>Objects:
<input type="text" name="objects">
<br>Destination:
<input type="text" name="destination">
<br>
<input type="button" name="submit" value="Submit" onclick="newVerse(form1)">
</form>
I've made a working example here.
Here are you errors:
Javascript
function newVerse(form1) {
var objects = form1.objects.value;
var destination = form1.destination.value;
var result = "Where have all the" + objects + "gone?" + "Long time passing." + "Where have all the" + objects + "gone?" + "Long time ago." + "Where have all the" + objects + "gone?" + "Gone to" + destination + ", everyone." + "When will they ever learn?" + "When will they ever learn?";
//Missing quotes arround text area.
//Missing ; althought is not necessary.
//document.getElementByID(textarea).value += result
document.getElementByID('textarea').value += result;
}
HTML
<form name=form1><!-- Missing "" around form1 -->
Objects:
<input type="text" name="objects"> <!-- Missing closing / -->
<br>Destination:
<input type="text" name="destination"> <!-- Missing closing / -->
<br>
<input type="button" name="submit" value="Submit" onclick="newVerse(form1)">
<!-- You want to pass the actual form, so replace onclick="newVerse(form1)" by onclick="newVerse(document.forms['form1'])"-->
<!-- Missing closing / -->
</form>