Check if input value is empty and display an alert - javascript

How is it possible to display an alert with jQuery if I click the submit button and the value of the input field is empty?
<input type="text" id="myMessage" name="shoutbox_msg" size="16" class="field_nosize" maxlength="150">
<input id="submit" type="submit" name="submit_post" class="button_nosize" value="Senden" onclick="sendMessage(); clearInput();">

$('#submit').click(function(){
if($('#myMessage').val() == ''){
alert('Input can not be left blank');
}
});
Update
If you don't want whitespace also u can remove them using jQuery.trim()
Description: Remove the whitespace from the beginning and end of a string.
$('#submit').click(function(){
if($.trim($('#myMessage').val()) == ''){
alert('Input can not be left blank');
}
});

Better one is here.
$('#submit').click(function()
{
if( !$('#myMessage').val() ) {
alert('warning');
}
});
And you don't necessarily need .length or see if its >0 since an empty string evaluates to false anyway but if you'd like to for readability purposes:
$('#submit').on('click',function()
{
if( $('#myMessage').val().length === 0 ) {
alert('warning');
}
});
If you're sure it will always operate on a textfield element then you can just use this.value.
$('#submit').click(function()
{
if( !document.getElementById('myMessage').value ) {
alert('warning');
}
});
Also you should take note that $('input:text') grabs multiple elements, specify a context or use the this keyword if you just want a reference to a lone element ( provided theres one textfield in the context's descendants/children ).

Also you can try this, if you want to focus on same text after error.
If you wants to show this error message in a paragraph then you can use this one:
$(document).ready(function () {
$("#submit").click(function () {
if($('#selBooks').val() === '') {
$("#Paragraph_id").text("Please select a book and then proceed.").show();
$('#selBooks').focus();
return false;
}
});
});

Check empty input with removing space(if user enter space) from input using trim
$(document).ready(function(){
$('#button').click(function(){
if($.trim($('#fname').val()) == '')
{
$('#fname').css("border-color", "red");
alert("Empty");
}
});
});

You could create a function that checks every input in an input class like below
function validateForm() {
var anyFieldIsEmpty = jQuery(".myclass").filter(function () {
return $.trim(this.value).length === 0;
}).length > 0
if (anyFieldIsEmpty) {
alert("Fill all the necessary fields");
var empty = $(".myclass").filter(function () {
return $.trim(this.value).length === 0;
})
empty.css("border", "1px solid red");
return false;
} else {
return true;
}
}
What this does is it checks every input in 'myclass' and if empty it gives alert and colour the border of the input and user will recognize which input is not filled.

Use this instead because just trying to check if the value is not equal to an empty string won't help if there are multiple spaces.
('#submit').onclick = function(){
let count = 0;
let notEmpty = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
for(let i=0; i < $('#myMessage').value.length; i ++){
for(let j = 0; j < notEmpty.length ; j++){
if($('#myMessage').value[i]== notEmpty[j]){
count += 1;
}
}
}
if(count==0){
alert("You cannot leave this blank");
}
}

Related

How to edit the correct phone number in my script?

I have this sample:
link
CODE HTML:
<label for="primary_phone">Primary Phone Number<span class="star">*</span></label>
<br>
<input type="text" name="primary_phone" id="primary_phone" class="_phone required-input" value="" maxlength="10">
CODE CSS:
.invalid{
border:1px solid red !important;
}
.valid{
border:1px solid green !important;
}
CODE JS:
function phoneFormat(){
$( "._phone" ).on('blur change', function() {
text = $(this).val().replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
var testt=$(this).val().match(text);
if($(this).val()=='' || $(this).val().match(text) || $(this).val().length == 0)
{
$(this).removeClass('valid').addClass('invalid');
}
else{
$(this).removeClass('invalid').addClass('valid');
}
$(this).val(text);
});
}
$( "#primary_phone" ).blur(function() {
phoneFormat();
});
I put a script that arranges text format
for example, we can add this number :
1234567890
After calling script appears next form (what is right)
(123) 456-7890
The problem is when you want to edit my phone number ... if you want to delete the last two numbers because I put the following code maxlength="10"
I want the user can not write more than 10 characters.
How do I fulfill both requirements.
If something is not explained well I'll do an edit to this post
Thanks in advance!
Just remove all special characters when you focus in on the input box:
$("#primary_phone").on("click", function() {
var thisVal = $(this).val();
var value = thisVal.replace(/[^\/\d]/g,'');
$(this).val(value);
});
Now when you click out of the input box, your original function to format the number comes in to play :)
Working fiddle : https://jsfiddle.net/reko91/gto0qeyx/2/
I would set a higher maxlength (say 15) and bind the input to keypress.
Inside the event you can check the keyCode against a set of allowed ones and suppress the event (entry of the character) otherwise.
I would also suppress the entry of numbers if we already have 10 (with one exception: if the user selected (marked) a portion of the input and that selection contains numbers.
var alwaysAllowed = [32, 40, 41, 45]; // [" ","(",")","-"]
function keyCode(keyCode) {
if (alwaysAllowed.indexOf(keyCode) !== -1) {
return "allowed";
} else if (keyCode >= 48 && keyCode <= 57) {
// 0 - 9
return "number";
} else {
// any other character
return false;
}
}
function countNumbers(text) {
// return the number of characters [0-9] in the string "text"
var counter = 0;
for (var i = 0; i < text.length; i++) {
if (parseInt(text[i]) >= 0 && parseInt(text[i]) < 10) {
counter++;
}
}
return counter;
}
$primaryPhone.on("keypress", function () {
var keyCodeEvaluation = keyCode(event.keyCode);
if (keyCodeEvaluation === false) {
event.preventDefault();
} else if (keyCodeEvaluation === "number") {
var value = this.value,
counter = countNumbers(value.substring(this.selectionStart, this.selectionEnd));
//
if (counter === 0 && countNumbers(value) > 9) {
event.preventDefault();
}
}
});
This would allow the user to edit (or write) the phonenumber with your format applied.
MORE IMPORTANTLY
You should rewrite your phoneFormat() function.
Each execution adds another event listener. The first time you change the input value it executes one time. Then two times, three times and so forth.
You should also store objects you use repeatedly in a variable, e.g. $( this ) (creating the same jQuery object each time is a performance killer).
Here is a working example that should cover most of your use cases.

Check whether the required field is not empty

I want to check whether the required field is empty or not.
I used the code below.
$(":input").each(function() {
if($(this).data('label')=='required')
{
if($(this).val() === "")
alert("Empty Fields!!");
}
});
But it was alert more than one time.
JSFiddle:
http://jsfiddle.net/hbk2a5qo/3/
Why not directly use required attribute in HTML:
<input id="name"type="text" data-label="required" required/>
You need to use a flag
$(document).ready(function () {
$("#submit").click(function (e) {
e.preventDefault()
AlertSave();
});
});
function AlertSave() {
//use the flag to set the valid status in the loop
var valid = true;
//iterate over only the required elements
$(':input[data-label="required"]').each(function () {
if ($(this).val() === "") {
valid = false;
return false;
}
});
if (valid) {
//do your save
} else {
alert("Empty Fields!!");
}
}
Demo: Fiddle
As you have used $(":input").each() so it will go through all fields. But you can use flag to show alert only once.
function AlertSave() {
var alertShown=false;
$(":input").each(function() {
if($(this).data('label')=='required')
{
if($(this).val() === "" && !alertShown)
{
alertShown=true;
alert("Empty Fields!!");
}
}
});
}
You Updated Fiddle
By using required attribute (which is recommended), this will return all the required input fields that has no value:
var inputsWithMissingValues = $('input[required]').filter(function(i, input) {
return !input.value.length;
});
So, if the length of that is more than zero, then you have required fields with missing value.

Jquery validation code for not allowed only blank space in textbox

i m looking for code in which for not allowed only blank space... for e.g i have one textbox and i have tried this
$(document).ready(function()
{
$("#mybutton").live('click',function()
{
var txt_family_name=$("#mytextbox").val();
if(txt_family_name =="" || txt_family_name ==null)
{
alert("null");
}
else
{
alert("not null");
}
});
});
this above code i have tried and its not working. so pls help me on that.. on one of my button i m calling this above code
Example : space....with any text -- output should be not null
: space space.... any space without any other text -- output should be null
you can use the length attribute and the trim method to remove the trailing spaces, if any:
$("#mybutton").on('click',function()
{
var length = $.trim($("#mytextbox").val()).length;
if(length == 0)
{
alert("null");
}
else
{
alert("not null");
}
});
See the updated code it's working
$(document).ready(function()
{
$("#clickme").on('click',function()
{
var txt_family_name=$.trim($("#mytextbox").val());
if(txt_family_name ==="" || txt_family_name ===null)
{
alert("null");
}
else
{
alert("not null");
}
});
});
Jquery Validation : require method only check the length of the input. So it allow the blank space.The solution will be the simple change the one line code in it.
required: function( value, element, param ) {
// Check if dependency is met
if ( !this.depend( param, element ) ) {
return "dependency-mismatch";
}
if ( element.nodeName.toLowerCase() === "select" ) {
// Could be an array for select-multiple or a string, both are fine this way
var val = $( element ).val();
return val && val.length > 0;
}
if ( this.checkable( element ) ) {
return this.getLength( value, element ) > 0;
}
return value.length > 0;
}
in above code change value.length to $.trim(value).length
so simply remove the blank space
you can use regexp.
$(document).ready(function() {
$("#mybutton").bind('click', function() {
var txt_family_name = $("#mytextbox").val();
if (txt_family_name.replace(/\s/g, '') == "") {
alert("null");
} else {
alert("not null");
}
});
});
//To add method to remove blankspaces
$.validator.addMethod("blankSpace", function(value) {
return value.indexOf(" ") < 0 && value != "";
});

Dynamic if/else statement with jQuery and textarea

So I'm trying to style a <textarea> tag to highlight when it has more than one character typed in. (For a contact form). When someone is filling out the form, the fields will all highlight green to let them know its valid. I'm very new to JS and jQuery in general but I'm pretty sure this is supossed to work. I can use the $('#message').addClass('valid') by itself and it will apply the class, but when I add the if/else statement, nothing works. Here is the script
\\ Begin Highlight Code
var $messageval = $('#message').val()
if ($messageval.length != 0 ){
$('#message').addClass('valid');
}
else ($messageval.length = 0 ){
$('#message').removeClass('valid');
}
});
I've been googling for hours and I can't find anything to dynamically add and remove classes based on a text length variable.
Thanks
You are missing else if
if ($messageval.length != 0 ){
$(this).addClass('valid');
}
else if($messageval.length == 0 ){ //<-- Here
$('#message').removeClass('valid');
}
Basically you can just have
if ($messageval.length != 0 ){
$('#message').addClass('valid');
}
else { //<-- Here
$('#message').removeClass('valid');
}
I guess this is what you are looking for:-
$(function(){
$('#message').on('keyup', function () {
var $messageval = $.trim($(this).val()); //$.trim here to avoid whitespace preventing validation.
if ($messageval.length != 0) {
$(this).addClass('valid'); //this here represent the textarea dom element, and $(this) is the jquery wrapper.
} else {
$(this).removeClass('valid');
}
});
});
Fiddle
$(document).ready(function(){
$("#message").keyup(function(){
var messageval = $('#message').val();
if (messageval.length > 1) {
$('#message').addClass('valid');
} else {
$('#message').removeClass('valid');
}
});
});
change your code to this
$(document).ready(function(){
$('#message').trigger('change');//if you initially want to check the textarea
$('#message').on('change', function(){
var $messageval = $(this).val();
if ($messageval.length != 0 ){
if (!$(this).hasClass("valid")) {
$(this).addClass("valid");
}
}
else ($messageval.length == 0 ){
if ($(this).hasClass("valid")) {
$(this).removeClass("valid");
}
}
});
});
Cheers!

