jQuery: Compact way to fetch values of all input fields? - javascript

I have a form with five input fields and a register button ('.register').
I want to enable the register button ONLY IF all fields have at least one character.
Here comes my code:
$(document).ready(function() {
// when page loads
$('.register').addClass('a_unclickable');
// Input validation
// Are all fields filled out?
$('input').on('keyup', function() {
var un_value = $('#username_operators').val();
var fn_value = $('#first_name_operators').val();
var ln_value = $('#last_name_operators').val();
var e_value = $('#email_operators').val();
var pw_value = $('#password_operators').val();
var pw_r_value = $('#password_repeat_operators').val();
if ((un_value.length > 0) && (fn_value.length > 0) && (ln_value.length > 0) && (e_value.length > 0) && (e_value.indexOf('#') !== -1) && (pw_value.length > 0) && (pw_r_value.length > 0)) {
$('.register').removeClass('a_unclickable');
} else {
$('.register').addClass('a_unclickable');
}
})
});
I have the feeling that there is a much easier way to achieve the same result. Does anyone of you have a compact suggestion?

That's quiet compact:
$(document).ready(function() {
// when page loads
$('.register').addClass('a_unclickable');
// Input validation
// Are all fields filled out?
$('input').on('keyup', function() {
$('.register').removeClass('a_unclickable');
$('input').each(function() {
if ($(this).val() === '') {
$('.register').addClass('a_unclickable');
}
});
})
});

A couple of things come to mind. First:
$('input').on('keyup', function() {
var valid = true;
$('#username_operators, #first_name_operators, #last_name_operators, #email_operators, #password_operators, #password_repeat_operators').each(function() {
if (/^\s*$/.test(this.value)) {
valid = false;
}
});
if (valid) {
$('.register').removeClass('a_unclickable');
}
else {
$('.register').addClass('a_unclickable');
}
});
You can combine all the Ids into one CSS selector. Really the cleanest way is to add a class name to each required input, then utilize event.target.form to find all required fields inside the form.
$('input').on('keyup', function(event) {
var valid = true;
$(event.target.form).find(".required").each(function() {
if (/^\s*$/.test(this.value)) {
valid = false;
}
});
if (valid) {
$('.register').removeClass('a_unclickable');
}
else {
$('.register').addClass('a_unclickable');
}
});

Wrap the inputs in a <div class="verifyLength" ></div>
Add the a_unclickable class to the register field by default.
Then jquery:
$('input').on('keyup', function() {
var emptyField = false;
$(".verfyLength").find("input").each(function()
{
if((this).val().length() <=0)
emptyField = true;
});
if(emptyField)
$('.register').addClass('a_unclickable');
else
$('.register').removeClass('a_unclickable');
});

Here you go JSFiddle
var arr = [un_value, fn_value, ln_value, e_value, pw_value, pw_r_value];
$.each(arr,function(i,item){ if(item.length > 0){
$('.register').removeClass('a_unclickable');
} else {
$('.register').addClass('a_unclickable');
}})
if you are able to read all the values with selector you could pass them
like:
$.each($('input'),function(i,item){ if($(item).val().length > 0){
$('.register').removeClass('a_unclickable');
} else {
$('.register').addClass('a_unclickable');
}})

Have a look at this jsfiddle:
var i = 0, count = 0;
$.each($( ":input" ), function( index, value ) {
if(value.value.length > 0) {
count++;
}
});
if(count === 6) {
console.log(true);
} else {
console.log(false)
}

Related

How to query multiple conditions or results of anonymous functions in jQuery

