Javascript Count number of time same value repeated in the textbox(s) - javascript

The below code add as yes if the master class text box value matches with the user but i want to compare the master with the user class and print the number count result in a div of how many input user class have the same repeated value of as master has.
Html:
<input class="master" value="1">
<input class="user" value="1">
<input class="user" value="1">
<input class="user" value="0">
<input class="user" value="0">
<div id="result_count"></div>
Javascript:
$(function() {
var master = $('input.master').get(0).value; // get the master value
var fn = function() {
return this.value === master ? "yes" : "no";//if current text-box matches master,then yes else no
};
$('input.user').val(fn); // loop and replace text for each user input
});

You should use the attribute selector based on the master input's value:
$(function() {
var master = $('input.master').val(); // get the master value
var userInputs = $('input.user');
var fn = function() {
return this.value === master ? "yes" : "no";//if current text-box matches master,then yes else no
};
userInputs.val(fn); // loop and replace text for each user input
// get inputs who has the same value as "master"
var inputs = userInputs.filter( 'input[value="'+ master +'"]' )
// Print the number of matches
console.log( inputs.length )
});
An example: http://jsfiddle.net/gjangztm/

This should do the job: http://codepen.io/zvona/pen/qOqKJe?editors=101
var masterValue = $('.master').val();
var $userInputs = $('.user');
var resultCount = $userInputs.filter(function(i, input) {
return $(input).val() === masterValue;
});
$('#result_count').text(resultCount.length);

$(function() {
var count=0;
var master = $('input.master').get(0).value; // get the master value
var fn = function() {
return this.value === master ? "yes" : "no";//if current text-box matches master,then yes else no
};
$('input.user').val(fn);
$(".user").each(function() {
if($(this).val()==master ){
++count;
}
});
$('#result_count').val(count);
});

var same = $('input.user').filter(function( index ) {
return ($(this).val() == $('.master').val());
})
console.log(same.length);
$('#result_count').text(same.length);
demo
Documentation for more information

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/

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

If text box value matches then make that specific label text to yes else no

Iam trying check if the text of label matches with the text box if matches then make that specific label text to yes else no but in my code am not sure what is wrong but that is not happening for all it is showing "no" it self
Demo
HTML
<input class="master" value="1">
<label class="user_label" >1</label>
<label class="user_label" >0</label>
<label class="user_label" >1</label>
JS:
$(function() {
var master = $('input.master').get(0).value; // get the master value
var fn = function() {
return this.text === master ? "yes" : "noo";//if current text-box matches master,then yes else no
};
$('label.user_label').text(fn); // loop and replace text for each user input
});
this.text will be undefined inside fn, because this is a DOM node, and it doesn't have text property.
You can wrap it as a jQuery object and use the text() method:
var fn = function() {
return $(this).text() === master ? "yes" : "noo";
}
http://jsfiddle.net/L6d39f10/5/
You can simplify your code as follows, second parameter in text() callback function refers the old text value. You can use val() for getting value in jQuery.
var val = $('input.master').val();
$('.user_label').text(function(i, text){
return val === text ? 'yes' : 'no';
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input class="master" value="1">
<label class="user_label">1</label>
<label class="user_label">0</label>
<label class="user_label">1</label>
when fn passed into $('label.user_label').text(fn) the context changed but still this.text is undefined. use this.textContent,this.innerHTML,$(this).text()
use text to compare and then modify it that makes logic odd, should it be like this?
$(function() {
$('input.master').keyup(function() {
var master = $(this).val(); // get the master value
var fn = function() {
return $(this).attr('data-val') === master ? "yes" : "noo"; //if current text-box matches master,then yes else no
};
$('label.user_label').text(fn); // loop and replace text for each user input
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<input class="master" value="">
<label class="user_label" data-val="1"></label>
<label class="user_label" data-val="0"></label>
<label class="user_label" data-val="1"></label>
$(function() {
var master = $('input.master').get(0).value; // get the master value
$('label.user_label').each(function(){
if($(this).text() === master){
$(this).text("yes");
}else{
$(this).text("no");
}
});
});

Add checkbox value to another hidden input field if first hidden field has content

I have a group of 4 checkboxes.
When any two have been checked they have their values copied to two hidden input fields.
The first checked checkbox value goes to the first input id="checkedBox1"
How do I get the second checked checkbox value to go to the second hidden input field id="checkedBox2"
I have used the JavaScript function below to place the values into each input from the individual checkboxes but can't figure out how to iterate through the list of all four checkboxes and place the two checked ones into each separate input field.
Checkboxes:
<input type="checkbox" value="test1" id="a" name="one"><label>Test11</label>
<input type="checkbox" value="test2" id="b" name="one"><label>Test12</label>
<input type="checkbox" value="test3" id="c" name="one"><label>Test13</label>
<input type="checkbox" value="test4" id="d" name="one"><label>Test14</label>
<input type="hidden" value="" id="checkedBox1">
<input type="hidden" value="" id="checkedBox2">
<script>
function populate() {
var checkboxes = document.getElementsByName('one');
var ip1 = document.getElementById('checkedBox1');
var ip2 = document.getElementById('checkedBox2');
// clear current values
ip1.value = ip2.value = '';
var first = false;
var second = false;
// Loop over checkboxes,stop when found 2 that are checked
for (var i=0,iLen=checkboxes.length; i<iLen || !(first && second); i++) {
if (checkboxes[i].checked) {
if (!first) {
ip1.value = checkboxes[i].value;
first = true;
} else if (!second) {
ip2.value = checkboxes[i].value;
second = true;
}
}
}
}
$('input[type="checkbox"]').on('change', function() {
populate();
}).change();
</script>
You could try plain JS, though I would use form property access rather than getElementsByName or getElementById:
function populate() {
var checkboxes = document.getElementsByName('one');
var ip1 = document.getElementById('checkedBox1');
var ip2 = document.getElementById('checkedBox2');
// clear current values
ip1.value = ip2.value = '';
var first = false;
var second = false;
// Loop over checkboxes,stop when found 2 that are checked
for (var i=0,iLen=checkboxes.length; i<iLen || !(first && second); i++) {
if (checkboxes[i].checked) {
if (!first) {
ip1.value = checkboxes[i].value;
first = true;
} else if (!second) {
ip2.value = checkboxes[i].value;
second = true;
}
}
}
}
Edit
Thanks Mal, added a line to clear the values of the hidden inputs each time.

Categories