How can I make "You got it!" message to pop up when my input is not only 5, but lower or equal to 5?
document.getElementById("my-button").onclick = function() {
if (document.getElementById("my-input").value == "5") {
alert("You got it!")
} else {
alert("Opps, wrong number. Please try again.")
}
}
What is my favorite numbers?
<input type="text" id="my-input">
<button id="my-button">Submit</button>
You have to convert your value to a number using Number, and then compare it using <=.
document.getElementById("my-button").onclick = function() {
if (Number(document.getElementById("my-input").value) <= 5) {
alert("You got it!")
} else {
alert("Opps, wrong number. Please try again.")
}
}
What is my favorite numbers?
<input type="text" id="my-input">
<button id="my-button">Submit</button>
You need to convert the input value which is a string to number before comparing it.
In this case you can use parseInt
document.getElementById("my-button").onclick = function() {
if (parseInt(document.getElementById("my-input").value, 10) <= 5) {
alert("You got it!")
} else {
alert("Opps, wrong number. Please try again.")
}
}
What is my favorite numbers?
<input type="text" id="my-input">
<button id="my-button">Submit</button>
The value that u get from input type is string so u need to convert it to number with [ ParseInt, Number ] methods after that u can compare and everytings will work fine so i think it's better of u
let button = document.getElementById("my-button");
let value = document.getElementById("my-input");
button.on('click', function () {
if (Number(value) <= 5) {
alert("You got it!")
} else {
alert("Opps, wrong number. Please try again.")
}
});
have a nice game
A slight issue with your question is that the type of the input is text rather than number. You can change the type of the input by doing <input type=number id="my-input">.
If you want to keep the type you will have to check if the input is a number.
In either case you will have to convert the value of the input from string to number since numeric operations using strings are wrong most of the time (there are rare specific cases where the outcome is the same). The only difference between using text and number is having to check if the value of the input is valid, which you can do using isNaN after the conversion. I usually prefer forcing JavaScript to convert the text by using - 0 over parseInt or parseFloat, since it's scricter and will not convert "123test" to 123.
Here is a solution working with number
document.getElementById("my-button").addEventListener("click", function() {
if (document.getElementById("my-input").value - 0 <= 5) {
alert("You got it!")
} else {
alert("Opps, wrong number. Please try again.")
}
});
<input type="number" id="my-input">
<button id="my-button">Submit</button>
Here is a solution working with text
document.getElementById("my-button").addEventListener("click", function() {
var value = document.getElementById("my-input").value - 0;
if (isNaN(value)) {
alert("Not a number");
} else if (value <= 5) {
alert("You got it!")
} else {
alert("Opps, wrong number. Please try again.")
}
});
<input type="text" id="my-input">
<button id="my-button">Submit</button>
Actually when you access the value of <input> its a string. You can't use >,<,>=,<= between strings you use need to convert it into a number using parseInt()
document.getElementById("my-button").onclick = function() {
let value = parseInt(document.getElementById("my-input").value)
if (value <= 5) {
alert("You got it!")
} else {
alert("Opps, wrong number. Please try again.")
}
}
What is my favorite numbers?
<input type="text" id="my-input">
<button id="my-button">Submit</button>
Related
<!DOCTYPE html>
<html>
<body>
<div id="text" class="CommentBox">
Some text :
<input type="text" />
</div>
<script>
$(document).ready(function () {
jQuery("#text").on("change", function () {
var x = $('#text').value;
if (isNaN(x))
{
window.alert("You have entered not a number");
return false;
});
});
});
</script>
</body>
</html>
I am trying to write javascript code to check if the given value is not number.If not i would like to give error message? If it is number I would like to check if it is integer and between 0 and 100.
Basically you need to convert to an Int before compare it with NaN which means something like:
var x = $('#text').value;
if ( isNaN( parseInt(x) ) ) {
// Not a decimal number.
}
There are a lot of syntax errors in your code.
Your selector checks your div for the change event instead of your input, which means it will never trigger the code.
You should use .val() to get the value of an element when using jQuery selectors instead of .value.
You can also use the this keyword inside the event handler to get the referenced element.
Besides that there were some misplaced ) and } in your code.
Below I have included an working sample of your code.
$(document).ready(function() {
jQuery("#text > input").on("change", function() {
var x = $(this).val();
if (isNaN(x)) {
window.alert("You have entered not a number");
return false;
} else if (x > 0 && x < 100) {
alert("number in between 0 and 100");
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text" class="CommentBox">
Some text :
<input type="text" />
</div>
function numberOrNot(var input)
{
try
{
Integer.parseInt(input);
}
catch(NumberFormatException ex)
{
return false;
}
return true;
}
this will return true if your input is number, otherwise it will return false
try this code
you enter direct input on change or write id for input and pass it to javascript
$(document).ready(function() {
jQuery("input").on("change", function() {
var x = $('#text').val();
if (isNaN(x)) {
window.alert("You have entered not a number");
return false;
}
else{
if(x>=0 && x<=100)
{
window.alert("You have enter write number");
}else{
window.alert("You enter number between 0 to 100");
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="CommentBox">
Some text :
<input type="text" id="text" />
</div>
You can use try-catch and put as many conditions you want in try block Like this. I have put three conditions for now.
<script type="text/javascript">
function Validation(){
var number1=document.LoginForm.number1.value;
try{
if(number1==""){
throw "Empty";
}
if(isNaN(number1)){
throw "Not a Number";
}
if(number1<0 || number1>100){
throw "Out of range";
}
}
catch(err){
if (err=="Empty"){
alert("Number 1 and Number 2 fields cannot be empty");
}
if (err=="Not a Number"){
alert("Please enter a number");
}
if(err=="Out of Range"){
alert("Out of Range");
}
return false;
}
//return true;
}
</script>
I have two input field like this in my HTML:
<input type="text" class="txtminFeedback" pattern="^\d+([\.\,][0]{2})?$" placeholder="Minimum Feedback">
<input type="text" class="txtmaxFeedback" pattern="^\d+([\.\,][0]{2})?$" placeholder="Maximum Feedback">
I've tried several regex patterns like following:
^\d+([\.\,][0]{2})?$
or
(^[0-9]+$|^$)
or
/^\d*$/
None of these worked whatsoever with the following code in jQuery:
if ($('.txtminFeedback').val() == "" && $('.txtmaxFeedback').val() == "") {
if ($('.txtmin')[0].checkValidity() && $('.txtmax')[0].checkValidity()) {
if ($('.txtSearch').val() == "") {
ShowMessage("Please enter the search term!");
return;
}
else {
PostAndUpdate($('.txtSearch').val(), $('input[name=type]:checked').val(), $('input[name=shipping]:checked').val(), $('input[name=condition]:checked').val(), $('.txtmin').val(), $('.txtmax').val(), $('.txtNegativeKeywords').val(), $('.txtminFeedback').val(), $('.txtmaxFeedback').val());
}
} else {
ShowMessage("You have entered incorrect value for minimum or maximum price!");
return;
}
} else if (!$('.txtminFeedback')[0].checkValidity() || !$('.txtmaxFeedback')[0].checkValidity())
{
ShowMessage("Please enter only positive value for minimum and maximum feedback.");
return;
}
User can leave the txtminfeedback and txtmaxfeedback empty if he wants. However if he decides to enter some values, then both fields must be entered and will require to have entered only whole positive numbers (from 0 to 4 million).
What am I doing wrong here?
In the end this did it:
pattern="^(\s*|\d+)$"
if ($('.txtminFeedback')[0].checkValidity()==false || $('.txtmaxFeedback')[0].checkValidity()==false) {
ShowMessage("Please enter only positive value for minimum and maximum feedback.");
return;
}
if ($('.txtmin')[0].checkValidity() && $('.txtmax')[0].checkValidity()) {
if ($('.txtSearch').val() == "") {
ShowMessage("Please enter the search term!");
return;
}
else {
PostAndUpdate($('.txtSearch').val(), $('input[name=type]:checked').val(), $('input[name=shipping]:checked').val(), $('input[name=condition]:checked').val(), $('.txtmin').val(), $('.txtmax').val(), $('.txtNegativeKeywords').val(), $('.txtminFeedback').val(), $('.txtmaxFeedback').val());
}
} else {
ShowMessage("You have entered incorrect value for minimum or maximum price!");
return;
}
Just in case someone in future might need it.
Cheers =)
i need compare two values using Less Than or Greater Than, but it's not working fine. Here below my code.
//JAVASCRIPT
<script type="text/javascript">
function validform()
{
var balanvar = document.myform.balance.value,
currntvar = document.myform.currnt.value;
if( currntvar == "" ) { document.myform.currnt.focus(); document.getElementById("curntid").style.borderColor = "red"; return false; } // Must be filled error
if(currntvar > balanvar) { document.myform.currnt.focus(); document.getElementById("curntid").style.borderColor = "red"; return false; } else { document.getElementById("curntid").style.borderColor = "green"; } // Maximum value error
}
</script>
//HTML
<form name="myform" method="post" action="">
<input type="text" name="balance" id="balanceid" value="12000"/>
<input type="text" name="currnt" id="curntid"/>
<input type="submit" name="submit" value="Proceed" onclick="return validform();"/>
</form>
What i want is, i have to enter less than "balance" value in "currnt" text box, if i entered maximum value compare to "balance" text box mean, have to throw error message.
Problem Is, when clicking proceed without filling "currnt" it's showing error. and when entering value 15000 in "currnt" means its showing error. But when entering value 100000 in "currnt" means its not giving error. i don't know what error is this. please help me.
The .value property returns a string. hence you comparisons are done using string comparisons, which most of the time do yield other results than number comparisons.
To solve that, convert to numbers first using parseFloat() or parseInt():
function validform()
{
var balanvar = parseFloat( document.myform.balance.value ),
currntvar = parseFloat( document.myform.currnt.value );
if( isNaN( currntvar ) ) { document.myform.currnt.focus(); document.getElementById("curntid").style.borderColor = "red"; return false; } // Must be filled error
if(currntvar > balanvar) { document.myform.currnt.focus(); document.getElementById("curntid").style.borderColor = "red"; return false; } else { document.getElementById("curntid").style.borderColor = "green"; } // Maximum value error
}
I believe I have a fairly simple problem, but I am unfortunately unable to resolve it. I have searched for a while and tried several different variations of this code but cannot seem to get it to work.
All I am trying to do is check and see if my input value has a alpha character in it opposed to a number.
Here is my js function:
function checkLetters(input) {
var numOnly = /^[0-9]+$/;
var hasLetters = false;
if (!input.value.match(numOnly)) {
hasLetters = true;
}
return hasLetters;
}
and here is the code calling it:
<input type="text" name="cc_number" size="13" maxlength="11" onblur="
if(checkLength(cc_number.value) == true) {
alert('Sorry, that is not a valid number - Credit Card numbers must be nine digits!');
} else if (checkLetters(cc_number.value) == true) {
alert('Credit Card number must be numbers only, please re-enter the CC number using numbers only.');
}">
Any help or suggestions would be appreciated.
It looks like you're trying to validate credit card input. May I suggest a different approach?
function checkCardInput(input,errorId) {
var errorNoticeArea = document.getElementById(errorId);
errorNoticeArea.innerHTML = '';
if(!input.value) {
errorNoticeArea.innerHTML = 'This field cannot be left blank.';
return;
}
if(!input.value.match(/[0-9]/)) {
errorNoticeArea.innerHTML = 'You may only enter numbers in this field.';
input.value = '';
return;
}
if(input.value.length != 9) {
errorNoticeArea.innerHTML = 'Credit card numbers must be exactly 9 digits long.';
return;
}
}
See this jsFiddle for an example use.
You're passing cc_number.value as input, but then referencing input.value.match(), which works out to:
cc_number.value.value.match();
Just pass cc_number:
if (checkLetters(cc_number)) {
...
}
My if-else is not working, I think that I have a variable issue. When I look at the value of x it is not what is entered in the text field. Any Ideas?
function guess() {
var x = document.getElementById("magic");
var word = "please";
if (x == word) {
alert("You entered the magic word!");
} else {
alert("Please try again!");
}
}
<form>
What is the magic word?<br />
<input type="text" id="magic" onchange="guess()" />
</form>
You're not getting the value. Use this:
var x =document.getElementById("magic").value;
You want:
var x = document.getElementById("magic").value;
Also, onchange won't work, you'll need to use onkeyup, although onblur is probably more sane:
What is the magic word?<br />
<input type="text" id="magic" onblur="guess()" />
function guess() {
var x = document.getElementById("magic").value;
var word = "please";
if (x == word) {
alert("You entered the magic word!");
} else {
alert("Please try again!");
}
}
http://jsfiddle.net/6uAhq/
You need to check against the actual value of the "magic" element, e.g.:
var x = document.getElementById("magic").value;
I'm assuming "magic" is an input.