First of all, I have a form with several input fields and some Bootstrap-Buttons. Now, what I want to do is to check, if two conditions ("Are all input fields filled?" ; "Is at least one Button pushed down?") are fullfilled to enable the user to click the submit button.
This is my code:
function checkInput() {
var inputFields = $("input[name=inp1],[name=inp2],[name=inp3]");
var buttons = $("button[name=btn1],[name=btn2],[name=btn3]");
var empty1;
var empty2;
buttons.click(function() {
if(!$(this).hasClass('active')) {
empty1 = false;
} else {
empty1 = true;
}
});
inputFields.keyup(function() {
inputFields.each(function() {
if($(this).val().length == 0) {
empty2 = true;
} else {
empty2 = false;
}
});
});
alert(empty1);
alert(empty2);
if(empty1 == true && empty2 == true) {
$('button[name=submitBtn]').prop('disabled', false);
} else {
$('button[name=submitBtn]').prop('disabled', true);
}
}
The alert(...) functions say, that empty1 and empty2 are "undifined", which i can understand. But my question is, how can I retrieve the true or false values from buttons.click() and inputFields.keyup() to query them afterwards?
The problem is the scope of the variables, those vars need to be global:
var empty1;
var empty2;
function checkInput() {
var inputFields = $("input[name=inp1],[name=inp2],[name=inp3]");
var buttons = $("button[name=btn1],[name=btn2],[name=btn3]");
buttons.click(function () {
if (!$(this).hasClass('active')) {
empty1 = false;
} else {
empty1 = true;
}
});
inputFields.keyup(function () {
inputFields.each(function () {
if ($(this).val().length == 0) {
empty2 = true;
} else {
empty2 = false;
}
});
});
alert(empty1);
alert(empty2);
if (empty1 == true && empty2 == true) {
$('button[name=submitBtn]').prop('disabled', false);
} else {
$('button[name=submitBtn]').prop('disabled', true);
}
}
Move it outside of the function an it will works:
see it in jsFiddle working example

if statement echo out different links for different codes

I am using this code
HTML:
<div id="message">some message</div>
<input type="text" id="myInput" />​
jQuery:
$(function() {
$("#message").hide();
$("#fail").hide();
var prefix = ['HX', 'HD', 'BD', 'LS']
$('#myInput').keyup(function(e) {
var value = $(this).val();
var firstTwo = value.substr(0,2);
var firstTwoUpper = firstTwo.toUpperCase();
if(firstTwo != firstTwoUpper) {
$(this).val( value.replace(/^\w\w/, firstTwoUpper) );
}
if(value.length > 1) {
if($.inArray(firstTwoUpper, prefix) >= 0) {
$("#fail").hide();
$("#message:hidden").fadeIn();
} else {
$("#message").hide();
$("#fail:hidden").fadeIn();
}
} else {
$("#message").hide();
$("#fail").hide();
}
});
});
​
To be a post code check. I got the above code from here: Jquery check array perform function and it works just fine but I want to display a message containing a link which all differ from one another. For example I want code 'HX' to link to facebook and I want 'BD' to link to the BBC. How would I write the if statement correctly? I have tried various ways but I am not achieving what I need.
Could someone give me a little guideance please?
Thanks,
Ben.
This fiddle does what you might be looking for
<div id="message">Some link</div>
<div id="fail">Invalid postcode</div>
<input type="text" id="myInput" />
$(function () {
$("#message").hide();
$("#fail").hide();
var prefix = ['HX', 'HD', 'BD', 'LS'];
var links = ['http://www.facebook.com','http://www.example.com','http://www.bbc.com','#'];
$('#myInput').keyup(function (e) {
var value = $(this).val();
var firstTwo = value.substr(0, 2);
var firstTwoUpper = firstTwo.toUpperCase();
if (firstTwo != firstTwoUpper) {
$(this).val(value.replace(/^\w\w/, firstTwoUpper));
}
if (value.length > 1) {
var index = $.inArray(firstTwoUpper, prefix);
if (index >= 0) {
$("#fail").hide();
$("#message").fadeIn();
$("#message a").attr("href",links[index]).html(links[index])
} else {
$("#message").hide();
$("#fail:hidden").fadeIn();
}
} else {
$("#message").hide();
$("#fail").hide();
}
});
});
this fiddle: http://jsfiddle.net/um67M/2/
I changed prefix from an array of strings to an array of objects.
You're going to see an issue if users type really fast because of the speed of fadeIn().
$(function() {
$("#message").hide();
$("#fail").hide();
var prefix = [{code:'HX',link:'www.facebook.com'}, {code:'BD',link:'www.bbc.com'}];
$('#myInput').keyup(function(e) {
var value = $(this).val();
var firstTwo = value.substr(0,2);
var firstTwoUpper = firstTwo.toUpperCase();
if(firstTwo != firstTwoUpper) {
$(this).val( value.replace(/^\w\w/, firstTwoUpper) );
}
if(value.length > 1) {
for(var obj in prefix){
console.log(firstTwoUpper, prefix[obj].code, firstTwoUpper == prefix[obj].code);
if(firstTwoUpper === prefix[obj].code){
$("#fail").hide();
var link = ''+prefix[obj].link+'';
$("#message").append(link);
$("#message:hidden").fadeIn();
break;
}else {
$("#message").hide();
$("#fail:hidden").fadeIn();
}
};
} else {
$("#message").empty();
$("#message").hide();
$("#fail").hide();
}
});
});
$('#myInput').keyup(function (e) {
var value = $(this).val();
var firstTwo = value.substr(0, 2);
var firstTwoUpper = firstTwo.toUpperCase();
if (firstTwo != firstTwoUpper) {
$(this).val(value.replace(/^\w\w/, firstTwoUpper));
}
if (value.length > 1) {
if ($.inArray(firstTwoUpper, prefix) >= 0) {
if (firstTwoUpper == "HX") {
$("#message").empty();
$("#message").html('<p>some message</p>Google');
} else if (firstTwoUpper == "HD") {
$("#message").empty();
$("#message").html('<p>other message</p><a `enter code here`href="http://www.stackoverflow.com">Stack OverFlow</a>');
}
$("#fail").hide();
$("#message:hidden").fadeIn();
} else {
$("#message").hide();
$("#fail:hidden").fadeIn();
}
} else {
$("#message").hide();
$("#fail").hide();
}
});
the fiddle is here
fiddle

