I am trying to make a form that someone can enter a number and each number entered will correspond to a certain value in the output text. What I have so far is this:
<script>
function myFunction() {
var x, text;
x = document.getElementById("zip").value;
if (x = 53527) {
text = "$20.00";
}
if (x = 53718) {
text = "$25.00";
}
else {
text = "Please Call for Delivery";
}
document.getElementById("fee").innerHTML = text;
}
</script>
Overall it works, but the problem that I am having is once a number is entered, it always displays the "$25.00" value no matter what is entered in. I am not sure what is making it override the other values. Any help would be great. I am new to this and learning it as I go.
Change the single equal signs on (x = 53527) and (x = 53718) to double equal, i.e. (x == 53527) and (x == 53718) and see if works. Because in javascript when you are comparing values inside an if you have to have double equal.
Pay additional attention with your else clause because this is acting only over your second if. If you want to use it as an else for both ifs you can use else if on your second if.
Related
I am writing a number guessing game. The guessing game starts by prompting a user for a maximum number (this is not their guess yet--it's the top range for their guess). The prompt should be in a loop with validation, making sure the max number is a (rounded) positive integer. The loop should reprompt the user if the input is 0, <0, or a non-number. I am having trouble getting the validation loop to work.
This is what I have so far, and the prompt works, but the function does not work as I need it to.
let suggestion = parseInt(prompt("Help me come up with a range from 1 to a higher number. Type in a number greater than 1."));
function get_suggestion(prompt) {
let validInput = false;
let initial_ans, input;
while(!validInput) {
input = window.prompt(prompt);
initial_ans = parseInt(input);
if(initial_ans != NaN && initial_ans > 0) {
validInput = true;
message.innerHTML = "Guess a number!"
}
}
return(initial_ans);
}
For example a correct format will be 2,545.39.
The user must not to be able to enter anything except for what is show above.
The user must also enter in a valid input, for example a user can't enter in a value such as 002453.23, so they can't have 2 0's next to each other.
Use the below code:
var regex = /^\d+(\.\d{1,2})?$/i;
var key = $('textbox').val();
if ((key.match(regex) != null) || (parseInt(key) != 0)) {
$('textbox').val(key.replace(/^0+/, ''));
alert('legal');
}
else {
alert('illegal');
}
I called a class called test for my textbox. When I entered the first value for e.g. the first value as 4., then suddenly the output coming as 4.00. I just want to restrict entry only for two decimal places.
$(".test").keyup(function (event) {
debugger;
this.value = parseFloat(this.value).toFixed(2);
});
This small change to your code may suffice:
this.value = this.value.replace (/(\.\d\d)\d+|([\d.]*)[^\d.]/, '$1$2');
Essentially replace the decimal point followed by any number of digits by a decimal point and the first two digits only. Or if a non digit is entered removes it.
What about something like this:
$(".test").keyup(function (event) {
if ((pointPos = this.value.indexOf('.')) >= 0)
$(this).attr("maxLength", pointPos+3);
else
$(this).removeAttr("maxLength");
});
Here is a working fiddle.
you can use the maxLength attribute for that, try
$(".test").keyup(function (event) {
var last = $(this).val()[$(this).val().length - 1];
if (last == '.') {
$(".test").attr("maxlength", $(this).val().length+2);
}
});
You shouldn't worry about what the user has in the input until they submit the form. You really don't care what's in there before then. However, if you want to warn about invalid input, you can put a message on the screen if you detect non–conforming input, e.g.
<script>
function validate(element) {
var re = /^\s*\d*\.?\d{0,2}\s*$/;
var errMsg = "Number must have a maximum of 2 decimal places";
var errNode = document.getElementById(element.name + '-error')
if (errNode) {
errNode.innerHTML = re.test(element.value)? '' : errMsg;
}
}
</script>
You should probably also put a listener on the change handler too to account for values that get there by other means.
$(document).on("keyup", ".ctc", function ()
{
if (!this.value.match(/^\s*\d*\.?\d{0,2}\s*$/) && this.value != "") {
this.value = "";
this.focus();
alert("Please Enter only alphabets in text");
}
});
What I'm trying to achieve is a code checker. Only the first 4 numbers are important, the other numbers can be any number. The form will be used for users to put in productcodes.
The problem is that if the variable changes to say, 5 numbers the variable is false.
See below example:
http://jsfiddle.net/MZfxs/3/
If the user puts in the numbers 3541 the box changes color, but if the user put in the remaining numbers the value is set to false.
Additionally I'm trying to make the box only change color when 13 numbers are inserted AND the first 4 numbers are matching, in that order.
Solved!
Working Example:
http://jsfiddle.net/MZfxs/8/
If I understood correctly, you need a field value validation and the requirement is the value should start from 4 numbers like 7514 or 9268. Here you can use a regular expression to validate input value like:
// Will work for " 123433 " or "12345634 ", etc.
var value = $(this).val(),
re = /^\s*(\d{4})(\d+)\s*$/, // better to initialize only once somewhere in parent scope
matches = re.exec(value),
expectedCode = 3541,
expectedLength = 13;
if(!!matches) {
var code = matches[1]; // first group is exactly first 4 digits
// in matches[2] you'll find the rest numbers.
if(value.length == expectedLength && code == expectedCode) {
// Change the color...
}
}
Also if your requirement is strict to length of 13 than you can modify the regular epression to
var re = /^(\d{4})(\d{9})$/;
and retrieve first 4 numbers in first group and rest 9 in second group:
var matches = re.exec(value);
if(!!matches) {
var first4Digits = matches[1],
rest9Digits = matches[2];
// ...
// Also in this way you'll not need to check value.length to be 13.
}
You can break the string each time on key event fires. You can do this by calling js substring() method and take the first four characters and check it.
Try to use this:
<script>
$("input").keyup(function () {
var value = $(this).val();
$("p").text(value);
var value2 = $(this).val().substr(0,4);
if(value2 == 3541){
$(".square").css("background-color","#D6D6FF");
}else{
$(".square").css("background-color","yellow");
}
})
</script>
I'm a beginner and a student and I'm hoping someone can help me out. I have an assignment where I need the program to be broken up into 3 functions. The first takes a sentence from the user, the second converts the sentence into a new "pig language" depending on the length of each word, and the third displays the results in the console. I have the heart of this program done, but I have a problem with clearing out the return string. Specifically, once the user has gone through all 3 steps, I don't want them to be able to enter into the 3rd part of the program and see the results again. I want them to have to go back to the beginning. Sorry for drawing this out so much, but I'm just not sure of how else to explain it.
Here's my code:
function prog1(){
var userLang = prompt("Type in your sentence");
//If the user enters an empty string
if(userLang == ""){
console.log("You must enter a sentence");
}
//If the user presses cancel
else if(userLang == null){
wantToQuit = true;
}
//If the user enters in a good string
else {
console.log("Thank you, now go to program 2");
been2prog1 = true;
return userLang;
}
}
function prog2(){
//sets newLang = userLang and splits the string
var newLang = prog1Lang.split(" ");
//enters loop to find length of each split word
var x = 0;
for( x = 0; x < newLang.length; x++ ){
//if it's 5 or less words, add -oink
if ((newLang[x].length) <= 5){
newLang[x] += "-oink";
}
//if it's more than 5 words, add -a
else {
newLang[x] += "-a";
}
}
**newLang.join(" ");**
//put the string back together
console.log("String converted");
been2prog2 = true;
return newLang;
}
function prog3(){
var endLang = prog2Lang;
console.log(endLang);
**delete prog2Lang;**
}
I was thinking "delete" might work, as seen above, but I didn't do anything all all. Then I was thinking a Boolean, but I am not sure how to go about doing so. Any help would be much appreciated.
One last thing, I am also stuck on how to join my string back together. Currently it logs it in the console as being a part of the array and separates each word with quotes and a comma. I've looked up the .join(); and I thought it would do the trick, but it doesn't seem to work either. I put it inside of the if else statements in function 2 but, it just freaks out when I do that, so pointers on this issue would also be much appreciated.
Thank you!
Try assigning the newLang.join to itself..
newLang = newLang.join(" ");
I wasn't sure what the other bit was that you were having trouble with was, I was a bit confused.
if all you are trying to do is clear out a string variable then..
prog2Lang = null;
or
prog2Lang = "";
null is a null object and "" is an empty string.
Is that what you were after?