remove duplicate entry from html input boxes in JavaScript/jQuery - javascript

I have a fiddle which checks for any duplicate entry entered in html input boxes.
It works in a way that if any duplicate entry is entered in a newly added row or the rows which are already there then the alert message "duplicate" is displayed.
I have used the following script in order to make that happen.
$('input[name*="code"]').each(function() {
$(this).change(function(){
let value = $(this).val();
let count = 0;
$('input[name*="code"]').each(function() {
if ($(this).val() != '' && $(this).val() == value) {
count++;
if (count > 1) { alert('duplicate'); }
}
});
});
$(this).addClass('e');
});
$('#addRow').on('click', function(){
$('input[name*="code"]:not(.e').each(function() {
$(this).change(function(){
let value = $(this).val();
let count = 0;
$('input[name*="code"]').each(function() {
if ($(this).val() != '' && $(this).val() == value) {
count++;
if (count > 1) alert('duplicate');
}
});
});
$(this).addClass('e');
});
});
What I am trying to achieve now is when any duplicate entry is entered in html input boxes then it should get disappeared automatically and the text "Please enter different text" left to the row should be displayed, something like this
http://jsfiddle.net/zHJSF/
This is what I have tried but it doesn't seem to work.
$('input[name*="code"]').each(function() {
$(this).change(function(){
let value = $(this).val();
let count = 0;
$('input[name*="code"]').each(function() {
if ($(this).val() != '' && $(this).val() == value) {
count++;
if (count > 1) {
alert('duplicate');
($(this).val()).stop(false,true).after(' <span style="color:red;" class="error">Please enter different text</span>');
$('.error').delay(600).fadeOut();
$(this).val('');
}
}
});
});
$(this).addClass('e');
});
$('#addRow').on('click', function(){
$('input[name*="code"]:not(.e').each(function() {
$(this).change(function(){
let value = $(this).val();
let count = 0;
$('input[name*="code"]').each(function() {
if ($(this).val() != '' && $(this).val() == value) {
count++;
if (count > 1) {
alert('duplicate');
($(this).val()).stop(false,true).after(' <span style="color:red;" class="error">Please enter different text</span>');
$('.error').delay(600).fadeOut();
$(this).val('');
}
}
});
});
$(this).addClass('e');
});
});
Problem Statement:
I am wondering what changes I should make in the script above so that it get rid of any duplicate entry entered in the html input boxes.

EDIT
This should work. It will get the input values and put them into an array, then check if the value exists in the array.
javascript
$('input[name*="code"]').each(function() {
$(this).change(function(){
let element = this;
var array = $('input[name*="code"]').map(function() {
if (this != element)
return $(this).val()
return null;
}).get();
if (array.includes($(this).val())) {
$(this).val("");
$(this).attr("placeholder", "Please enter different text");
$(this).addClass("error");
} else if ($(this).hasClass("error")) {
$(this).removeClass("error");
}
});
$(this).addClass('e');
});
css
.error {
border: 1px solid red;
}

Related

JQuery Filtering Table with Search Input