Disable submit until form is filled javascript

I need to disable the submit button until all fields are filled with the rules any tips?
window.onload = $("input[type=submit]").attr("disabled", "disabled");
$(function(){
$("input[type=submit]").attr("disabled", "disabled");
var total = document.getElementById('valor_total'),
descontado = document.getElementById('valor_descontado'),
valor_final = document.getElementById('valor_final'),
vendedor = document.getElementById('vendedor'),
cliente = document.getElementById('cliente'),
no_contrato = document.getElementById('contrato'),
validation;
var f_total = total.value;
var f_descontado = descontado.value;
var f_final = valor_final.value;
var f_vendedor = vendedor.value;
var f_cliente = cliente.value;
var f_no_contrato = no_contrato.value;
$("#numero_contrato").blur(function() {
if ( f_vendedor == "0" || f_cliente == "0" || f_no_contrato == "" || f_total == "0,00" || f_final == "0,00") {
validation = false;
} else {
validation = true;
}
if (validation = true) {
$("input[type=submit]").removeAttr("disabled");
} else {
$("input[type=submit]").attr("disabled", "disabled");
}
});
});
what i'm doin wrong?
I want that user type in the field with id numero_contrato the function runs and enable or not the submit
For starters, try fixing this conditional:
if (validation === true) {
$('input[type=submit]').removeAttr('disabled');
} else {
$('input[type=submit]').attr('disabled', 'disabled');
}
You had a single equals which is used for assignment. You want double or preferably, triple equals. But you can drop those entirely since you're using a boolean: if (validation) { ... }

combining element ids

