Validation to prevent duplicated values on input text - javascript

Im trying to prevent duplicated values on inputs with same name when I click a submit button, but it is not working and i am not sure why...
I need some help to understand why is not working?
Thanks lot in advance!
this is my code:
I tried with a solution I found here which it worked "on input change" behavior, but it doesnt with button click...
My button:
<button type="button" id="approve" class="positive valid" tabindex="-1">Approve</button>
and my jquery
$('#received').on('click',function() {
var $current = $(this);
if ($('input[name^="RE_SignedByID"]').val() == $current.val() && $('input[name^="RE_SignedByID"]').attr('tabindex') !== $current.attr('tabindex') ) {
alert('You can not have duplicated ID´s');
return false;
}else {
return true;
}
});
I want to show an alert and prevent the submit.
Thanks a lot for any help!

The issue is because you're comparing the value of the clicked button to the first input[name^="RE_SignedByID"] element.
To fix this you could instead create an array of all the input[name^="RE_SignedByID"] values using map(). You can then dedupe this list and compare the resulting array lengths. If they are different there was a duplicate. Try this:
$('#received').on('click', function(e) {
var values = $('input[name^="RE_SignedByID"]').map(function() {
return this.value.trim();
}).get();
var unique = [...new Set(values)];
if (values.length != unique.length) {
e.preventDefault();
alert('You can not have duplicated ID\'s');
}
});
Note that [...new Set(values)] will not work in IE. If you need to support legacy browsers there are plenty of alternatives to dedupe an array. See this answer for more information.

I could fix it! Here is the code... you can add a button event like:
$('#submit').on('click', function () {
var values = $('[name=RE_SignedByID]').map(function() {
return this.value.trim();
}).get();
var values2= $('[name=RE_OwnersID]').map(function() {
return this.value.trim();
}).get();
values.sort();
values2.sort();
for (var i = 0; i < values.length-1; i++) {
if( values[i] == values[i+1] && values[i] !=""){
showAlert(translator.getTranslation(' You can not have duplicated signers ID\'s'));
return false;
// break;
}
}
for (var i = 0; i < values2.length-1; i++) {
if( values2[i] == values2[i+1] && values2[i] !=""){
showAlert(translator.getTranslation(' You can not have duplicated owners ID\'s'));
return false;
// break;
}
}
});

Related

disable anchor link '<a>' if one of my six checkboxes are not checked

How can I disable a anchor link if one(1) of my six(6) checkbox is not check?
var first_option = $('#pid-1590083, #pid-1590090, #pid-1590091, #pid-1590092, #pid-1590093, #pid-1590094');
$("a").click(function(e) {
if($("first_option").prop("checked") === false) {
e.preventDefault(); return false;
} else {return true;};
});
Your current logic doesn't work as you're only looking at the checked property of the first element you select, not all of them.
To achieve what you require, you can use the :checked selector to get all the checked elements within the selectors you provide, then check the length property of the result to see if there aren't any. Try this:
var $first_option = $('#pid-1590083, #pid-1590090, #pid-1590091, #pid-1590092, #pid-1590093, #pid-1590094');
$("#tmp_button-99035").click(function(e) {
if ($first_option.filter(':checked').length === 0) {
e.preventDefault();
alert('Please Choose Collar Colour To Continue');
};
});
first_option.prop("checked") will always check for first element. What you have to do is loop over all elements to check
Like this
$("#tmp_button-99035").click(function(e) {
var isChecked = false;
for (var i = 0; i < first_option.length; i++) {
if (first_option.eq(i).prop("checked")) {
isChecked = true;
break;
}
}
if (!isChecked) {
alert('Please Choose Collar Colour To Continue');
e.preventDefault();
}
return isChecked;
});
Well, the js snippet of yours is only checking the first element. So, you have to track other checkboxes as well for correct result.
var first_option = $('#pid-1590083, #pid-1590090, #pid-1590091, #pid-1590092, #pid-1590093, #pid-1590094')
$(document).on('click', '#tmp_button-99035', function (e) {
if ($(first_option).filter(":checked").length == 0) {
e.preventDefault();
}
});

Adding select/deselect all to dynamic tabular form

I have a form which contains buttons to add and delete rows. My javascript function to check all checkboxes works for the first row, but once I add more rows to the form, the first row is still the only one that gets checked.
Any tips?
Here is my javascript function:
<code>
//checks all rows
function checkAll() {
var masterCheck = document.getElementById('masterCheck');
var on = false;
if(masterCheck.checked==true) {
document.getElementById('checkbox').checked=true;
} else {
document.getElementById('checkbox').checked=false;
}
}
</code>
And here is the form:
http://crimsonroot.com/files/freelance/new.html
Any help is appreciated!
I found out what was wrong! #Mohammed your answer really helped. There were just one or two syntax errors that I found. In order to check and uncheck all of the boxes, I needed to add a boolean variable as an input to the function as follows:
//checks all rows
function checkAll(bool) {
var masterCheck = document.getElementById('masterCheck');
var allcheck = document.getElementsByClassName('checkbox');
var on = false;
for (var i = 0; i < allcheck.length; i++) {
if (masterCheck.checked == true) {
allcheck[i].checked = true;
} else {
allcheck[i].checked = false;
}
}
}
For some reason, this was the final piece to the puzzle. Thanks for all of the help!
You should try something like this.
$("#masterCheck").click(function () {
$('input:checkbox').not(this).prop('checked', this.checked);
});
Since document.getElementById() returns first element, because id cannot be used more than one. To make it usable, add a class checkbox and try the following code:
//checks all rows
function checkAll() {
var masterCheck = document.getElementById('masterCheck');
var allcheck = getElementsByClassName('checkbox');
var on = false;
for (var i = 0; i < allcheck.length; i++) {
if (masterCheck.checked == true) {
allchecked[i].checked = true;
} else {
allchecked[i].checked = false;
}
}
}

