jQuery check if input is empty - javascript

I am trying to get it where, if there is value in the input, go ahead and do your thing but if there isn't, don't do anything. I keep getting getting it where, if there is nothing in the input, a failure message occurs but only if I hit the enter key
jsfiddle.net/BBaughn/8ovrmhgp click the space in the lower right corner, then press enter. It shouldn't pop up, because the input is not focused.
login/failure jQuery:
$(document).ready(function(){
$('.btn1').on('click', function(){
var login = [marion, 'FATHER1'];
var marion = $('#logging').val();
marion = marion.toUpperCase();
if (marion !== 'FATHER1' && $('#logging').val()) {
alert('Login Failed');
} else if (marion === 'FATHER1' && $('#logging').val()) {
$('.notify').css('margin-top', '0');
$('#logging').val('');
}
});
$('.exit').on('click', function(){
$('.notify').slideUp('slow');
});
});

if you just want to check if an input is empty, I'm guessing #logging is the input:
$('.btn1').on('click', function(){
var marion = $('#logging').val();
if (marion == '') {
//this means the input value was empty
}
});

if the length is equal zero, that means the field is empty. It works after adding length === 0 check, please try this,
if (e.which == 13 && $('.btn1').val().length === 0) {
e.preventDefault();
} else if (e.which == 13 && $('.btn1').focus()) {
$('.btn1').click();
}

Ok, I think I get what you mean now. You're checking the entire document for keypresses as is, you need to check the input only. I think this is a good solution to do that:
$('.login input').keypress(function (e) {
if (e.which == 13 && !$('#logging').val()) {
e.PreventDefault();
} else if (e.which == 13 && $('.btn1').focus()) {
$('.btn1').click();
}
});
Working Fiddle here

$(document).ready(function(){
$('.btn1').on('click', function(){
var login = [marion, 'FATHER1'];
var marion = $('#logging').val();
marion = marion.toUpperCase();
if (marion !== 'FATHER1' && $('#logging').val()) {
alert('Login Failed');
} else if (marion === 'FATHER1' && $('#logging').val()) {
$('.notify').css('margin-top', '0');
$('#logging').val('');
}
});
$('.exit').on('click', function(){
$('.notify').slideUp('slow');
});
});
I didn't realize that my if statement was if the input wasn't detecting the right login, so it didn't matter if it was out of focus. Now it says "if it's not FATHER1 and there is value in the input only, then send this alert"

Related

validate input type="number"

