I have a function that returns whether or not every text input in a form has a value.
When I first made the function it looked like this:
function checkInput(inputId) {
check = 0; //should be 0 if all inputs are filled out
for (var i=0; i < arguments.length; i++) { // get all of the arguments (input ids) to check
var iVal = $("#"+arguments[i]).val();
if(iVal !== '' && iVal !== null) {
$("#"+arguments[i]).removeClass('input-error');
}
else {
$("#"+arguments[i]).addClass('input-error');
$("#"+arguments[i]).focus(function(){
$("input").removeClass('input-error');
$("#"+arguments[i]).off('focus');
});
check++;
}
}
if(check > 0) {
return false; // at least one input doesn't have a value
}
else {
return true; // all inputs have values
}
}
This worked fine, but when I called the function I would have to include (as an arstrong textgument) the id of every input I wanted to be checked: checkInput('input1','input2','input3').
Now I am trying to have my function check every input on the page without having to include every input id.
This is what I have so far:
function checkInput() {
var inputs = $("input");
check = 0;
for (var i=0; i < inputs.size(); i++) {
var iVal = inputs[i].val();
if(iVal !== '' && iVal !== null) {
inputs[i].removeClass('input-error');
}
else {
inputs[i].addClass('input-error');
inputs[i].focus(function(){
$("input").removeClass('input-error');
inputs[i].off('focus');
});
check++;
}
}
if(check > 0) {
return false;
}
else {
return true;
}
}
When I call the function it returns this error:
Uncaught TypeError: inputs[i].val is not a function
What am I doing wrong?
When you do inputs[i], this returns an html element, so it is no longer a jquery object. This is why it no longer has that function.
Try wrapping it with $() like $(inputs[i]) to get the jquery object, and then call .val() like:
$(inputs[i]).val()
If you are going to use this in your for loop, just set it as a variable:
var $my_input = $(inputs[i])
Then continue to use it within the loop with your other methods:
$my_input.val()
$my_input.addClass()
etc..
if you use jquery .each() function, you can do it a little cleaner:
$(document).ready(function() {
$('.submit').on('click', function() {
$('input').each(function() {
console.log('what up');
if($(this).val().length < 1 ) {
$(this).addClass('input-error');
}
else {
$(this).removeClass('input-error');
}
});
});
});
.input-error {
background-color: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<br/>
SUBMIT
This is actually a very simple fix. You need to wrap you jquery objects within the jquery constructor $()
Such as for inputs[i].val() to $(inputs[i]).val();
Here is the full working example:
http://jsbin.com/sipotenamo/1/edit?html,js,output
Hope that helps!
This is exactly one of the things the .eq() method is for. Rather than using inputs[i], use the following:
// Reduce the set of matched elements to the one at the specified index.
inputs.eq(i)
Given a jQuery object that represents a set of DOM elements, the .eq() method constructs a new jQuery object from one element within that set. The supplied index identifies the position of this element in the set.
in this case, I would make use of the jQuery.each() function for looping through the form elements. This will be the modified code
function checkInput() {
var $inputs = $("input"),
check = 0;
$inputs.each(function () {
val = $.trim($(this).val());
if (val) {
$(this).removeClass('input-error');
}
else {
$(this).addClass('input-error');
$(this).focus(function () {
$("input").removeClass('input-error');
$(this).off('focus');
});
check++;
}
});
return check == 0;
}
Related
Hi have a html code like this
<input type="text" value="quantita" id="quantita" name="quantita">
<input type="text" value="prodotto" id="prodotto" name="prodotto">
<input type="text" value="prezzo" id="prezzo" name="prezzo">
Now I'm trying to do a jquery code that add a button if the value of all these id is different from NULL
so I do this
var list = $("#prezzo", "#quantita", "#prodotto").val();
if (list!="")
{...do this...}
else
{....do nothing...}
but it doesn't work
You could do it like this instead
var list = $("#prezzo, #quantita, #prodotto").filter(function() {
return this.value === "";
}).length === 0;
if (list) { // All values set
assuming you meant the value is an empty string, as in no value set, and not actually the string NULL ?
$("#prezzo,#quantita,#prodotto").each(function()
{
if ($(this).val() !="" )
{}
else
{}
});
My goal is to flag when a user enters the same text into one input that matches at least one other input's text. To select all of the relevant inputs, I have this selector:
$('input:text[name="employerId"]')
but how do I select only those whose text = abc, for instance?
Here is my change() event that checks for duplicate text among all the inputs on the page. I guess I am looking for something like :contains but for text within an input.
var inputsToMonitorSelector = "input[type='text'][name='employerId']";
$(inputsToMonitorSelector).change(function() {
//console.log($(this).val());
var inputsToExamineSelector = inputsToMonitorSelector
+ ":contains('" + $(this).val() + "')";
console.log(inputsToExamineSelector);
if($(inputsToExamineSelector).length > 1) {
alert('dupe!');
}
});
Or is there no such selector? Must I somehow select all the inputsToMonitorSelector's and, in a function, examining each one's text, incrementing some local variable until it is greater than one?
With input you need to use [value="abc"] or .filter()
$(document).ready(function() {
var textInputSelector = 'input[type="text"][name="employerId"]';
$(textInputSelector).on('input', function() {
$(textInputSelector).css('background-color', '#fff');
var input = $(this).val();
var inputsWithInputValue = $(textInputSelector).filter(function() {
return this.value && input && this.value == input;
});
var foundDupe = $(inputsWithInputValue).length > 1;
if(foundDupe) {
console.log("Dupe found: " + input);
$(inputsWithInputValue).css('background-color', '#FFD4AA');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="employerId" value="abc">
<input type="text" name="employerId" value="">
<input type="text" name="employerId" value="">
<input type="text" name="employerId" value="">
[value="abc"] means if the value is abc
[value*="abc"] * means if the value contains abc
[value^="abc"] ^ means if the value starts with abc
[value$="abc"] $ means if the value ends with abc
Note: :contains() not for inputs , and word text not used with inputs and <select>.. inputs and <select> has a value
In your case .. instead of using
$(inputsToExamineSelector).length > 1)
You may need to use .filter()
$(inputsToExamineSelector).filter('[value*="abc"]').length > 1)
OR
$('input[type="text"][name="employerId"]').filter(function(){
return this.value.indexOf('abc') > -1
// for exact value use >> return this.value == 'abc'
}).length;
And to use a variable on it you can use it like
'[value*="'+ valueHere +'"]'
Something like this works. Attach isDuplicated(myInputs,this.value) to a keyup event listener attached to each input.
var myInputs = document.querySelectorAll("input[type='text']");
function isDuplicated(elements,str){
for (var i = 0; i < myInputs.length; i++) {
if(myInputs[i].value === str){
myInputs[i].setCustomValidity('Duplicate'); //set flag on input
} else {
myInputs[i].setCustomValidity(''); //remove flag
}
}
}
Here's another one. I started with vanilla js and was going for an answer like Ron Royston with document.querySelector(x) but ended up with jquery. A first attempt at several things but here you go:
$("input[type='text']").each(function(){
// add a change event to each text-element.
$(this).change(function() {
// on change, get the current value.
var currVal = $(this).val();
// loop all text-element-siblings and compare values.
$(this).siblings("input[type='text']").each(function() {
if( currVal.localeCompare( $(this).val() ) == 0 ) {
console.log("Match!");
}
else {
console.log("No match.");
}
});
});
});
https://jsfiddle.net/xxx8we6s/
I am trying to perform this action like if user choose same value for two different box i have to show some errors.my textbox code as follows.
<input class="order form-control vnumber" type="text" maxlength="1" name="Orderbox[]" required="true">
<input class="order form-control vnumber" type="text" maxlength="1" name="Orderbox[]" required="true">
<input class="order form-control vnumber" type="text" maxlength="1" name="Orderbox[]" required="true">
<input class="order form-control vnumber" type="text" maxlength="1" name="Orderbox[]" required="true">
so the textbox values should be different like 1,2,3,4 it should not be 1,1,1,1 so i have tried real time update using jquery.
$('.order').keyup(function () {
// initialize the sum (total price) to zero
var val = 0;
var next_val=0;
// we use jQuery each() to loop through all the textbox with 'price' class
// and compute the sum for each loop
$('.order').each(function() {
val+=$(this).val();
});
alert(val);
if (next_val==val) {
alert("same value");
}
next_val=val;
});
But its not working as i expected can anybody tell is there any solutions for this.Any help would be appreciated.Thank you.
JFIDDLE:
jfiddle
Try this Demo Fiddle.
var valarr = [];
$('.order').keyup(function () {
var curr = $(this).val();
if (jQuery.inArray(curr, valarr) > -1) {
alert('exists');
} else {
valarr.push(curr);
}
});
You can use arrays to maintain values. To check the existence of value use inArray()
You need to put more of the code inside the .each() loop. Also, change val+= to just val=
$('.order').each(function() {
val=$(this).val();
alert(val);
if (next_val==val) {
alert("same value");
}
next_val=val;
});
And keep in mind next_val is actually the previous value...
fiddle http://jsfiddle.net/phZaL/8/
This will only work if all values entered till now have the same value
jQuery Code
var arr = [];
$('.order').change(function () {
arr.push($(this).val());
if (arr.length > 1) {
if (arr.AllValuesSame()) alert("Values are same");
}
var val = 0;
$.each(arr, function () {
val = parseInt(val) + parseInt(this);
});
$('.val').text(val);
});
Array.prototype.AllValuesSame = function () {
if (this.length > 0) {
for (var i = 1; i < this.length; i++) {
if (this[i] !== this[0]) return false;
}
}
return true;
}
Demo Fiddle
Made with great help from this answer by #Robert
Im new to web dev and jQuery. I have input element binded with blur event.
This is my code:
// this are my input elements:
<input class="input_name" value="bert" />
<input class="input_name" value="king kong" />
<input class="input_name" value="john" />
<input class="input_name" value="john" />
<script>
$(".input_name").bind("blur",function(){
alert(findDuplicate($(this).val()));
})
function findDuplicate(value){
var result = 0;
$(".input_name").each(function{
if($(this).val == value){
result++;
}
});
}
</script>
my main problem is when i change bert to john it returns me 3 result. how would i exempt the event sender from being checked?
Like others have mentioned, you've got a few syntax errors. Also, rather than explicitly iterating over all the inputs, you could just have jQuery find them for you using selectors:
$(".input_name").bind("blur",function(){
alert(findDuplicate($(this).val()));
})
function findDuplicate(value){
return $(".input_name[value='" + value + "']").length - 1;
}
$(".input_name").bind("blur", function () {
alert(findDuplicate(this.value));
})
function findDuplicate(value) {
var result = 0;
$(".input_name").each(function(){
if (this.value == value) {
result++;
}
});
return result - 1;
}
DEMO
Try this (untested):
$(".input_name").bind("blur",function(){
var nth = $(this).index();
alert(findDuplicate($(this).val(),nth));
})
function findDuplicate(value,nth){
var result = 0;
$(".input_name").each(function{
if($(this).val == value && nth != index){
result++;
}
});
return result;
}
I have problem with passing an argument to my simple function in jQuery:
When function is attached directly to the element everything is OK.
$companyNameInputs.bind('blur keyup',function(){
if ($(this).hasClass('required')) {
if (this.value == ''){
$(this).addClass('inputError');
}else {
$(this).removeClass('inputError');
}
}
});
but when I want to declare this simple check as an different function it doesn't work:
this is my function:
var standardCheck = function($param){
$param.addClass('inputError');
if ($param.hasClass('required')) {
if ($.trim($param).value == ''){
$param.addClass('inputError');
}else {
$param.removeClass('inputError');
}
}
};
and this is how I call it:
$companyNameInputs.bind('blur keyup',function(){
standardCheck($(this));
});
variable declaration:
var $companyNameInputs = $("#companyName")
and the HTML:
<div>
<p>
<input class="text_input" type="text" id="companyName" name="companyName" value="" />
</p>
</div>
please help.
Since param is a jQuery container, you have to call .val() and trim the output of that:
if ($.trim($param.val()) == ''){
or get the corresponding DOM element and its value property.
if ($.trim($param[0].value) == ''){