jQuery live validation - javascript

I'm trying to create a live validation script for a form. I've somewhat got it, I think anyway...but the error message comes up when there is text in the field as opposed to when there is no text. I'm sure I'm doing something stupid wrong, I'm pretty sure I have the if values right, value == '' is if value is nothing, value !== '' is if value is not nothing, right? Gah, maybe it's the on/change thing I should change? Hope you can help. Thank you.
http://jsfiddle.net/Vjwxs/3/
$(document).ready(function () {
$('#name').on('change', function() {
var name = $("#name").val();
if (!this.value == '') {
$("#errorname").fadeIn();
$('#errorname').css("display", "inline-block");
$('#errorname').css("color", "#838383");
$('#errorname').css("background-color", "#fff568");
}
else if (!this.value !== '' ) {
$("#errorname").fadeOut();
$('#errorname').css("display", "none");
}
});
});

Read your if conditions out loud. That should help you realise where the problem is:
if (!this.value == '') { /* Show the error */ }
"If not this value is equal to an empty string". Or, in a more understandable form, "If this value is not equal to an empty string". You actually want to show the error "if this value is equal to an empty string".
if (!this.value !== '' ) { /* Hide the error */ }
"If not this value is not equal to an empty string". And again, more readable, "If this value is not not equal to an empty string". You actually want to hide the error "if this value is not equal to an empty string".
Your code will work if you remove the first negation from both conditions.

Related

convert string to boolean and compare with if condition in js

I have an attribute where I have got condition .I took that condition from tag's attribute now I want place that condition in if block and get result.
my code:-
<div myCondition="1 == 2" id="hey"></a>
<script>
var a = document.getElementById('hey');
var x = a.getAttribute('myCondition');
if(x){
console.log('accepted')
}else{
console.log('not accepted')
}
</script>
above program should return not accepted
value of myCondition attribute can be very complex for example:-
'hello' == 'hello'
5>1 etc
I guess what you need is the eval function. As it says in the provided link:
The eval() function evaluates JavaScript code represented as a string.
So, you can change your code like this:
if( eval(x) ){
console.log('accepted')
}else{
console.log('not accepted')
}
P.S: That being said, I don't think doing it like this really safe.

Make user input start with either "BR" or "BT"