I try to do some programming:
I have this order form with different input fields (name, amountOfProductA, amountOfProductB, amountOfProduct...) and I submit this form, after some validation, with a jquery script.
I plan to reuse the code and the number of product fields may vary form time to time.
In the validation I make sure that at least one of the (type="number") product input fields is filled in.
If a user types a number in one of the product inputfields and by mistake a character (or a number and a character) in the other the form submits with this later field empty.
Because the wrong filled in field submits empty I cannot validate this.
Can you please give me a clue how validate this?
Should I just juse type="text" input fields? (How do I check if at least one product field is filled in then?)
This is my code:
jQuery(function ($) {
$('#bttn-submit').click(function () {
$('input').css('background', '#fff'); // reset BGcolor
var formOk = true;
var allProdFields = $('input[type=number]') // Selection of all Product('number') fields
var numberOfProdFields = allProdFields.length; // How many ('number') fields are there?
// How many product fields are empty?
var prodFieldsEmpty = 0;
for (i = 0; i < numberOfProdFields; i++) {
if( $(allProdFields[i]).val() == '' || $(allProdFields[i]).val() == 0){
prodFieldsEmpty++;
}
}
// Is there at least one product field filled?
if(prodFieldsEmpty == numberOfProdFields){
var formOk = false;
alert('Form not OK');
allProdFields.css('background', '#f30302');
}
// Is the name field filled?
if( $('#pesoonNaam').val() == '') {
$('#pesoonNaam').css('background', '#f30302');
var formOk = false;
}
if( formOk == true ) {
document.actieForm.submit();
}
})
})
The code below will not let the user enter character in your field only number. Because the type="number" is html5 and doesn't work in all the browsers.
$(document).on('keydown', '.numeric-input', function(event) {
var dot_split = $(this).val().split('.');
if ($.inArray(event.keyCode,[46,8,9,27,13]) !== -1 || (event.keyCode == 65 && event.ctrlKey === true) || (event.keyCode >= 35 && event.keyCode <= 39) && dot_split.length <= 2) {
// let it happen, don't do anything
return;
}else{
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
event.preventDefault();
}
}
})
Then you can check with an .each if any of the fields is empty.
prodFieldsEmpty = 0;
$('.numeric-input').each(function(){
if($(this).val() != ""){
prodFieldsEmpty++;
}
})
I hope this helps you!
You can try smth like:
function checkInputs(){
result = false;
$('input[type="number"]').each(function(){
if($(this).val() != '' && isNumeric($(this).val())) result = true;
})
return result;
}
UPD: Fiddle
You should not attach validation to the submit button as the user can submit the form without pressing it, attach validation to the form's submit handler:
jQuery(function ($) {
$('#formID').submit(
...
jQuery has an each method for iterating, so:
$('input[type=number]').each( function(index) {
/* do validation */
});
Within each, the function's this is set to the current element, so you can do:
if (this.value == 0) {
prodFieldsEmpty++;
}
The value of a form control is always a string, so the test this.value == 0 will return true if the value is '0' or '' (empty string). If you don't like using type coercion, then do:
if (this.value === '0' || this.value === '') {
If you want to check that the value is an integer, then there are any number of answers here about that, the simplest is probably the accepted answer here:
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Note that this will allow all types of numbers, e.g. 2.34e3. If you just want to allow say positive integers, you can try:
function isPositiveInt(n) {
return /^\d+$/.test(n); // or return !/\D/.test(n)
}
Again, there are many ways to approach that.
Rather than count the number of fields and then the number that pass, if you only want to check that at least one passed, set a flag:
var passNumeric = false;
$('input[type=number]').each( function(index) {
if (isNumber(this.value)) {
passNumeric = true;
} else {
// do something with fails?
}
});
You can use the else branch to do something with the fails (or nothing).

Not allow initial spaces on input

I need to deny initial spaces on my input (which is not in a form), I have code like this:
<input id="customer-name" class="required no-spaces" minlength="3" />
And this is my javascript function:
$(".no-spaces").on('keypress', function(e) {
if (e.which == 32) {
return false;
}
});
But this doesn't allow spaces in any part of the input. How to do it just before any text?
Edit: The real is that I'm doing an autocomplete with the input and, If i allow initial spaces it will return all data.
Verify if the string is empty beforehand.
$(".no-spaces").on('keypress', function(e) {
if ($(this).val() == "" && e.which == 32) {
return false;
}
});
Also, check this in order to prevent the case where the user selects the entire text and then presses space and this to check if the cursor is indeed at the beggining of the input (Thanks to Barmar for mentioning this specific case)
Just simply check there is another character on textbox.
$(".no-spaces").on('keypress', function(e) {
if (e.which == 32 && ($this).val() == '') {
return false;
}
});
Edit
I hope it might be work.
$(".no-spaces").on('keypress', function(e) {
$(this).val(function(i, v) {
if (v[0] == ' ') {
return v.slice(1, v.length);
};
return v;
});
});
$(".no-spaces").on('keypress', function(e) {
if (e.which == 32) {
$(this).val($(this).val().replace(/^\W*/, ''));
}
});
This works for me.
$(".no-spaces").on('keypress', function(e) {
var val = $(this).val();
val_ltrim = ltrim(val);
$(this).val(val_ltrim);
});
Greetings.

Adding keyboard shortcuts (up, down, enter) to search input suggestions div

I have a search suggestion div that appears when you keyUp an input. This works fine, but now I am trying to make keyboard shortcuts in action.
I want a behavior like when you click down keyboard arrow button a span gets selected and if it is selected then another span that is after gets selected, similarly, if you click up arrow an upward span gets selected, when you click enter then link opens.
I am stuck because I could not remove a:hover and could not add classes to it. Even after I have basically no idea how to do it. But I really tried hard and a lot..
Here is a jsfiddle link (type anything in field). maybe somebody will help me.
This code should go when the request is made and data is being returned:
<script type="text/javascript">
$(document).ready(function(){
total = 3;
$(".result-item").mouseenter(
function(){
hovered = $(this).attr("id");
total = 3;
$(".result-item").each(function(){
$(this).children("a").css({
'background-color':'#e4e4e4',
'color':'#000000'
});
$(this).find(".searchheading").css({
'color':'#191919'
});
$(this).find(".searchcaption").css({
'color':'#555555'
});
});
$(this).children("a").css({
'background-color':'#b7b7b7',
'color':'#ffffff'
});
$(this).find(".searchheading").css({
'color':'#ffffff'
});
$(this).find(".searchcaption").css({
'color':'#f1f1f1'
});
}
);
});
</script>
And this code on a page where request is made:
$("#suggestions").hide();
$("#search").bind('keyup', function(event){
if (event.which == 40 || event.which == 38 || event.which == 13) return false;
else
{
hovered = undefined;
lookup($(this).val());
}
});
$("#search").bind('keydown', 'down', function(evt){
if ($("#suggestions").is(":visible"))
{
if (typeof hovered == 'undefined')
{
$("#result-item-0").trigger("mouseenter");
return;
}
count = parseInt($("#"+hovered).attr("count"));
next = (count + 1);
if (next == total)
next = 0;
$("#result-item-"+next).trigger("mouseenter");
}
});
$("#search").bind('keydown', 'up', function(evt){
if ($("#suggestions").is(":visible"))
{
if (typeof hovered == 'undefined')
{
$("#result-item-"+(total-1)).trigger("mouseenter");
return;
}
count = parseInt($("#"+hovered).attr("count"));
prev = (count - 1);
if (prev == -1)
prev = (total-1);
$("#result-item-"+prev).trigger("mouseenter");
}
});
$("#search").bind('keydown', 'return', function(evt){
if ($("#suggestions").is(":visible"))
{
if (typeof hovered == 'undefined')
{
str = $("#search").val();
window.location.href = urlencode(str); // urlencode is a custom function
return false;
}
count = parseInt($("#"+hovered).attr("count"));
current = count;
$("#result-item-"+current).trigger("mouseenter");
$("#suggestions").fadeOut();
window.location.href = $("#"+hovered).children("a").attr("href");
}
});
})
;
Also I removed onkeyup="" attribute on element, this approach is nicer.

Checking if any input or textarea element in the page is not empty

I'm adding a mechanism in my website that's supposed to warn users whenever they are about to close a page they were working in. I'm binding a function dropDraftConfirmation to the window.onbeforeunload event, like this:
window.onbeforeunload = dropDraftConfirmation;
function dropDraftConfirmation()
{
if (<there is an input or textarea element not empty on the page>) {
alert('Your changes will be lost. Are you sure you want to exit the page?');
}
}
But this is called every time I close a page. So my question is, how to detect if there is an input or textarea element in the page that is not empty? I'm using jQuery by the way.
I think this should do the trick.
window.onbeforeunload = dropDraftConfirmation;
function dropDraftConfirmation()
{
if ($("input:empty,textarea:empty").length == 0) {
alert('Your changes will be lost. Are you sure you want to exit the page?');
}
}
rewrite your function like the one below to check any unsaved changes before unload
window.onbeforeunload = checkUnSaved;
function checkUnSaved(){
if($("#textarea").val() === ""){
dropDraftConfirmation();
}else
return;
}
function dropDraftConfirmation()
{
if (<there is an input or textarea element not empty on the page>) {
alert('Your changes will be lost. Are you sure you want to exit the page?');
}
}
you could also do something like:
var errors = 0;
$("input, textarea").map(function(){
var val = $.trim( $(this).val() );
if( val.length < 1 ) {
errors++;
}
});
if( errors > 0 ) {
alert('Your changes will be lost. Are you sure you want to exit the page?');
}
Your condition will look like this:
if ($("input[value!='']").length > 0 || $('textarea:not(:empty)').length > 0 ){

verify before confirmation message

I'm trying to check if the '#text' (id for a textarea) is empty when I change '#my_selection' (id for a drop-down select) option. And if NOT EMPTY (ie, there's some text in the textarea), I would like the confirmation to pop up, else don't want to change the
'#my_selection'.
Many thanks in advance.
var selected=$('#my_selection').val();
$('#my_selection').change(function(){
if($("#text").val() != ""){
var check=confirm("change?");
if(check){
selected=$(this).val();
$('#my_selection').val(selected);
}else{
$(this).val(selected);
}
}
});
As far as I can tell you code is ok. Perhaps you are just missing an else on the outter if:
var oldVal = $('#select').val();
$('#select').change(function(){
if ($('#text').val() != ''){
if(confirm('change ?')){
oldVal=this.value;
} else {
this.value = oldVal;
}
} else {
this.value = oldVal;
}
});
You can test a running example here.

Categories