Make a div show a specific message if input is empty - javascript

I'm trying to have a div have the exact same content as an input. If I type "lalala" in the input, I want it to show in the div. That part is working fine. But I would also like to show in the div something along the lines of "the input is empty" when the input, is empty.
So basically like
input = blablabla
div = blablabla
input =
div = The input is empty
I'm trying to make it "if empty, do this, if not, show the same content as the input". But for some reason, the empty bit is not working.
const textInput = $('#input');
const textOutput = $('#output');
if ( textInput.value == "" ) {
textOutput.innerHTML += 'It's empty';
} else {
textInput.on("input", function() {
textOutput.text($(this).val());
});
}
});```

You have an unescaped quotation here 'It's empty'.
There's no reason to use innerHTML
You should use === to compare equality.
const input = document.querySelector('#input');
const output = document.querySelector('#output');
input.addEventListener('input', () =>
output.textContent = input.value ? input.value : "It's empty.");
<input id="input">
<div id="output"></div>

Apart from the apostrophe ' in your string you are mixing Vanilla Javascript with JQuery and your trigger is inside the if() block which is supposed to be called on the trigger.
Change the code like this:
const textInput = $('#input');
const textOutput = $('#output');
textInput.on("input", function() {
if ( $(this).val() === "" ) {
textOutput.html('It\'s empty');
} else {
textOutput.html($(this).val());
}
});

Step by step instruction on what needs changing
As you are using jQuery:
textInput.value == "" should be ! textInput.val()
textOutput.innerHTML = 'it's empty' should be textOutput.text("it's empty");
textOutput.text($(this).val()); should be textOutput.text(textInput.val());
and it should all be within the on "input" listener i.e.
textInput.on('change',function(){ /*code goes here*/ });

fix if
if ( textInput.value == "" ) {
textOutput.innerHTML += 'It\'s empty';
} else {
textInput.on("input", function() {
textOutput.text($(this).val());
});
}
Better if:
if (!textInput.value) {
textOutput.innerHTML = 'It\'s empty';
} else {
textInput.on("input", () => textOutput.text($(this).val()));
}
Short:
!textInput.value ? textOutput.innerHTML = 'It\'s empty' : textInput.on("input", () => textOutput.text($(this).val()));

There ya go
const $textInput = $('#input');
const $textOutput = $('#output');
$textInput.on('input', function(){
if($textInput.val() != '') {
$textOutput.text($textInput.val());
}
else {
$textOutput.text('It\'s empty');
}
});

Related

Javascript show validation message right after the text box

I am trying to validate a form using javascript. On button click function I have called a javascript function where I have displayed the message after the text box. The number of times I click the button same number of times message gets displayed just below the existing validation message. Please help me
Here goes my code:
function check() {
var v = true;
if ((document.getElementById('firstname').value == "")) {
$('#firstname').after('Validation message');
document.getElementById('firstname').style.borderColor='#DA394B';
v = false;
}
if ((document.getElementById('lastname').value == "")) {
$('#lastname').after('Some validation text');
document.getElementById('lastname').style.borderColor = '#DA394B';
v = false;
}
return v;
}
Assuming I understand what v is for. Which i probably don't because v (I hate one letter variable names...).
Try this:
function check() {
var v = true;
if ((document.getElementById('firstname').value == "")) {
if ($('#firstnameMessage').length <= 0)
{
$('#firstname').after('<p id="firstnameMessage">Validation message</p>');
document.getElementById('firstname').style.borderColor='#DA394B';
}
v = false;
}
if ((document.getElementById('lastname').value == "")) {
if ($('#lastnameMessage').length <= 0)
{
$('#lastname').after('<p id="lastnameMessage">Some validation text</p>');
document.getElementById('lastname').style.borderColor = '#DA394B';
}
v = false;
}
return v;
}
Simple fiddle to show this working: https://jsfiddle.net/srLt7wo0/
Using .after will insert another element per http://api.jquery.com/after/
The below solution uses a separate element already in the HTML to display the error message. If you use .after you have to check that you have not already added an element to your HTML
HTML
<input id="firstname" type="text"/><div id="firstnameMessage"></div>
<input id="lastname" type="text"/><div id="lastnameMessage"></div>
JS
function check() {
$("#firstnameMessage,#lastnameMessage").text(''); // clear message, reset border color
document.getElementById('firstname').style.borderColor='';
document.getElementById('lastname').style.borderColor='';
var isValid = true;
if ((document.getElementById('firstname').value == "")) {
$('#firstnameMessage').text('First name is required');
document.getElementById('firstname').style.borderColor='#DA394B';
isValid = false;
}
if ((document.getElementById('lastname').value == "")) {
$('#lastnameMessage').text('Last name is required');
document.getElementById('lastname').style.borderColor='#DA394B';
isValid = false;
}
return isValid;
}
I'm not sure to have understood you issue but maybe this could help you :)
window.firstname = document.getElementById('firstname')
window.lastname = document.getElementById('lastname')
window.issue = document.getElementById('issue')
function check() {
if(firstname.value == '' || lastname.value == '') {
issue.innerHTML = 'Please, use correct credentials.'
} else {
issue.innerHTML = ''
}
}
<input id="firstname" />
<input id="lastname" />
<button onclick="check()">
Check
</button>
<div id="issue" style="color:red;"></div>
This should work if i understand you.
It will add only one message no matter how many times you click
function check() {
var v = true;
if ((document.getElementById('firstname').value == "")) {
$('#message').remove()
$('#firstname').after('<span id='message'>Validation message</span>');
document.getElementById('firstname').style.borderColor='#DA394B';
v = false;
}
if ((document.getElementById('lastname').value == "")) {
$('#message').remove()
$('#lastname').after('<span id='message'>Some validation text</span>');
document.getElementById('lastname').style.borderColor = '#DA394B';
v = false;
}
return v;
}

How to allow only numbers between 0 to 30 or A,D character in input using javascript?

Hi i have created a javascript function to only allow numbers between 0 to 30 and character A and D. I give an alert if it does not match the criteria but if the user clicks ok on the alert the values still remain in the input and can be updated in the database. I want that user should not be able to enter anything at all in the input box except character A , D and numbers between 0 to 30 like it is done in the case of input type=number we can only enter numbers. My javascript function is:-
function validate() {
var regex = /[ad0-9]/gi;
var txt = document.getElementById('txt').value;
var valid = true;
var error = '';
if (regex.test(txt)) {
if (!isNaN(txt)) {
if (!(parseInt(txt) >= 0 && parseInt(txt) <= 30)) {
valid = false;
error = 'Please enter between 0 to 30.'
}
}
}
else {
valid = false;
error = 'Please enter between 0 to 30, A or D'
}
if (!valid) {
alert(error);
}
}
The javascript works fine with validation but after clicking ok in alert value still remains there and it also gives error when input box is empty any way to avoid that. Is there any other better way to create the function or can it done by using jquery. I am new to jquery if it is possible to do it with jquery it would be great. I would be highly gratefull if anybody can help.
You may try this code example.
function validate(box) {
var val = box.value;
if (!/^[AD]?$/.test(val) && isNaN(val) || (0 > val || 30 < val)) {
box.value = '';
alert('Only A or D or 0-30');
}
}
<input type='text' value='30' onblur='validate(this);' />
The best solution would be to check it at the moment when you are inserting it in the database.
if(txt.replace(/ /g, '').length == 0) {
// text is empty
return; // get out of function
}
If you want to make sure there is no error when the text is empty, you can do this. The .replace part is to ensure that if the text input is filled with only spaces, it is considered empty.
With the rest of the function:
function validate() {
var regex = /[ad0-9]/gi;
var txt = document.getElementById('txt').value;
var valid = true;
var error = '';
if(txt.replace(/ /g, '').length == 0) {
// text is empty
return; // get out of function
}
if (regex.test(txt)) {
if (!isNaN(txt)) {
if (!(parseInt(txt) >= 0 && parseInt(txt) <= 30)) {
valid = false;
error = 'Please enter between 0 to 30.'
}
}
}
else {
valid = false;
error = 'Please enter between 0 to 30, A or D'
}
if (!valid) {
alert(error);
}
}
How about replacing disallowed values so only the desired input is allowed. With this you won't be able to enter anything other than A, D and numbers 0 - 30:
$('input').on('input', function(e) {
this.value = this.value
.replace(/[^AD\d]/, '')
.replace(/(3)[1-9]/, '$1')
.replace(/(30)[0-9]/, '$1')
.replace(/([4-9])[0-9]/, '$1')
.replace(/([\d][\d])[\d]/, '$1');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" />
Note, it's still a good idea to do some server side validation.

Swap default field value using pure JavaScript

I've written some code in jQuery for removing/replacing the default value of an e-mail field on focus and blur events. Its' working fine,
But I wanted it in JavaScript .. I've tried several times but I couldn't succeed.
here's my jQuery Code
$(document).ready(function(){
var email = 'Enter E-Mail Address....';
$('input[type="email"]').attr('value',email).focus(function(){
if($(this).val()==email){
$(this).attr('value','');
}
}).blur(function(){
if($(this).val()==''){
$(this).attr('value',email);
}
});
});
can anyone tell me how to do it in JavaScript,
Assuming <input type='text' id="email_field"/>
var email = 'Enter E-Mail Address....';
var emailField = document.getElementById("email_field");
emailField.onfocus = function(){
removeDefaultText(this);
}
emailField.onblur = function(){
setDefaultText(this);
}
function removeDefaultText(element){
var defaultValue = 'Enter E-Mail Address....';
if(element.value == defaultValue){
element.value = "";
}
}
function setDefaultText(element){
var defaultValue = 'Enter E-Mail Address....';
if(element.value == ''){
element.value = defaultValue;
}
}
Apparently you're trying to display a placeholder value, when there is no other value.
In any modern browser, you might simply use this:
<input type="text" class="email" placeholder="Enter E-Mail Address..." />
Unfortunately that excludes older IEs, so an approach for vanilla JavaScript could be like this:
// grab all input[type="email"] elements
var emailFields = document.getElementsByTagName('INPUT').filter(function(input) {
return input.type === 'email';
});
var placeholder = 'Enter your E-Mail Address...';
// watch onfocus and onblur on each of them
emailFields.forEach(function(input) {
input.onfocus = function() {
// clear only if the value is our placeholder
if (input.value === placeholder) {
input.value = '';
}
}
input.onblur = function() {
// set the value back to the placeholder, if it's empty
if (input.value === '') {
input.value = placeholder;
}
}
});
Hope that suits your needs.
try
function validEmail(e) {
var filter = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
return String(e).search (filter) != -1;
}
with jQuery
var userinputmail= $(this).val();
var pattern = /^\b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i
if(!pattern.test(userinputmail))
{
alert('not a valid e-mail ');
}​
You can also try the following regex for other validation (I think this will helpful)
Matching a Username => /^[a-z0-9_-]{3,16}$/
Matching a Password => /^[a-z0-9_-]{6,18}$/
Matching a URL => /^[a-z0-9_-]{6,18}$/
You can use regular old javascript for that:
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
======
using new regex
demo http://bit.ly/Hzbq4i
added support for Address tags (+ sign)
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
if( !isValidEmailAddress( emailaddress ) ) { /* do stuff here */ }
NOTE: keep in mind that no 100% regex
email check exists!
check this link

How to write simplified and generic validation logics and rules in JQuery

I know there are tons of information out there over internet to validate form in JavaScript and JQuery. But I’m interested to write my own. Basically I want to learn this thing.
So here is my validation script I have written and its working fine.
function validate() {
var firstName = jQuery("#firstName").val();
var lastName = jQuery("#lastName").val();
var dateOfBirthy = jQuery().val("dateOfBirth");
if (firstName.length == 0) {
addRemoveValidationCSSclass("#firstName", false);
} else {
addRemoveValidationCSSclass("#firstName", true);
}
if (lastName.length == 0) {
addRemoveValidationCSSclass("#lastName", false);
} else {
addRemoveValidationCSSclass("#lastName", true);
}
}
function addRemoveValidationCSSclass(inputField, isValid) {
var div = jQuery(inputField).parents("div.control-group");
if (isValid == false) {
div.removeClass("success");
div.addClass("error");
} else if (isValid == true) {
div.removeClass("error");
div.addClass("success");
} else {
}
}
I want to achieve few things--
add validation message
More generic way to handle for every form.
And I want to add validation rule, like length, email validation,
date validation etc.
Now how can I achieve these?
Use jQuery validate. It does everything you want straight out of the box.
I did something similar to this, except that I wrote my rules in PHP since you need a server-side backup. When the PHP generates the form, it also generates some simple client-side validation that looks like this:
<!-- html field -->
<label for="first">
First Name: <input type="text" name="first" id="first">
<span id="first_message"></span>
</label>
Then the script is like this:
<script>
var formValid = true;
var fieldValid = true;
// Check first name
fieldValid = doRequiredCheck("first");
if (!fieldValid) {formValid = false};
fieldValid = doCheckLength("first", 25);
if (!fieldValid) {formValid = false};
function doRequiredCheck(id) {
var el = document.getElementById(id);
var box = document.getElementById(id + "_message";
if (el.value === "") {
box.innerHTML = "**REQUIRED**";
}
}
function doCheckLength(id,len) {
var el = document.getElementById(id);
var box = document.getElementById(id + "_message";
if (el.value.length > len) {
box.innerHTML = "Too long";
}
}
</script>
Create a simple function:
function validations(day, hour, tap1, tap2, employed){
if( day== "" | hour== "" | tap1== "" | tap2== "" | employed== "" ){
return false;
} else {
return true;
}

More efficient way of writing this javascript

I am creating a contact form for my website and and using javascript to the first layer of validation before submitting it which is then checked again via php but i am relatively new to javascript, here is my script...
$("#send").click(function() {
var fullname = $("input#fullname").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("textarea#message").val();
if (fullname == ""){
$("input#fullname").css("background","#d02624");
$("input#fullname").css("color","#121212");
}else{
$("input#fullname").css("background","#121212");
$("input#fullname").css("color","#5c5c5c");
}
if (email == ""){
$("input#email").css("background","#d02624");
$("input#email").css("color","#121212");
}else{
$("input#email").css("background","#121212");
$("input#email").css("color","#5c5c5c");
}
if (subject == ""){
$("input#subject").css("background","#d02624");
$("input#subject").css("color","#121212");
}else{
$("input#subject").css("background","#121212");
$("input#subject").css("color","#5c5c5c");
}
if (message == ""){
$("textarea#message").css("background","#d02624");
$("textarea#message").css("color","#121212");
}else{
$("textarea#message").css("background","#121212");
$("textarea#message").css("color","#5c5c5c");
}
if (name && email && subject && message != ""){
alert("YAY");
}
});
How can i write this more efficiently and make the alert show if all the fields are filled out, thanks.
$("#send").click(function() {
var failed = false;
$('input#fullname, input#email, input#subject, textarea#message').each(function() {
var item = $(this);
if (item.val()) {
item.css("background","#121212").css("color","#5c5c5c");
} else {
item.css("background","#d02624").css("color","#121212");
failed = true;
}
});
if (failed){
alert("YAY");
}
});
glavic and matt's answers were exactly what I was going to suggest, except I would take it a step further by separating the logic from the presentation.
Have classes defined in your css for when a field contains an invalid entry, and add or remove that class using $.addClass() or $.removeClass()
Since you're using jQuery, I would recommend setting a class on each field that requires a non-blank value (class="required").
Then you do something like this:
var foundEmpty = false;
$(".required").each(function()
{
if($(this).val())
{
foundEmpty=true;
$(this).style("background-color", "red");
}
});
if(foundEmpty)
{
alert("One or more fields require a value.");
}
Giving them a common class, define classes to apply the styles, and do this:
JS
$("#send").click(function() {
$('.validate').attr("class", function() {
return $(this).val() === "" ? "validate invalid" : "validate valid";
});
if( $('.invalid').length === 0 ) {
alert('YAY');
}
});
CSS
.valid {
background:#121212;
color:#5c5c5c
}
.invalid {
background:#d02624;
color:#121212;
}
HTML
<button id="send">SEND</button><br>
<input class="validate"><br>
<input class="validate"><br>
<input class="validate"><br>
<input class="validate">
JSFIDDLE DEMO
A little bit more efficient approach:
var validate = $('.validate');
$("#send").click(function() {
validate.attr("class", function() {
return $(this).val() === "" ? "validate invalid" : "validate valid";
});
if( validate.filter('.invalid').length === 0 ) {
alert('YAY');
}
});
You can use jQuery to iterate over each object and get their values. Depending on your form, this code will change, but it's to give you an example. I'm probably missing a couple of brackets here and there but the concept is there.
var objectName=$(this).attr('id');
$('#formId').children().each(
function(){
if ($(this).value == ""){
$(this).css("background","#d02624");
$(this).css("color","#121212");
$error[objectName]='true';
}else{
$(this).css("background","#121212");
$(this).css("color","#5c5c5c");
$error[objectName]='false';
}
}
);
$.each(error, function(key, value){
if (value=='false'){
alert (key + 'is empty');
}
});
I would probably divide part of this up into my css file. If any of the fields are empty add a class like "empty" to the object, if not, remove it. Then in your css file you can add some descriptors like:
input#fullname,
input#email {
...
}
input#fullname.empty,
input#email.empty {
...
}
You can use jQuery addClass() and removeClass().
You can then add a loop as follows:
var inputs = new Array();
inputs[0] = "input#fullname";
inputs[1] = "input#email";
inputs[2] = "input#subject";
inputs[3] = "textarea#message";
var complete = true;
for (var i = 0; i < 4; i++) {
var value = $(inputs[0]).val();
if (value.length > 0) {
$(inputs[i]).removeClass("empty");
} else {
complete = false;
$(inputs[i]).addClass("empty");
}
}
if (complete) {
}
EDIT:
There you go, fixed it for you.

Categories

Resources