I've recreated a problem in one of my projects. I have no idea why this doesn't work. It seems to fail when I add the textbox. For some reason, using a textbox is creating this error.
<input type="text" id="apple">
<input type="button" value="Go" id="banana">
<script>
var element = document.getElementById('apple');
var element2 = document.getElementById('banana');
element2.addEventListener("click", function(){
var test = element.value;
if (typeof test != "number"){
alert();
}
});
</script>
Fiddle: https://jsfiddle.net/3mp0869s/8/
element.value; will return always string, so the condition will be never acheived, you should parse the value returned. or if you want just to check if the value of input is a number you can use isNaN() function :
if(isNaN(element.value)){
alert('is not a number');
}else{
alert('is a number');
}
NOTE : you can also use input with type number so you don't have to check.
Hope this helps.
Try this code:
if (isNaN(test)){
alert("Not a number");
}
Here is your updated jsfiddle : https://jsfiddle.net/3mp0869s/9/
Related
I am trying to find the value of an input by className using pure JavaScript. When I run similar code for and ID it works, but when I try with a class name it returns undefined. I am able to do this with jQuery but I want to achieve it with pure JavaScript to have a better understanding of the language. Thank you!
JAVASCRIPT
var input1 = document.getElementsByClassName("blank1");
var submit = document.getElementsByClassName("submit");
correctAnswer = 'hello';
submit[0].addEventListener('click', checkFillIn);
function checkFillIn(){
if ( input1[0].value === correctAnswer ){
console.log('correct!');
}else{
console.log('incorrect');
}
}
HTML
<p><input id="blank1" value="" type="text"></input></p>
Submit
Please add class attribute on your input element. See example below:
<input id="blank1" class="blank1" value="" type="text">
Of course, you wouldn't want to make the id same with the class attribute.
Ot returns undefined because you have an error in your syntax:
getElementsByClassName(blank1)
blank1 was the ID not the class
This should work:
var input1 = document.getElementById("blank1");
var submit = document.getElementsByClassName("submit");
correctAnswer = 'hello';
// submit is an array getElementsByClassName returns an array of elements
submit[0].addEventListener('click', checkFillIn);
function checkFillIn(){
if ( input1.value === correctAnswer ){
console.log('correct!');
}else{
console.log('incorrect');
}
}
<p><input id="blank1" value="" type="text"></input></p>
Submit
The error in your code is on line 1, where you get the first Element in javascript. It should be:
var input1 = document.getElementById("blank1");
This is because blank1 is an ID, not a class name.
Hope this helps!
you need to change var input1 = document.getElementsByClassName("blank1");to var input1 = document.getElementsById("blank1");or add class="blank1"to your input .
I want to check if the value entered by the user is a valid integer using jquery
I have tried this code but it always seems to return true:
if ((manageridEntered === "") || ($.isNumeric(manageridEntered))) {
success = false;
}
You could use classic JavaScript :
var isNumber = Number.isInteger(yournumber);
Or if you want to check if it isn't (without using !) :
var isNaN = Number.isNaN(yournumber);
console.log(Number.isInteger(0.1)); // false
console.log(Number.isInteger(1)); // true
console.log(Number.isInteger(-100000)); // true
console.log(Number.isInteger(Math.PI)); // false
console.log(Number.isInteger(-Infinity)); // false
console.log(Number.isInteger(true)); // false
console.log(Number.isInteger(NaN)); // false
console.log(Number.isInteger(0)); // true
console.log(Number.isInteger("10")); // false
No need to use jquery
You can use javascript isNaN()
isNaN() accepts decimal numbers also
return !isNaN(manageridEntered))
or
You can use plain javascript regex here to match only digits
return new RegExp('^\\d+$').test(manageridEntered))
You can use vanilla JavaScript:
success = !manageridEntered.length || parseInt(manageridEntered) == manageridEntered;
Use regex
var intRegex = /^\d+$/;
var floatRegex = /^((\d+(\.\d *)?)|((\d*\.)?\d+))$/;
var str = $('#myTextBox').val();
if(intRegex.test(str) || floatRegex.test(str)) {
alert('I am a number');
}
Example taken from checking if number entered is a digit in jquery
$('.submitBtn').click(function() {
var Number = $('#Number').val();
if ((Number === "") || ($.isNumeric(Number))) {
alert('Valid NUmber');
}else{
alert('Not Valid NUmber');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form method="post" action="">
Inateger Value: <input type="text" name="Number" id="Number" />
<input type="submit" value="Submit" class="submitBtn">
</form>
isNumeric is checking for a number (which could be wrapped in a string too), not an integer. Beside that isNumeric() is not always returning true like you can see in the following snippet using JQuery 2.1.1.
console.log($.isNumeric('a')); // false
console.log($.isNumeric('1')); // true
console.log($.isNumeric(1)); // true
console.log($.isNumeric(1.5)); // true
console.log($.isNumeric('1.5')); // true
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Please try this:
if(Math.floor(manageridEntered) == manageridEntered && $.isNumeric(manageridEntered)){
//code here
}
Using Regex you can achieve it see below code
$(document).ready(function () {
$("#button").on("click", function () {
var patt = new RegExp("^[0-9]*$");
if (patt.test($("#number").val())) {
alert("true")
} else {
alert("false")
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="number" />
<input type="button" id="button" value="Check"/>
returns true if it's an integer
if(manageridEntered == parseInt(manageridEntered))
I created a basic program where user input is turned into an alert on submission. I can't figure out why the program only works as intended if I use false rather than true as the first condition in my if/else statement. I'm sure this is very basic but I've failed to find anything of relevance. After a long search I decided to post the question. Any answers will be greatly appreciated.
The HTML:
<form id="greetingForm">
<input type="text" name="userInput" id="userInput"/>
<input type="submit" value="click" id="submit"/>
</form>
The broken script:
function output(){
var input = document.getElementById('userInput').value;
if(input == true){
alert(input);
}else{
alert('Say something!');
}
}
function init(){
var greetingForm = document.getElementById('greetingForm');
greetingForm.onsubmit = output;
}
window.onload = init;
The working script:
function output(){
var input = document.getElementById('userInput').value;
if(input == false){
alert('Say something!');
}else{
alert(input);
}
}
function init(){
var greetingForm = document.getElementById('greetingForm');
greetingForm.onsubmit = output;
}
window.onload = init;
The variable input will never be equal to the boolean true because it is a string. Try changing it to:
function output(){
var input = document.getElementById('userInput').value;
if(input != ""){
alert(input);
}else{
alert('Say something!');
}
}
To clarify ferd tomale's answer, it's one of the "weird" type conversion cases where a check on equality to true does not behave in the same way as check on equality to false.
"" == false -> true
"a" == false -> false, but
"" == true -> false
"a" == true -> false
You can switch to using typesafe comparison operators (===, !==), which behave much more predictable, but then you'll have to convert values to the correct type yourself. Or you can learn the quirks of JS's automatic type conversion when you use == or !=.
Because your input is a string. And string == true will be false.
You can set breakpoints to check them.
I am managing to check the value inside a postcode input field using the following:
html:
<input type="text" class="cart-postcode2" size="10" tabindex="22">
JQuery:
$('.cart-postcode2').keyup(function(){
var value = $(this).val();
if (value.indexOf('BT') >= 0) {
alert("is ireland");
}
})
This is working great however I want it to only alert if it starts with BT and does not contain BT in any part of the value, does anyone know if this is possible?
So typing BT2 9NH will alert "Ireland" but typing OX2 8BT will not
You can check if string starts with BT, as indexOf() will give index zero if value stats with BT
$('.cart-postcode2').keyup(function(){
var value = $(this).val();
if (value.indexOf('BT') == 0) {
alert("is ireland");
}
})
a regex solution:
$('.cart-postcode2').keyup(function(){
var value = $(this).val();
if (value.match(/^BT/)) {
alert("is ireland");
}
})
hi guys i have a html form where i have a textfield which is having capabilities to enter two digits the first digit is autopopulated to be 0 and i donot want users to change that hows that possible using javascript or jQuery or anything else.
Here is another way.
the onKeyUp might not be how you want it to work but at least you have some ideas
<script>
window.onload=function() {
document.getElementById('part2').focus();
}
</script>
<form onSubmit="this.realvalue.value='0'+document.getElementById('part2').value">
<input type="text" name="realvalue" value="">This can be hidden<br />
<input type="text" style="border-right:0; width:12px" value="0" readonly="readonly" size="1"><input type="text" id="part2" style="border-left:0; width:13px" size="1" maxsize="1"
onKeyUp="this.value=(this.value.length>1)?this.value.substring(-1):this.value">
<input type="submit">
You can use the event "keyup" triggered when the user enters text in the field:
$('#my-input').keyup(function() {
var theInputValue = $(this).val();
// Do whatever you want with the value (like check its length,
// append 0 at the beginning, tell the user not to change first
// character
//
// Set the real value
$(this).val(newValue);
});
You may be better off with a '0' as text in front of a textbox that can only accept a single digit and then prepend the '0' programmatically?
I wrote and tested this code, and works exactly as you expect:
$(function (){
$('#input_id').bind('input',function (){
var val = $(this).val();
var r = val.match(/^[0][0-9]$/g);
if (r !== null){
val = r[0];
if (val.length === 1){
val = '0' + val;
}
}else{
val = '0';
}
$(this).val(val);
});
});
And works for copy/paste too =]