I have 2 dropdowns that filter a table. These work properly. They show/hide rows based on the selection. I also want to add a search to further filter the rows, but I cannot get this to work.
For Example
The search needs to take into account the dropdown selections. So if dropdown 1='Three' and dropdown 2='Four' (for instance) - 5 rows are returned. If I start typing in the search box 'Right' then 2 rows should appear. When I back out of the search, then the 5 rows should reappear(dropdown filters intact)
CODEPEN: https://codepen.io/rblanc/pen/eYOEgXg
Here is the JQuery
$(function() {
$('#archive, #type').change(function() {
filterTable($('#archive').val(), $('#type').val());
});
});
function filterTable(archive, entry) {
var $rows = $('#filter tbody tr').show();
if (archive == "one") {
$rows.filter(":has(td:nth-child(4):contains('Two'))").hide()
$rows.filter(":has(td:nth-child(4):contains('Three'))").hide()
} else if (archive == "two") {
$rows.filter(":has(td:nth-child(4):contains('One'))").hide()
$rows.filter(":has(td:nth-child(4):contains('Three'))").hide()
} else if (archive == "three") {
$rows.filter(":has(td:nth-child(4):contains('One'))").hide()
$rows.filter(":has(td:nth-child(4):contains('Two'))").hide()
}
if (entry == "one") {
$rows.filter(":has(td:nth-child(6):contains('N'))").hide()
$rows.filter(":has(td:nth-child(7):contains('Y'))").hide()
$rows.filter(":has(td:nth-child(8):contains('Y'))").hide()
} else if (entry == "two") {
$rows.filter(":has(td:nth-child(6):contains('Y'))").hide()
$rows.filter(":has(td:nth-child(7):contains('Y'))").hide()
$rows.filter(":has(td:nth-child(8):contains('N'))").hide()
} else if (entry == "three") {
$rows.filter(":has(td:nth-child(6):contains('Y'))").hide()
$rows.filter(":has(td:nth-child(7):contains('N'))").hide()
$rows.filter(":has(td:nth-child(8):contains('Y'))").hide()
} else if (entry == "four") {
$rows.filter(":has(td:nth-child(6):contains('N'))").hide()
$rows.filter(":has(td:nth-child(7):contains('Y'))").hide()
$rows.filter(":has(td:nth-child(8):contains('N'))").hide()
}
}
// SEARCH INPUT
$("#search").on("keyup", function() {
var value = $(this).val();
$("table tbody tr").each(function(index) {
if (index !== 0) {
$row = $(this);
var id = $row.find("td:first").text();
if (id.indexOf(value) !== 0) {
$row.hide();
}
else {
$row.show();
}
}
});
});

Textbox Maxlength Issue for amount field

