Getting value from text input using document.getElementByID not working - javascript

I'm doing a simple project with javascript and it requires me to get a value out of an HTML text input with javascript. In the following code I've found that nothing after line 6 works and I have no idea why. This has been driving me crazy for like two hours and I'm kind of at my wits end. Please help!
function letsPlayAGame() {
var answer = Math.floor(Math.random() * 100 + 1);
var guess = document.getElementByID("theinput").value;
if (Number.isInteger(guess) == false) {
document.getElementByID("label").innerHTML =
"Please enter a number between 1 and 100!";
} else if (guess < 1 || guess > 100) {
document.getElementByID("label").innerHTML =
"Please enter a number between 1 and 100!";
} else {
alert("not this part");
}
}

It should be:
document.getElementById
instead of
document.getElementByID
as Javascript is case sensitive.

Related

Javascript Phone Validation

I want if phone number starts with + it should accept 12 digits if it does not contain + it should accept 10 digit what changes I have to do?
My code is attached below.
function phvalid()
{
var a = document.getElementById('phone').value;
var gb = /^([0|\+[0-9]{1,5})?([7-9][0-9]{9})$/;
if (a=="") {
document.getElementById('ph').innerHTML="Enter Number";
}
if (a.match(gb))
{
document.getElementById("ph").innerHTML="";
// return true;
}
if(a.length!=10)
{
document.getElementById("ph").innerHTML="Enter 10 digits";
return false;
}
if(a.indexOf("+")==0)
{
document.getElementById("ph").innerHTML="Enter 12 digits";
return false;
}
else
{
document.getElementById('ph').innerHTML="";
}
}
Hope this will help you..!! I have used the simple startwith method.
function phoneValidator() {
var number = document.getElementById('phoneNumber').value
if(number.startsWith("+")) {
document.getElementById("phoneNumber").maxLength = 12;
}
else {
document.getElementById("phoneNumber").maxLength = 10;
}
}
<input type="text" name="phoneNumber" id="phoneNumber" onkeyup="phoneValidator()"/>
Firstly, your check for 10 digits overrides your check for 12. What I would do is:
function phvalid()
{
let phone = document.getElementById('phone');
let regex = /^([0|\+[0-9]{1,5})?([7-9][0-9]{9})$/;
if (phone.value=="") {
phone.innerHTML="Enter Number";
}
if (phone.value.match(regex))
{
phone.value.innerHTML="";
// return true;
}
if ( phone.value.charAt(0) != '+' && phone.value.length != 12 ){
if ( phone.value.length != 10 ){
phone.innerHTML = "Please enter a valid phone number, it should be 10 digits unless it is international in which case it should be 12 prefixed by a +";
return;
} else {
// Do whatever you need to do for a 10 digit phone number
}
} else {
// Do whatever you need to do for a 12 digit number
}
}
It is always easier to read your code later if you explain what you are doing, to yourself. The nested if, yes you could do it all on one line or use an iif there but when you come back to read it later, this will probably be easier to understand. I also set the result of the document.getElementById to a variable for both less typing and to make it clear what you are modifying. Your code you are modifying a different element. If that's what you are trying to do, it is still easier than calling getElementById every time you wish to modify it, calling and storing it means you only have to change it in one place if your code changes later instead of having a weird bug because you forgot to change it somewhere.
If I'm reading your regex right, the 10 digit phone number must start with a 0? It might be better to use:
let regex=/(^\+?\d{10,12}$)/;

check if input form value (int) is less than expected

My question is about validating a form. I am doing a validation of two fields, one of them receives the value in decimal, example ($ 500.00), is already with mask.
In this field that receives the value, it can not be less than 300.00.
If it is smaller 300.00, a message will appear saying the value has to be greater than 300.00.
Summary: The validation checks that it is empty, but does not check if the (number) int is less than $ 300
I'm using it this way (there's more code, in short):
function valid_simulation(form1) {
if (form1.valor.value == ' ') {
alert("value is not valid");
return false;
}
if (form1.valor.value <= 300) {
alert("value is not valid");
return false;
}
}
Thanks for any help.
Your basic concept is correct: set the message when the if statement test is falsy. Something like the following:
function showFormError(message) {
$("#alertBox").text(message)
}
if (isInvalid) { showFormError("We have a problem.") }
If the dollar mark is the issue, You can split it and validate.
var userInput = $("#inputData").val();
if(userInput.includes("$")) {
var splitArray = userInput.split("$");
if (typeof splitArray[1] && parseFloat(splitArray[1]) < 300){
alert("Amount Not valid");
}
}

Trying to make keydown number turn red if wrong in comparison

Can someone please help implement something in my javascript project? #http://codepen.io/urketadic/pen/YpLgBX
I want number to turn red if its wrong and not in sequence with pi. Its really difficult for me to keep count and compare with everything.
I've tried a lot of this and at the end I've come up with this code:
var count = 0;
// color the mistake right away
$("#inputsm").keyup(function(event) {
var pressed = event.key;
answer = $("#inputsm").val();
pisub = pi.substr(input,answer.length)
if (pressed!=="Backspace"&&pressed!=="Delete") count++;
else count--;
console.log(count);
});
I'm just confused, i don't know how i can do this. Also does text area even allow numbers to turn red? I've tried adding jquery css as well but it doesn't work. Can someone write it in their own codepen and post a link?
Take a look at this fiddle: https://jsfiddle.net/ebv5n64j/2/
I've put together something that does basically what you are trying to do. You can modify it from there but that is the basic concept. I designed mine to not let the user continue until they get it right, but you could easily change that.
This is a snippet, but jsfiddle has the complete working version:
// If it's a delete command
if(code === 8){
if(!$("#wrong").length > 0)
inputCount = (inputCount === 0 ? 0 : --inputCount);
$("#pi span").last().remove();
console.log(inputCount);
} else if (code >= 48 && code <= 57) {
var inputNumber = code - 48;
var numSpan;
$("#wrong").remove();
numSpan = $("<span>"); // make a new one
// Append the number
numSpan.text(inputNumber);
numSpan.removeClass("incorrect");
if(String(inputNumber) === piDigits[inputCount]){
numSpan.addClass("correct");
inputCount++;
} else {
numSpan.attr("id", "wrong");
}
$("#pi").append(numSpan);
placeCaretAtEnd(this);
}
So I looked at your pen and thought that you were somewhat over-complicating the solution. I think a better way would be to compare the string of the input textarea with the substring of pi. Anyways, here's the fixed code and I've linked to the pen with the working version.
By the way, you mention in the description that if they want to start at the number 4 in 3.14 they should type in 1 (for index 1), but you take their input and subtract it by 1, so it essentially starts them off at 1 instead of 4, if they typed in 1.
$("#inputsm").keyup(function() {
var thisLength = parseInt(input) + $(this).val().length - 1;
if($(this).val().trim() === pi.substring(parseInt(input), thisLength)) {
console.log("good so far!");
$(this).removeAttr('style');
} else {
console.log("ahhh no good!");
$(this).css('background', 'red');
}
});
http://codepen.io/msafi/pen/dOKogK/

JAVASCRIPT HELP - code not working

My code isn't working, can someone please tell me what the problem is?
I'm guessing it's the for loop, but I cannot find the problem.
<html>
<body>
<script>
username = prompt("Please enter a your username:");
for (var i = 0; i < username; i++) {
if(isFinite(username.charAt(i))) {
result = true;
document.write("The username consists of one or more numbers." + BR);
}
else {
result = false;
document.write("The username must consist of one or more numbers." + BR);
}
}
</script>
</body>
</html>
You have two problems in your code:
In the for loop, use the length of the variable to establish the stop condition
for (var i = 0; i < username.length; i++)
BR is not defined
Working code: http://jsfiddle.net/f643fr4w/
From the output I can probably assume you just want to check if username consists of at least one number, actually: a digit.
// iterate over the input
for (var i = 0; i < username.length; i++) {
// check if it is a number (not a digit but that's the same here)
if (isFinite(username.charAt(i))) {
result = true;
// The requirement "one or more numbers" is fulfilled,
// we can break out of the loop
break;
}
else {
result = false;
}
// print something according to "result"
if(result === true){
document.write('The username consists of one or more numbers.');
} else {
document.write('The username must consist of one or more numbers.');
}
}
You have to go over the full length of the string to find out if there's no number but not if you want to find out if there is any number in it.
Now, if you want to test if it consists of only digits you have to reword the requirements, they are a bit too ambiguous now.
Additional hints:
you need to check the input, you always have to check user input!
you need to be aware that JavaScript strings are UTF16. Rarely a problem but gets easily one if you iterate over JavaScript strings.
String.charAt() returns a character, not a number. Don't rely on the automatic conversions in JavaScript, you way too easily shoot yourself in the foot if you rely on it but also if you don't, so be careful.
please don't use document.write, use either the console if available or change the text-node of an HTML element.
With these points in mind you may get something like this:
// make a list of digits
var digits = ['0','1','2','3','4','5','6','7','8','9'];
// ask the user for a username
var username = prompt("Please enter a your username:");
// check input
if (username.length === 0) {
console.log('no username given');
} else {
for (var i = 0; i < username.length; i++) {
// indexOf searches for the same type, that's why the digits above
// are strings with quotes around them
if (digits.indexOf(username.charAt(i)) >= 0) {
result = true;
// The requirement "one or more numbers" is fullfilled,
// we can break out of the loop
break;
}
else {
result = false;
}
}
// print something according to "result"
if (result === true) {
console.log('The username consists of one or more numbers.');
} else {
console.log('The username must consist of one or more numbers.');
}
}
The above is one variation of many and could easily give rise to a heated discussion on some forums (not here! Of course not! ;-) ) but I hope it helps.
Use a regex for such shenanigans:
var username = prompt("username plz kk thx");
var result = /[0-9]/.test(username);
document.write("The username " + (result ? "consists" : "must consist") + " of one or more numbers");

javascript check for a special character at the end of a string

I am getting value from a text field. I want to show an alert message if a special character, say % doesn't appear at the end of entered input.
Usecases:
ab%C - show alert
%abc- show alert
a%bc- show alert
abc%- ok
The regex i came up so far is this.
var txtVal = document.getElementById("sometextField").value;
if (!/^[%]/.test(txtVal))
alert("% only allowed at the end.");
Please help.
Thanks
No need for a regex. indexOf will find the first occurrence of a character, so just check it it's at the end:
if(str.indexOf('%') != str.length -1) {
// alert something
}
2020 edit, use string.endsWith()
You don't need regex to check for this at all.
var foo = "abcd%ef";
var lastchar = foo[foo.length - 1];
if (lastchar != '%') {
alert("hello");
}
http://jsfiddle.net/cwu4S/
if (/%(?!$)/.test(txtVal))
alert("% only allowed at the end.");
or to make it more readable by not using a RegExp:
var pct = txtVal.indexOf('%');
if (0 <= pct && pct < txtVal.length - 1) {
alert("% only allowed at the end.");
}
Would this work?
if (txtVal[txtVal.length-1]=='%') {
alert("It's there");
}
else {
alert("It's not there");
}

Categories

Resources