Data Validation: isNaN not working with this.value - javascript

Is it possible to use the isNaN() function to check if textbox value is a number without listing each field? I tried the below coded and it does not work properly. It triggers my alert regardless of what is input.
var numberCheck = function() {
var i = this.value
if(isNaN(i)==true) {
alert("You must enter an number value!");
}
}

I figured out how to do what I wanted to do. I had to define the parameters of the function as the ID of the element.
onkeyup = "numberCheck(this.id);"
var numberCheck = function(myID){
if(isNaN(document.getElementById(myID).value)){
alert("You must enter an number value!" );
};
}

Related

Display message in Chrome if wrong type is entered in input field

In Chrome (55.x) if a user attempts to enter mismatched type into an input (in my case a number input) nothing outwardly appears to happen. To enhance usability I'd like to display a popup to let users know they're trying to enter invalid data rather than have them thinking the input is 'broken'.
This is easily achieved with pure JS in FF (which allows mismatched type to be entered, it just isn't valid):
input.addEventListener('input', function() {
if (!this.checkValidity()) {
this.value = '';
console.log('please enter a number!');
}
}
Because Chrome doesn't actually input anything, however, the validity check always passes as the input is empty; it doesn't appear to do anything with the incorrect input except ignore it.
Is there any way to override this behaviour, or otherwise achieve the intended effect?
Sure, you could do a listener for keyup and it will give you the key that was pressed.
<script>
var numInput = document.getElementById("num");
numInput.addEventListener("keyup", function(e) {
if (isNaN(String.fromCharCode(e.which))) {
alert("Must be a number");
}
});
</script>
How about setting a last input value and check like this?
let input = document.querySelector('input');
let lastInput = input.value;
input.addEventListener('input', (e) => {
if (e.target.value === lastInput) {
alert("Input must be a number");
}
lastInput = e.target.value;
});

Detect when text is entered into the textarea and change it correspondingly

I have a textarea where users can enter or paste email addresses of other people and send them an invite after pressing Submit button. Each email must be seperated with a comma and valid before the form is submitted - validation is taken care of by jQuery Validate plugin & multiemail method.
Problem
Some people paste email addresses directly from their email clients and those emails are often in a weird format - containing name and surname before the actual email, or the email is wrapped in < >. For example:
"The Dude" <the.dude#gmail.com>, "The Dudette" <thedudette193#gmail.com>
Question
What I want to do is to Extract all email addresses from bulk text using jquery, but I'm having problems integrating this piece of code to work with my textarea - I don't know where to start.
How could I use the code from the above answer to extract each email entered into the textarea after a comma is typed or when the focus is moved away from textarea? So if I paste "The Dude" <the.dude#gmail.com> and type , after it or switch focus away, the entered value would change to the.dude#gmail.com.
I'm guessing something like this :
var textarea = $('#emails');
textarea.on({
keyup: function(e) {
if (e.which === 188) check();
},
blur: check
});
function check() {
var val = $.trim(textarea.val()),
err = '';
if (!val.length) {
err = 'No input ?';
return;
}
var emails = val.split(','),
notvalid = [],
temp = [];
$.each(emails, function(_,mail) {
mail = $.trim(mail);
if ( mail.length ) {
var m = mail.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
if (m) {
temp.push(m);
}else{
temp.push(mail);
notvalid.push(mail)
}
}else{
temp.push(mail);
}
if (notvalid.length) err = 'Not valid emails : ' + notvalid.join(', ');
});
$('#error').html(err);
textarea.val((temp.length ? temp : emails).join(', '));
}
FIDDLE
you can detect when an textarea is changed (or other input field) by using an eventhandler. Jquery supports multiple events (have a look here http://api.jquery.com/category/events/). In this particular case I should use the keyup event for triggering the extractEmails function. This way your extraction will be "live". However, it is also possible by catching a blur or change event.
With keyup eventhandler
http://jsfiddle.net/kasperfish/9hLtW/5/
$('#text').on('keyup',function(event) {
emails=extractEmails($(this).val());
$("#emails").text(emails);
});
function extractEmails (text)
{
return text.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
}
This will convert the entered text to emails when you either lose focus, or enter a comma, as you requested:
function extractEmails (text)
{
return text.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
}
$("#emailtext").on('keypress blur', function(e) {
if (e.which === 44 || e.type =="blur")
{
$('#emails').text(extractEmails($("#emailtext").val()));
}
});
Here's the fiddle:
http://jsfiddle.net/Mj2KM/

If a specific value is inputed into an input box, display a message using javascript

I'm can't figure out a way of displaying a message if a specific word is inputed into an input box. I'm basically trying to get javascript to display a message if a date, such as '01/07/2013', is inputed into the input box.
Here is my html
<p>Arrival Date</p> <input type="text" id="datepicker" id="food" name="arrival_date" >
I'm using a query data picker to select the date.
You can insert code in attribute onchange
onchange="if(this.value == 'someValue') alert('...');"
Or create new function
function change(element){
if(element.value == 'someValue'){
alert('...');
}
}
And add attribute
onchange="change(this);"
Or add event
var el = document.getElementById('input-id');
el.onchange = function(){
change(el); // if 'el' doesn't work, use 'this' instead
}
I'm not sure if it works, but it should :)
Use .val() to get the value of the input and compare it with a string
var str = $('#datapicker').val(), // jQuery
// str = document.getDocumentByI('datapicker').value ( vanilla js)
strToCompare = '01/07/2013';
if( str === strToCompare) {
// do something
}
And encase this in either change or any keyup event to invoke it..
$('#datepicker').change(function() {
// code goes here
});
Update
Try the code below.
$(function () {
var $datepicker = $('#datepicker');
$datepicker.datepicker();
$datepicker.on('change', function () {
var str = $datepicker.val(),
strToCompare = '07/19/2013';
if (str === strToCompare) {
console.log('Strings match')
}
else {
console.log('boom !!')
}
});
});
Check Fiddle
Your input has 2 ids. You need to remove id="food". Then the following should work with IE >= 9:
document.getElementById('datepicker').addEventListener(
'input',
function(event) {
if (event.target.value.match(/^\d+\/\d+\/\d+$/))
console.log("Hello");
}, false);

Call a recursive function with different variables

I am new to javascript. I am doing a feedback form where there are 12 radio buttons that need to get validated individually and a textarea will be displayed when I click a particular value.
Here, when I click that button, my textarea, which is in display, should be mandatory entered (eg: when I click fail option in a results question, then I should mention in which subject he failed through that textarea. something like that).
For this, I have written code, it's working fine with the 1st radio button, but unable to call this recursively for remaining buttons.
I need to call this code in a function recursively, but my variables need to get change everytime. Like for 2nd time, I should use option2,text2, likewise in next call option3,text3, etc.
var option = $("#form1 input[#name=radio1]:checked").val();
var text = document.getElementById("text1").value;
if (!$("#form1 input[#name=radio1]:checked").val()) {
alert("Please fill all the fields");
return false;
errs++;
} else if (option == "3" && trim(text) == "") {
alert("Please enter comments.");
return false;
}
This piece of code needs to be called for var option1 to option10 and same text1 to text10. Like:
var option2 = $("#form1 input[#name=radio2]:checked").val();
var text2 = document.getElementById("text2").value;
This should get called immediately of completion of first radio button.
Please help me out.
"Recursive" is the wrong word here. You just want to loop over all the elements.
Get all the radios, and loop over them. Then get the ID, and all the fields associated with that id.
I'm assuming you're using jQuery, so here's an example:
// Note: The "#" is not needed in jQuery
var radios = $("#form1 input[name^='radio']"); // "^=" means "starts with"
radios.each(function(){
var id = this.name.replace('radio', ''); // this will get the number, eg: 1
var option = $(this).val(); // get radio's value
var text = $('#text'+id).val(); // get textX's value
if(!$(this).is(':checked')){ // check if radio is checked
alert("Please fill all the fields");
errs++; // make sure to do this before "return false"
return false; // break the .each loop
}
else if (option == "3" && trim(text) == "") {
alert("Please enter comments.");
return false;
}
});

Get the id of element focus is moving to in jQuery.blur event?

I've written some code using jQuery to do an ajax call and display a message on the page when the user moves focus away from a field. My field is called txtLogin and the user types in some text and clicks a button to create a new user account in a database using the given txtLogin value.
The issue is that a valid value must contain four letters, a dash, and then four more letters. My client insists that the form should have two fields, one for the first four letters, and another for the second four letters.
Suppose that these two fields are called txtLogin0 and txtLogin1. I still want to do an ajax call when the user moves focus away from the field, but the ajax call should not be invoked when the user moves from one of the two fields to the other!
My current code looks like this.
$('#txtLogin').blur(function() {
var login = $(this).val();
var isValid = testLogin(login);
if (!isValid) alert('Login is invalid');
});
I imagine my new code looking like this:
$('#txtLogin0').add('#txtLogin1').blur(function() {
var focusId = The Id of the newly focused element
if (focusId==='txtLogin0' || focusId==='txtLogin1) return
var login = $(#txtLogin0').val() + '-' + $('#txtLogin1').val();
var isValid = testLogin(login);
if (!isValid) alert('Login is invalid');
});
How can I get the id of the element that the focus moves to in the jQuery.blur event?
A simple hack is to create two var to store the current and previous element in onfocus and onblur and call the validate method inside a timer which will be triggered in 0 milli seconds.. Try below code and I think it is close to what you want.
DEMO
var prevEl, curEl;
$(document).ready(function() {
$('#txtLogin0, #txtLogin1').blur(function() {
prevEl = this.id;
setTimeout(validateLogin, 0);
}).focus(function() {
curEl = this.id;
});
});
function validateLogin() {
if ((prevEl === 'txtLogin0' && curEl === 'txtLogin1') || (curEl === 'txtLogin0' && prevEl === 'txtLogin1')) {
return;
}
prevEl = ''; curEl = '';
var login = $('#txtLogin0').val() + '-' + $('#txtLogin1').val();
var isValid = testLogin(login);
if (!isValid) alert('Login is invalid');
}
function testLogin(txt) {
return false;
}
var focusId = $(this).attr('id');

Categories