kendo ui grid: Compare data in multiple selected rows?

Ok, rephrasing the question here, it seems the articulation was lacking.
I have a kendo ui grid, and when I make multiple selections (2 or more at a time) of rows, I need to compare values of a specific column in all the selected rows to determine if they are exactly equal(same) or not. Here's is my kendo 'change: ' function, the dataItem in question we'll call 'fancyNumber':
change: function(e) {
var selectedRows = this.select();
var selectedDataItems = [];
for (var i = 0; i < selectedRows.length; i++) {
var dataItem = this.dataItem(selectedRows[i]);
selectedDataItems.push(dataItem);
}
var selected = $.map(this.select(), function(item) {
return $(item).text();
});
function allValuesSame() {
for (var i = 1; i < selectedRows.length; i++)
{
if(this[i] != this[0])
return false;
}
return true;
}
if (selected.length > 1){
var selectedRows = $("#myTable").data("kendoGrid").select();
var fancyNumberText = this.dataItem(this.select()).fancyNumber
if (allValuesSame(fancyNumberText) === true) {
alert(fancyNumberText); //just testing to see what I get
}
return allValuesSame(fancyNumberText);
}
if (selected.length == 0) {
$('#fancyButton').attr('disabled', 'disabled');
} else if (selected.length == 1) {
$('#fancyButton').attr('disabled', false);
} else if (selected.length > 1 && allValuesSame == true) {
$('#fancyButton').attr('disabled', false);
}
},
Clearly, this isn't correct; how do I do this?
You can use the .dataSource property to get the model that your grid is bound to and make the comparison there.
http://docs.telerik.com/kendo-ui/api/javascript/ui/grid#fields-dataSource
Say your grid has an Id of myDataGrid, you would use:
var gridModel = $("#myDataGrid").data("kendoGrid").dataSource.data();
// Sample comparison
if (gridModel[3].someField === gridModel[5].someField) {
// Do something with your buttons
}
You need to set up the grid with the following...
.Selectable(sel => sel.Mode(GridSelectionMode.Multiple))
.Events(e => e.Change("onChange"))
Once you have these in place, you can select individual lines and you have an event which is called on selection onChange
In your script, wire up this funciton...
function onChange() {
//you can get the selected row like this
var selected = $.map(this.select(), function(item) {
return item.getAttribute('data-uid');
});
//if selected count > 1 then check logic and enable/disable button
EnableDisableButton(true, "#myButton");//assuming condition was good
}
You need to set up the onChange to record the rows values from each selection, maybe using an array and then comparing the values in the array.
function EnableDisableButton(isToBeEnabled, buttonName) {
if (isToBeEnabled)
$(buttonName).removeAttr("disabled").removeClass("k-state-disabled");
else
$(buttonName).prop("disabled", true).addClass("k-state-disabled");
}

Check if input value is empty and display an alert