I have a situation having a textbox having 15 as a max length property. That field works as a amount field. it is working correctly in normal cases.
lets say if i enter 11234567890.99 this amount in textbox it displays it as 112,34,567,890.99 which is expected.
But, if i copy & paste 112,34,567,890.99 amount in textbox last two digits gets truncated because the length gets out of bound.
Is there any ways to change this without modifying the exact behavior? allowing to paste whole 112,34,567,890.99 amount.
$(document).on("focusout","#txtformate1",(function () {
if (this.value != null && this.value != "") {
$((this.parentElement).nextElementSibling).hide()
}
else{
$((this.parentElement).nextElementSibling).show()
}
}));
$(document).on('keyup', '.Amt', function () {
var val = $(this).val();
val = val.replace(/([~!#$%^&*()_+=`{}\[\]\|\\:;'<>,\/? ])+/g, '');
if(isNaN(val) && val!="-")
{
val="";
}
$(this).val(val);
/*if (isNaN(val)) {
val = val.replace(/(?!^)-/g, '');
if(val.indexOf("-")>-1)
{
val = val.replace(/[`*\/]/g, '');
}
else{val = val.replace(/[^0-9\.]/g, '');}
if (val.split('.').length > 2)
{
val = val.replace(/\.+$/, "");
}
else if(val==".")
{
val ="";
}
}*/
});
$(document).on('focusout', '.Amt', function () {
var val = $(this).val();
val = val.replace(/(?!^)-/g, '');
if(isNaN(val) && val.indexOf(',')>-1){
val=$(this).val();
}
if (val == "0.00"){
val="";
}
$(this).val(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control Amt" id="txtformate1" maxlength="15" />`

Sum with jquery not working

I have a lot of labels as shown on a page. I want to sum the values and store them in final_cpa.
HTML :
<label class="tmpcpa">32.1</label>
JS :
function calculate_final_cpa() {
var final_cpa = 0;
var allfilled = false;
$('.tmpcpa').each(function () {
if ($(this).val() != 0) {
final_cpa += parseInt($(this).text()) || 0;
allfilled = true;
} else {
allfilled = false;
}
});
console.log(final_cpa);
console.log(allfilled);
}
var run = setInterval(calculate_final_cpa, 500);
However final_cpa is always 0 and allfilled remains false.
That because label don't have a value attribute so the .val() function will always return an empty string, you have to use .text() instead to get the text content inside the label element :
if ($(this).val() != 0) {
Should be :
if ($(this).text() != 0) {
NOTE : as Rayon mentioned in the comment below text() will always return string so better to change the zero in condition to string '0'.
Hope this helps.
function calculate_final_cpa() {
var final_cpa = 0;
var allfilled = false;
$('.tmpcpa').each(function () {
if ($(this).text() != '0') {
final_cpa += parseInt($(this).text()) || 0;
allfilled = true;
} else {
allfilled = false;
}
});
console.log(final_cpa);
console.log(allfilled);
}
calculate_final_cpa();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="tmpcpa">32.1</label>
Check $(this).text() != "" instead of $(this).val() != 0 as You can not use .val() for getting label text. .text() will give you text of label
if ($(this).text() != "" && $(this).text() != "0") {
....
}
First thing, you need to use .text() instead of .val() to get the text inside a label. Also, if you are expecting your result to contain decimal digits, you need to use parseFloat():
function calculate_final_cpa() {
var final_cpa = 0;
var allfilled = false;
$('.tmpcpa').each(function () {
if ($(this).text() != 0) {
final_cpa += parseFloat($(this).text()) || 0;
allfilled = true;
} else {
allfilled = false;
}
});
console.log(final_cpa);
console.log(allfilled);
}
calculate_final_cpa();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<label class="tmpcpa">32.1</label>
<br />
<label class="tmpcpa">32.1</label>
Change
if ($(this).val() != 0)
to
if (parseInt($(this).text()) != 0)
Beside your code had an error, you should check the content of the table before parsing them. And because you use decimals in your example, you should switch from parseInt to parseFloat too.
And your allfilled varibale makes no sense, because if the last element of .tmpcpa was empty, it will be false again. So i removed it.
function calculate_final_cpa() {
var final_cpa = 0;
$('.tmpcpa').each(function () {
var content = $(this).text();
final_cpa += IsNumeric(content) ? parseFloat(content) : 0;
});
console.log(final_cpa);
}
Test it with .text instead of val() as label has no value property
Use Unary plus(+)/Number operator instead of parseInt as parseInt will ignore floating point
Use length of lable-elements to test whether all the label has values !== 0
function calculate_final_cpa() {
var final_cpa = 0;
var countOfFilled = 0;
$('.tmpcpa').each(function() {
if ($(this).text() !== '0') {
final_cpa += +($(this).text()) || 0;
++countOfFilled;
}
});
console.log('Total: ' + final_cpa);
console.log('All filled ' + $('.tmpcpa').length === countOfFilled);
}
calculate_final_cpa();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<label class="tmpcpa">32.1</label>
<label class="tmpcpa">32.1</label>
<label class="tmpcpa">0</label>

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

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

How to submit form only one check box is selected using java script

on edit button click a want to submit form only if one check box checked,don't submit when 0 or more than 2 check box checked
my below code is not working
$("#editbtn_id").click(function () {
var cnt = 0;
var checkbox_value = "";
$(":checkbox").each(function () {
var ischecked = $(this).is(":checked");
});
if (ischecked) {
checkbox_value += $(this).val();
cnt = cnt + 1;
if (cnt == 0 || cnt > 1) {
alert(cnt);
alert("Please select one Test case");
return false;
}
}
return false;
});
HTML
<form action="/editSingletest/{{ testcase.id }}" method="post" onsubmit="return" >
<input type="checkbox"/>
</form>
You can achieve this by following code
$("#editbtn_id").click(function(){
var cnt=0;
var checkbox_checked_count = 0;
var form_submit = false;
$(":checkbox").each(function () {
if($(this).is(":checked")) {
checkbox_checked_count++
}
});
if(checkbox_checked_count == 1) {
form_submit = true;
}
else if(checkbox_checked_count > 1) {
alert("Please select one Test case");
}
alert(form_submit)
$("form").submit();
});
Check working example here in this fiddle
Your counter is in the wrong loop, should be something like this:
$("#editbtn_id").click(function(){
var cnt=0;
var checkbox_value = "";
$(":checkbox").each(function () {
var ischecked = $(this).is(":checked");
if (ischecked){
checkbox_value += $(this).val();
cnt=cnt + 1 ;
}
});
if(cnt==0 || cnt > 1){ ... }
});
try this
$("#editbtn_id").click(function (e) {
if($('form input[type="checkbox"]:checked').length == 1){
$('form').submit();
}
else{
e.preventDefault();
}
});
for 'form' use your form selector

Categories

Resources