How can I know the duplicate input element value using jquery? - javascript

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;
}

Related

How to get the number of input tags containing certain text?

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/

can we use and operator to combine multiple jQuery events

I want to use jQuery to see if three text boxes are changed so I can send data through AJAX.
I tried a simple script:
$("#name, #position, #salary").change(function()
{
console.log("All data are changed");
});
Where name, position and salary are the respective IDs of three text box.
The result was that when I change the first one:
And when I changed the second:
And here is the third one:
So, I've got the message when separately each text box is changed. What I do need is when the three are changed, display the message. I am new to jQuery, so I want to know if I can use something like IF ... AND ... AND in jQuery.
A lot of validation frameworks have the concept of a dirty input once a user has changed the value. You could implement this and check when all your fields are dirty.
$("#name, #position, #salary").change(function() {
this.classList.add("dirty");
if ($(".dirty").length === 3) {
console.log("All data are changed");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="name" />
<input id="position" />
<input id="salary" />
We can abstract this out into a jQuery plugin for re-usability
$.fn.allChange = function(callback) {
var $elements = this;
$elements.change(function() {
this.classList.add("dirty");
if (callback && $elements.filter(".dirty").length === $elements.length) {
callback.call($elements);
}
});
return $elements;
}
$("#name, #position, #salary").allChange(function() {
console.log("All data are changed");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="name" />
<input id="position" />
<input id="salary" />
You can store changed inputs in an array, and check it's length to detect if all of them where changed.
var changedInputs = [];
$("#name, #position, #salary").change(function()
{
changedInputs.push(this.id);
if(changedInputs.length === 3) {
alert('All 3 inputs where changed!');
}
});
You can try:
var changedInputs = [];
$("#name, #position, #salary").change(function()
{
if !(changedInputs.include(this.id) ){
changedInputs.push(this.id);
if(changedInputs.length == 3) {
alert('All 3 inputs where changed!');
}
});
You can also use this approach. Fiddle
var isNameChanged, isPositionChanged, isSalaryChanged = false;
function fieldsChanged()
{
var id = $(this).attr('id');
if (id == 'name') isNameChanged = true;
else if (id == 'position') isPositionChanged = true;
else if (id == 'salary') isSalaryChanged = true;
if (isNameChanged && isPositionChanged && isSalaryChanged) {
console.log('All have been changed');
isNameChanged = isPositionChanged = isSalaryChanged = false;
}
}
$(function(){
$('#name, #position, #salary').change(fieldsChanged);
});
Try using a class:
<input class="need">
<input class="need">
<input class="need">
$(".need").change(function()
{
var all = 0;
$(".need").each(function(i,v){
if ($(v).val().length >0 ) {
all+=1;
}
});
if(all.length == 3) {
alert('All 3 inputs where changed!');
}
});
Store the multiple selectors in a variable. On .change() loop through the elements in the multiple selector to test the input values. If all inputs have content an additional function can be called.
$(document).ready(function(){
var $selectors = $('#input1, #input2, #input3');
$selectors.change(function(){
var allChanged = true;
console.log($(this).attr('id') + ' was changed.');
$selectors.each(function(){
if ($(this).val() == '') {
allChanged = false;
}
});
if (allChanged) {
// $().ajax();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input1">
<input id="input2">
<input id="input3">
one possible solution:
var needed = ["name", "position", "salary"];
$("#name, #position, #salary").change(function()
{
if(needed.length == 0) return;
needed.splice(needed.indexOf($(this).attr('id')), 1);
if(needed.length == 0)
console.log("All data are changed");
});
first, you need to init the array "needed" to all required fields
then, when a field is changed, you remove that field from the needed array
once the array is empty, all required values are changed ;)
the first condition is to ensure not to log the message more than once
You can compare current input value to default one, then the logic could be like following:
btw, i set a common class for all inputs to check, because this is how it should be done imho...
$('.inputToCheck').on('change', function() {
var allInputsChanged = !$('.inputToCheck').filter(function() {
return this.value === this.defaultValue;
}).length;
if (allInputsChanged) alert('All inputs changed!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="name" class="inputToCheck">
<input id="position" class="inputToCheck">
<input id="salary" class="inputToCheck">

jQuery get input val() from $("input") array

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;
}

validation in if textbox having same values in jquery

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

maxlength not working if value is set from js code

I am having the following HTML block in my page.
<input type="text" id="fillingInput"/>
<input type="text" id="filledInput" maxlength="5"/>
<input type="button" onclick="$('#filledInput').val($('#fillingInput').val());"/>
when the button is clicked, the value of fillingInput is set as value for filledInput.
But the maxlength is not considered while setting value like this.
Any solution?
Try slice:
<input type="button"
onclick="$('#filledInput').val($('#fillingInput').val().slice(0,5));"/>
Try this
$(document).ready(function () {
$('#add').click(function () {
var str = $('#fillingInput').val();
if (str.length > 5) {
str = str.substring(0, 5);
$('#filledInput').val(str);
}
});
});
one way to get this is ... removing all charaters after 5th character. using substring()
<input type="button" id="add" />
JS
$('#add').click(function(){
var str=$('#fillingInput').val();
if(str.length > 5) {
str = str.substring(0,5);
}
$('#filledInput').val(str);
});
fiddle ..
it is recommended not to use inline javascript.
if you are using jQuery you can add a "valHook" which hooks into each call of .val()
$.valHooks.input = {
set: function(element, value) {
if ("maxLength" in element && value.length > element.maxLength)
value = value.substr(0, element.maxLength);
element.value = value;
return true;
}
};

Categories