check if all text inputs are empty

I want to check if all text inputs with class 'textinput' are empty, but it only seems to check if the first input is empty or not, I can't figure out why. can anyone see what I'm doing wrong?
$('#check').click(function(){
var allEmpty;
$('.textinput').each(function(){
if(!$('.textinput').val()){
allEmpty = true;
}
});
if (allEmpty == true){
alert('all empty');
}
});
Find all .textinput that are not empty, and check the selector length. If none exist, they are all empty :
$('#check').on('click', function(){
var allEmpty = ! $('.textinput').filter(function() {
return $.trim( this.value ) != "";
}).length;
if (allEmpty) alert('all empty');
});
or
if ( ! $('.textinput[value !=""]').length ) alert('all empty');
Try checking against the opposite logic. If any of the values are set, then they're not all empty.
Also, you want to make use of $(this) when you're within the context of the .each() function. Otherwise, calling $('.textinput') will re-select those elements again rather than working on the current one.
Adding $.trim() ensures that whitespace is not counted as an actual value, but you can remove this if you want to count whitespace as a value.
$('#check').click(function() {
var allEmpty = true;
$('.textinput').each(function(){
if ($.trim($(this).val())) {
allEmpty = false;
}
});
if (allEmpty == true){
alert('all empty');
}
});
Your condition is wrong; you are setting allEmpty = true for each single item.
You have to invert your logic:
$('#check').click(function(){
var almostOneNotEmpty = false;
$('.textinput').each(function(){
if($(this).val()){
almostOneNotEmpty = true;
}
});
if (!almostOneNotEmpty == true){
alert('all empty');
}
});
this should be your condition >>
if(!$('.textinput').val()){
}else {
allEmpty = true;
}
This simple check will tell you if they are all empty:
var isEmpty = !$('.textinput').map(function() { return this.value; }).get().join('');
This will give you boolean true if all the fields are blank.
You need to use the element that is selected by the each method by using "this".
$('#check').click(function () {
var allEmpty;
$('.textinput').each(function () {
if (!$(this).val()) {
allEmpty = true;
}
});
if (allEmpty == true) {
alert('all empty');
}
});

Categories

Resources