I'm trying to get both labels to appear but unfortunately only one of them is showing #city_label
<script type="text/javascript">
$(document).ready(function() {
function showDiv(element, pro2) {
if (pro2.children("option:selected").val() == 2) element.show();
else element.hide();
}
var myElement = $("div#pro2");
var mypro2 = $("select#ptype");
$("select").change(function() {
showDiv(myElement, mypro2)
});
$("#ctry").change(function() {
$(".state").hide();
var stateSelect = $("#state_" + $(this).val());
if (stateSelect.length === 0)
$("#state_label" && "#city_label").hide();
else {
$("#state_label" && "#city_label").show();
stateSelect.show();
}
});
});
</script>
HTML code:
<label id="state_label" style="display:none">State:</label><br />
<label id="city_label" style="display:none">Postal or City:</label>
That's... not how && works. In this case, it will return its right operand. What you want is this, using a comma in the selector:
<script type="text/javascript">
$(document).ready(function() {
function showDiv(element, pro2) {
if (pro2.children("option:selected").val() == 2) element.show();
else element.hide();
}
var myElement = $("div#pro2");
var mypro2 = $("select#ptype");
$("select").change(function() {
showDiv(myElement, mypro2)
});
$("#ctry").change(function() {
$(".state").hide();
var stateSelect = $("#state_" + $(this).val());
if (stateSelect.length === 0)
$("#state_label, #city_label").hide();
else {
$("#state_label, #city_label").show();
stateSelect.show();
}
});
});
</script>
You can't use the && operator the way you are, to select multiple elements at once you should include them in a single string separated by a comma; try this:
if (stateSelect.length === 0)
$("#state_label,#city_label").hide();
else {
$("#state_label,#city_label").show();
stateSelect.show();
}

AutoComplete (AutoFilter?), using jQuery delegate

$('#container form').delegate('#addSearch', 'keyup', function(e) {
var tmpVAL = $('#addSearch').val();
$('.w').each(function() {
var tmpHTML = $(this).html();
if (tmpHTML == tmpVAL) {
$(this).fadeIn(250);
} else if (tmpVAL.length < 1) {
$(this).fadeIn(250);
} else {
$(this).fadeOut(250);
}
});
});
and #addSearch is an <input type="text">.
So, my problem is that; this obviously will only return the results that are an exact match to the tmpVAL - How would I allow it so every letter will change the search result.
e.g.
I type N
it comes up with No, Not, Nothing, Nothingness
I type NOT
it comes up with Not, Nothing, Nothingness
Any help would be appreciated, I would imagine that it would be RegEx?
DEMO https://so.lucafilosofi.com/autocomplete-autofilter-using-jquery-delegate
$(function() {
$('#container form').delegate('#addSearch', 'keyup', function(e) {
var tmpVAL = $('#addSearch').val();
$('.w').each(function() {
var tmpHTML = $(this).text();
var subSection = tmpHTML.substring(tmpVAL.length, 0);
if (subSection == tmpVAL && tmpVAL != '' ) {
$(this).show();
} else {
$(this).hide();
}
});
});
});
You could use a regular expression, but I think that might be overkill. You could just use indexOf:
$('#container form').delegate('#addSearch', 'keyup', function(e) {
var tmpVAL = $('#addSearch').val().toLowerCase();
$('.w').each(function() {
var tmpHTML = $(this).html().toLowerCase();
if (tmpHTML.indexOf(tmpVAL) >= 0) {
$(this).fadeIn(250);
} else if (tmpVAL.length < 1) {
$(this).fadeIn(250);
} else {
$(this).fadeOut(250);
}
});
});
Working example: http://jsfiddle.net/andrewwhitaker/PRyvU/
Here's an alternative solution that doesn't use an .each():
$('#container form').delegate('#addSearch', 'keyup', function(e) {
var tmpVAL = $('#addSearch').val().toLowerCase();
var $words = $(".w");
var contains = function(haystack, needle) {
return haystack.indexOf(needle) >= 0;
};
if (tmpVAL.length < 1) {
$words.fadeIn(250);
}
else {
$words.filter(function() {
return !contains($(this).html().toLowerCase(), tmpVAL);
}).fadeOut(250);
$words.filter(function() {
return contains($(this).html().toLowerCase(), tmpVAL);
}).fadeIn(250);
}
});
http://jsfiddle.net/andrewwhitaker/EyJ6b/

Categories

Resources