I have an input field and I would like for it to check if the input entered starts with either "BR" or "BT". So for example BR1234 would be valid but JH1234 would not be valid. At the moment I can only get it to check "BR" and not "BT".
This is the code I have so far:
if (ID.indexOf('BR') === 0) || (ID.indexOf('BT') === 0){
}
else {
ID = "Invalid ID"
document.getElementById('ID').innerHTML = ID
return false;
Check that you have the proper parentheses in the right positions. The condition for your if statement only contains ID.indexOf('BR') === 0 because you already closed the parenthesis for it.
if (ID.indexOf('BR') === 0 || ID.indexOf('BT') === 0) {
// ...
}
You can also use String.prototype.startsWith to check if a string starts with the desired string.
if (ID.startsWith('BR') || ID.startsWith('BT')) {
// ...
}
You can use JavaScript startsWith method. Check if it helps.
Try this: if(ID.test(/^(B(R|T))/)==true){//do stuff} Remember your old friend RegExp.

How to test the null value condition in Javascript?

Below is the code,
<p id="sayHello"></p>
<script type="text/javascript">
var yourName = window['prompt']("What is your name?");
if (yourName != null) {
window['document']['getElementById']("sayHello").innerHTML = "Hello " + yourName;
} else {
window['alert']("Please enter your name next time");
}
</script>
for which, else block need to get executed based on the input given in prompt.
What should be the input in prompt box to test null value of primitive type Null?
When you click cancel on the prompt box the else block will get executed.
Per the MDN window.prompt docs:
If the user clicks OK without entering any text, an empty string is returned.
So really you want to check if (yourName !== null && yourName !== "") since the prompt is really returning the empty string (thus causing your else clause to be executed incorrectly since it's passing the not null check).
I think you actualy looking for empty string.Also null is a primitive value & null represent an "empty" value, that is no object value is present.
So to check null we can use
if(somVar === null && typeof somVar ==='object')
So you can arrange you code as
var yourName = window['prompt']("What is your name?");
if (yourName === null & typeof(yourName) ==='object') {
alert("Please enter your name next time");
} else {
document.getElementById("sayHello").innerHTML = "Hello " + yourName;
}
Also note this will ONLY test for null and will not pass for "",undefined,false,0 & NaN.
Beside is there any reason to use
window['document']['getElementById']("sayHello")
when it can be done like this
document.getElementById("sayHello").innerHTML
If you are checking for empty string , then you also have to validate that input is not empty
DEMO

Javascript: Ensure Input is Numbers Only

I have a unit conversion script; my HTML contains radio buttons (to pick the units), an input field, an output field and a button.
Here's a sample of my Javascript file:
[...]
window.addEventListener("load", function(){
document.getElementById("convert").addEventListener("click", function(){
var initial = document.getElementById("initial").value;
document.getElementById("answer").innerHTML = convertObj.converted(initial);
});
[...]
});
function ConvertClass(){}
ConvertClass.prototype.converted = function(initialAmount){
if(document.getElementById("kilograms").checked) {
this.calculation = this.multiply(initialAmount, 2.2046);
} else if(document.getElementById("pounds").checked) {
this.calculation = this.divide(initialAmount, 2.2046);
}
return this.calculation.toFixed(2);
}
[...]
var convertObj = new ConvertClass();
I would like to add something that ensures a) an empty input field isn't considered a "0", and b) something other than a number doesn't display "NaN" as the answer. In both cases, I'd simply like my output to return nothing (blank). I don't want it to do nothing, in case the user submits a blank field or an invalid value after a correct number submission (which I think would result in the previous answer still being displayed.)
How do I write that? I'm assuming I should use conditions, but I don't know which ones. I did a bit of research and apparently using isNaN() isn't entirely accurate, at least not in this context.
Where do I put the code, in the function triggered by the page load or the one triggered by the button?
I'm still learning so, if possible, I'd really appreciate explanations along with the edited code. Thank you!
Inside ConvertClass.prototype.converted at the beginning of the function, add:
// this coerces it to a number instead of a string
// or NaN if it can't convert to a number
initialAmount = initialAmount.length > 0 ? +initialAmount : 0/0;
// if not a number, return empty string
if (isNaN(initialAmount)) {
return "";
}
If the input is an empty string 0/0 evaluates to NaN.
Add the following function to check whether a value in Integer.
function isInt(value) {
return !isNaN(value) &&
parseInt(Number(value)) == value &&
!isNaN(parseInt(value, 10));
}
Change your load function like this:
window.addEventListener("load", function(){
document.getElementById("convert").addEventListener("click", function(){
var initial = document.getElementById("initial").value;
if(isInt(initial)){
document.getElementById("answer").innerHTML = convertObj.converted(initial);
}else{
document.getElementById("answer").innerHTML = '';
}
});
This will make sure that when a valid integer is supplied then only it will convert otherwise answer remain empty.
For further reading on how to check integer check this:
How to check if a variable is an integer in JavaScript?
Edit: setting answer to empty string when number not integer.

How to check value of a textbox that contain _age at the end?

This might be some odd question but it is the problem I am facing. I have textBox with Id like:
"pax_9495237e-5c9e-489f-8700-2f82e211fd51__Age"
"pax_9495237e-9h7e-489f-8700-2f82e211fd51__Age"
"pax_9495237e-9k2e-489f-8700-2f82e211fd51__Age"
Now I want to check if all Textboxes consist of __Age at the end, has numeric value or not. If not numeric(INT) i.e. characters(no .) not allowed then make an alert.
Please help me I don't know how to do it. I know I have a class option but I want to do by Id.
To select you input, you can use this :
$('[id$="__Age"]')
Then to know if is a number
$('[id$="__Age"]').each(function(){
if(isNaN(parseInt($(this).val()))){
alert(this,id + ' is not a number');
}
})
Fiddle : http://jsfiddle.net/3B9Vp/
In order to get all input ending with "__Age" you can use the jquery selector
jQuery( "[attribute$='value']" )
You can find more details here
So, in your occasion you can call:
$('input[id$="__Age"]');
where all text boxes with an id ending in "__Age" will be returned.
In order to validate if the input is numeric you can check the value of each textbox and use isNaN function provided in Javascript
Here is an example where there are 3 text boxes and you call a function to check if their current value is numeric or not.
Try like this
$(document).ready(function(){
$("input[type='text'][id$='__Age']").each(function(){
if(isNaN(parseInt($(this).val())))
alert('Not an Integer');
else
alert('It is an Integer');
});
});
It will check all the textbox values that are ids ended with '__Age'
Something like:
$("textarea").filter(function(i) { return $(this).prop("id").indexOf("__Age") !== -1; })
http://api.jquery.com/filter/
http://api.jquery.com/jQuery.inArray/
How to check whether a string contains a substring in JavaScript?
Working Example
// an array of e.which|e.key codes that is every key code for every number and control (like shift, backspace, etc..)
var numsNcontrols = [48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105,8,9,13,16,17,18,19,20,32,33,34,35,36,45,46,44,145,37,38,39,40];
// first grab all inputs ending with "__Age", then asign "keydown" check for improper characters
$("input[type=text]").filter(function(i) { return $(this).prop("id").indexOf("__Age") !== -1; }).on("keydown", function(e) {
if ($.inArray(e.which, numsNcontrols) == -1) return false;
}) // now, using jQuery Chaining, we continue and asign keyup event to alert users they cannot enter anything but numbers
.on("keyup", function(e) {
if ($.inArray(e.which, numsNcontrols) == -1) alert('Numbers only please!');
})
// simple check value update to show how many textboxes end in "__Age"
$("#bil").val(
$("input[type=text]").filter(function(i) { return $(this).prop("id").indexOf("__Age") !== -1; }).length
+ " textboxes have __Age at end of ID."
);
// Shows in a textbox how many textboxes end in "__Age" && have a numeric value
$("#bad").val(
$("input[type=text]").filter(function(i) { return $(this).prop("id").indexOf("__Age") !== -1 && !isNaN(parseInt($(this).val())); }).length
+ " textboxes have __Age at end of ID && numeric value."
);
¡ALSO! Find a pretty full listing in one big object (full of smaller objects and arrays) of Key Codes here
If you only need to show one alert when any of the inputs with __Age at the end has nonNumeric values then you can try something like this:
if($("input[type='text'][id$='__Age']").filter(function(){
return !isNaN($(this).val()); //leave only those inputs with nonNumeric value
}).length) //count their lenght - if it's > 0 then show alert
alert('There are inputs with "nonNumeric" values!');

Categories

Resources