How is it possible to display an alert with jQuery if I click the submit button and the value of the input field is empty?
<input type="text" id="myMessage" name="shoutbox_msg" size="16" class="field_nosize" maxlength="150">
<input id="submit" type="submit" name="submit_post" class="button_nosize" value="Senden" onclick="sendMessage(); clearInput();">
$('#submit').click(function(){
if($('#myMessage').val() == ''){
alert('Input can not be left blank');
}
});
Update
If you don't want whitespace also u can remove them using jQuery.trim()
Description: Remove the whitespace from the beginning and end of a string.
$('#submit').click(function(){
if($.trim($('#myMessage').val()) == ''){
alert('Input can not be left blank');
}
});
Better one is here.
$('#submit').click(function()
{
if( !$('#myMessage').val() ) {
alert('warning');
}
});
And you don't necessarily need .length or see if its >0 since an empty string evaluates to false anyway but if you'd like to for readability purposes:
$('#submit').on('click',function()
{
if( $('#myMessage').val().length === 0 ) {
alert('warning');
}
});
If you're sure it will always operate on a textfield element then you can just use this.value.
$('#submit').click(function()
{
if( !document.getElementById('myMessage').value ) {
alert('warning');
}
});
Also you should take note that $('input:text') grabs multiple elements, specify a context or use the this keyword if you just want a reference to a lone element ( provided theres one textfield in the context's descendants/children ).
Also you can try this, if you want to focus on same text after error.
If you wants to show this error message in a paragraph then you can use this one:
$(document).ready(function () {
$("#submit").click(function () {
if($('#selBooks').val() === '') {
$("#Paragraph_id").text("Please select a book and then proceed.").show();
$('#selBooks').focus();
return false;
}
});
});
Check empty input with removing space(if user enter space) from input using trim
$(document).ready(function(){
$('#button').click(function(){
if($.trim($('#fname').val()) == '')
{
$('#fname').css("border-color", "red");
alert("Empty");
}
});
});
You could create a function that checks every input in an input class like below
function validateForm() {
var anyFieldIsEmpty = jQuery(".myclass").filter(function () {
return $.trim(this.value).length === 0;
}).length > 0
if (anyFieldIsEmpty) {
alert("Fill all the necessary fields");
var empty = $(".myclass").filter(function () {
return $.trim(this.value).length === 0;
})
empty.css("border", "1px solid red");
return false;
} else {
return true;
}
}
What this does is it checks every input in 'myclass' and if empty it gives alert and colour the border of the input and user will recognize which input is not filled.
Use this instead because just trying to check if the value is not equal to an empty string won't help if there are multiple spaces.
('#submit').onclick = function(){
let count = 0;
let notEmpty = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
for(let i=0; i < $('#myMessage').value.length; i ++){
for(let j = 0; j < notEmpty.length ; j++){
if($('#myMessage').value[i]== notEmpty[j]){
count += 1;
}
}
}
if(count==0){
alert("You cannot leave this blank");
}
}

How do I fix two bugs for my jQuery form Validation code?

My code basically adds a class error if field is invalid and if the field is valid, the error class is removed and form is submitted normally.
I am having trouble figuring out two small bugs for the form validation code I created.
Bugs listed below:
1) If you enter the correct content within one field, and click submit, the length of the error class does not update on first submit click. It takes two submit clicks for the length to update. (view console.log)
2) If you change the content of the input field and click submit (all works well, error class is removed) BUT if you decide to delete your updated text & leave the field blank, the error class does not get re-applied.
Would be great if I can get some assistance solving this.
Please let me know if anything is unclear.
Thanks in advance:
JSFIDDLE
$('form.requiredFields').submit(function(e) {
var req = $(this).find('.req'),
validateEmail = function(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
};
req.each(function() {
var $this = $(this),
defaultVal = $this.prop('defaultValue'); //cache default val
//checks for validation errors
if ( ( $this.hasClass('email') && !validateEmail( $this.val() ) ) ||
( defaultVal === $this.val() || $this.val() === '' || $this.val().length < 3 )
)
{
$this.addClass('error');
} else {
$this.removeClass('error req');
}
});
console.log(req.length);
if ( req.length === 0 ) {
return true;
} else {
return false;
}
});
Like dc5 said for #2 don't remove the req class.
And for #1 - You're looking for errors (.req) before it is removed.
See this working fiddle. It is an example how your code work but maybe you can find a cleaner solution.
$('form.requiredFields').submit(function(e) {
var req = $(this).find('.req'), errorCheck = 0,
validateEmail = function(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
};
req.each(function() {
var $this = $(this),
defaultVal = $this.prop('defaultValue'); //cache default val
//checks for validation errors
if ( ( $this.hasClass('email') && !validateEmail( $this.val() ) ) ||
( defaultVal === $this.val() || $this.val() === '' || $this.val().length < 3 )
)
{
$this.addClass('error');
} else {
$this.removeClass('error');
}
});
errorCheck = $(this).find('.error');
console.log(errorCheck.length);
if ( errorCheck.length === 0 ) {
return true;
} else {
return false;
}
});
for #2, You are moving the 'req' class as well as the 'error' class when clearing the error. The next time through the call, the input is no longer found through your selector $(this).find('.req')
For #1 - I don't understand the problem as you have described it.
I made it easier for you, actually your code is a mess,
here is a fiddle:
Jsfiddle validate Demo
CODE:
$('#submit_form').click(function() {
var flag = 0;
var count = 0,
total = $(".req").length;
var validateEmail = function(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
$('.req').each(function(){
count++;
if($(this).attr('id')=='email') {
if(!validateEmail($(this).val())){ $(this).addClass('error'); flag = 1; }
else { $(this).removeClass('error'); } }
if($(this).attr('id')=='name') {
if($(this).val().length < 3){ $(this).addClass('error'); flag = 1; }
else { $(this).removeClass('error'); } }
if($(this).attr('id')=='com') {
if($(this).val().length < 3&&$(this).val()!=''){ $(this).addClass('error'); flag = 1; }
else { $(this).removeClass('error'); } }
if ( total==count&&flag<1) { alert('submit'); }
});
});
Validation rules:
name - must be bigger then 2.
email - true on pattern match function.
comment - if typed, must be bigger the 2 chars (just to understand how can it be done).
If this example is not clear or you need more help don't hesitate... I'm bored.

Categories

Resources