validation in if textbox having same values in jquery - javascript

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

Related

Temporarily disable an input field if second input field is filled

I'm attempting to disable an input while the user is filling another input. I've managed to disable one of the two inputs while the other input is being filled in.
The problem is that I want the disabled input to ONLY be disabled WHILE the other input is being typed in.
So if the user changes their mind on the 1st input, they can delete what is in the current input which makes the 2nd input available and the 1st disabled.
JS
var inp1 = document.getElementById("input1");
inp1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("input2").disabled = true;
}
}
HTML
<input type="text" id="input1">
<input type="text" id="input2">
First, I would use input rather than change. Then, you need to set disabled back to false if the input is blank. Your check for whether it's blank is redundant, you just neither either side of your ||, not both. (I'd also use addEventListener rather than assigning to an .onxyz property, so that it plays nicely with others. :-) )
So:
var inp1 = document.getElementById("input1");
inp1.addEventListener("input", function () {
document.getElementById("input2").disabled = this.value != "";
});
<input type="text" id="input1">
<input type="text" id="input2">
...and then of course if you want it to be mutual, the same for input2.
You can achieve this using focus and blur. Below it is done with JQuery.
$(function() {
$('#input1').focus(function(){
$('#input2').prop('disabled', 'disabled');
}).blur(function(){
$('#input2').prop('disabled', '');
});
$('#input2').focus(function(){
$('#input1').prop('disabled', 'disabled');
}).blur(function(){
$('#input1').prop('disabled', '');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input1">
<input type="text" id="input2">
How about using keyup?
Like this;
var inp1 = document.getElementById("input1");
var inp2 = document.getElementById("input2");
inp1.onkeyup = function() { inputValidation(this, inp2); }
inp2.onkeyup = function() { inputValidation(this, inp1); }
function inputValidation(origin, lock) {
var response = hasValue(origin.value);
lock.disabled = response;
}
function hasValue(value) {
return value != "" && value.length > 0;
}
https://jsfiddle.net/8o3wwp6s/
Don't make it harder than it is, this is simple.
var one = document.getElementById('one');
var two = document.getElementById('two');
//checks instantly
var checker = setInterval(function() {
if(two.value !== '') {
one.disabled = true;
} else {
//when its clear, it enabled again
one.disabled = false;
}
if(one.value !== '') {
two.disabled = true
} else {
two.disabled = false;
}
}, 30);
<input id="one">
<input id="two">

Display number of Input fields based on the value in database column

I have a database table with column name qty that holds an int.Now i want to display as many input fields as the value in qty.
So far i haved tried this using iavascript code . Here is my javascript code .
$(function() {
var input = $(<input 'type'="text" />);
var newFields = $('');
$('#qty').bind('blur keyup change', function() {
var n = this.value || 0;
if (n+1) {
if (n > newFields.length) {
addFields(n);
} else {
removeFields(n);
}
}
});
function addFields(n) {
for (i = newFields.length; i < n; i++) {
var newInput = input.clone();
newFields = newFields.add(newInput);
newInput.appendTo('#newFields');
}
}
function removeFields(n) {
var removeField = newFields.slice(n).remove();
newFields = newFields.not(removeField);
}
});
Just store the value in the textfield(hidden)
HTML:
<input type="hidden" id="quantitycount" value="4" />
<div class="textboxarea"></div>
Jquery:
Get the textbox value
var quantitycount=jQuery('#quantitycount').val();
var txthtml='';
for(var txtcount=0;txtcount<quantitycount;txtcount++){
txthtml+='<input type="text" id="txtbox[]" value="" />';
}
jQuery('.textboxarea').html(txthtml);
You can use entry control loops to loop for number of times
Now we can see number of textbox as per need, Just the value from db and store that in the textbox
You can try this
foreach($qty as $qt){
echo '<input type="text">';
}
To append the text fields you need a wrapper on your html form
use some wrapper as mentioned by #Rajesh: and append your text-fields to that wrapper as shown below
$('#qty').bind('blur keyup change', function() {
var n = this.value || 0;
if (n >0) {
for(var x=0;x<n;x++){
$('#textboxarea').append('<input type="text" name="mytext[]"/>');
}
});
similarly you can write your own logic to remove the text-fields also using jquery

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

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

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

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