I have fields in form which I add dynamically. How can I check if values of these fields unique?
HTML:
<div class="inputs">
<input type="text" class="form-control" id="regSection" name="regSection[]" required="required">
</div>
ADD
JavaScript:
$('#add').click(function(e) {
e.preventDefault();
$('<input type="text" class="form-control" id="regSection" name="regSection[]">').fadeIn('slow').appendTo('.inputs');
});
I've removed the id from the input as ID's must be unique.
This code will return found id the values in textbox repeat. Otherwise, it will return not found.
$('#add').click(function(e) {
e.preventDefault();
$('<input type="text" class="form-control" n ame="regSection[]">').appendTo('.inputs');
});
$('#check').click(function(e){
var arr = [];
var found = 0;
$('.inputs input').each(function(){
var myVal = $(this).val();
if(arr.includes(myVal))
found++;
else
arr.push(myVal);
});
if(found)
console.log('found');
else
console.log('unique');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inputs">
<input type="text" class="form-control" name="regSection[]" required="required">
</div>
ADD
<button id="check">Check</button>
Related
I have a multiple input rows and all rows have a total column at the end. Now, I want to put the total result of each rows in column Total. I tried but it returns NaN value instead of total result. Attached is my view & script please help what I am missing??? Thanks
$('body').on('change', '.bgpending, .registered', function() {
var el = $(this);
var totalRow = 0;
el.closest('.dosiaPlace').find('input').each(function() {
totalRow = totalRow + parseInt($(this).val());
});
el.closest('.dosiaPlace').find('.total-row').val(totalRow);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dosiaPlace">
<div class="col-md-2">
<label>#lang('dashboard.pastyear'):</label>
<input type="number" value="0" class="form-control bgpending" name="bgpending[]" />
</div>
<div class="col-md-2">
<label>#lang('dashboard.warida'):</label>
<input type="number" value="0" class="form-control registered" name="registered[]" />
</div>
<div class="col-md-2">
<label>#lang('dashboard.total'):</label>
<input type="text" class="form-control total-row" />
</div>
</div>
Result:
The container, the .dosiaPlace, I presume, has 3 inputs: the .bgpending, the .registered, and the .total-row. Your el.closest('.dosiaPlace').find('input') finds all 3 of those, including the .total-row. But the .total-row is empty (initially), so
totalRow = totalRow + parseInt($(this).val());
for it results in
totalRow = totalRow + parseInt('');
And the empty string can't be parseInt'd (results in NaN). (You also probably don't want to be including the .total-row anyway)
Use input:not(.total-row') instead of input:
$('body').on('change', '.bgpending, .registered', function() {
var el = $(this);
var totalRow = 0;
el.closest('body').find('input:not(.total-row)').each(function() {
totalRow = totalRow + parseInt($(this).val());
});
el.closest('body').find('.total-row').val(totalRow);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-2">
<label>#lang('dashboard.pastyear'):</label>
<input type="number" value="0" class="form-control bgpending" name="bgpending[]" />
</div>
<div class="col-md-2">
<label>#lang('dashboard.warida'):</label>
<input type="number" value="0" class="form-control registered" name="registered[]" />
</div>
<div class="col-md-2">
<label>#lang('dashboard.total'):</label>
<input type="text" class="form-control total-row" />
</div>
Your variable get null value or NaN just asign o if it is nan or empty
if(totalRow=='' || totalRow ==NaN )
{
totalRow=0;
}
I have 4 inputs on my page, and on a button onClick, i want to check, that all the inputs are filled with text.
<input type="text" value="" id="input1">
<input type="text" value="" id="input2">
<input type="text" value="" id="input3">
<input type="text" value="" id="input4">
What i want : Store all the required inputs ID in an array, and on click, check, that is there any input, that is empty.
How can i do this at the simplest way?
Use required tag instead as given below
<input type="text" value="" id="input1" required>
you can also try adding REGEX for more strict checking
// using Plain JavaScript
var input1= document.getElementById('input1').value;
if(input1 == "" ){
alert("Input 1 is Empty");
return false;
}
var input2 = document.getElementById('input2').value;
if(input12 == "" ){
alert("Input 2 is Empty");
return false;
}
var input3 = document.getElementById('input3').value;
if(input3 == "" ){
alert("Input 3 is Empty");
return false;
}
var input4 = document.getElementById('input4').value;
if(input4 == "" ){
alert("Input 4 is Empty");
return false;
}
just incase the required attribute fails.. you can do this..
add a validate function to the blur event, that is when the user leaves the field..
<input type="text" onblur="validate(this)" value="" id="input1">
<input type="text" onblur="validate(this)" value="" id="input2">
<input type="text" onblur="validate(this)" value="" id="input3">
<input type="text" onblur="validate(this)" value="" id="input4">
<button> ... </button>
and using jquery you can do this..
function validate(obj){
if($(obj).val() == ''){
alert('this Field cannot be empty');
$(obj).focus(); //send focus back to the object...
}
}
<input type="text" value="" id="input1">
<input type="text" value="" id="input2">
<input type="text" value="" id="input3">
<input type="text" value="" id="input4">
jQuery(function($){
var arr = [];
// number of input elements
var count = $("input").length;
// store list of input ids
$("buttonName").on('click', function(event) {
$("input").each(function(i){
var currId = $(this).attr('id');
arr.push(currId);
if ($(this).val()=="") {
alert(currId+": has no input");
}
});
});
});
Disabling jquery submit button until all the form inputs is filled.
Am working with Jquery and I have been trying to implement disabling form submission button until the whole form inputs are filled. i have tried most solution found here but it does not solve the issue. Thanks
$('.postbtn_video').click(function() {
var element = $(this);
var ID = element.attr('id');
var msg = $('#status').val();
var title = $('#title').val();
var video = $('#video').val();
var stat = $('#stat').val();
if (title == "") {
alert('Please Enter video Post Title?');
} else if (msg == "") {
alert('Please Enter Video Post Description');
} else if (video == "") {
alert('Enter Youtube Video Link');
} else if (stat == "") {
alert('Select Status');
} else {
var postData = "post=" + msg + "&title=" + title + "&video=" + video + "&stat=" + stat;
$("#loader").show();
$("#loader").fadeIn(400).html('<img src="loader.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
$.ajax({
type: "POST",
url: "posts.php",
data: postData,
cache: false,
success: function(html) {
$("ul#updatepost").prepend(html);
$("ul#updatepost li:first").slideDown("slow");
$('#status').val('');
$('#loader').hide();
}
});
}
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" name="statusform">
<label>Video Post Title </label>
<input type="text" name="title" id="title" class="form-control" placeholder="Enter Post Title">
<p></p>
<label>Video Post Description</label>
<textarea style="width:100%" name="status" class="status form-control" id="status" placeholder="Share what you like " title="What's on your mind?">
</textarea>
<label>Youtube Video Link</label>
<input style="width:100%" name="video" class="form-control" id="video" placeholder="Youtube Video Link">
<label>status</label>
<select style="width:100%" name="stat" class="form-control" id="stat">
<option value="ok">ok</option>
</select>
<p></p>
<input name="post" type="submit" value="Share Video Updates" class="postbtn_video" style="background:black;color:white; height:30px;float:left" />
</form>
Firstly apply disabled="disabled" to the button:
<input name="post" type="submit" value="Share Video Updates" class="postbtn_video" disabled="disabled" />
Secondly, you need a function which will check each field is empty or not!
Check below code:
$(document).ready(function(){
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if(!empty){ // this will only check next inputs if empty is false, but once its set to true no further check will be made
if ($(this).val() == '') {
empty = true;
}
}
});
if (empty) {
$('.postbtn_video').attr('disabled', 'disabled');
} else {
$('.postbtn_video').removeAttr('disabled');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" name="statusform">
<label>Video Post Title </label>
<input type="text" name="title" id="title" class="form-control" placeholder="Enter Post Title">
<p></p>
<label>Video Post Description</label>
<textarea style="width:100%" name="status" class="status form-control" id="status" placeholder="Share what you like " title="What's on your mind?"></textarea>
<label>Youtube Video Link</label>
<input style="width:100%" name="video" class="form-control" id="video" placeholder="Youtube Video Link">
<label>status</label>
<select style="width:100%" name="stat" class="form-control" id="stat">
<option value="ok">ok</option>
</select>
<p></p>
<input name="post" type="submit" value="Share Video Updates" class="postbtn_video" disabled="disabled" />
</form>
Maybe this will help. you can manipulated the Form Disabled attribute:
var checkboxes = document.getElementsByTagName('input');
//check all check all input elements to see if they are check-boxes
for (var i = 0; i < checkboxes.length; i++) {
//If the input is a check-box run script else skip over
if (checkboxes[i].type == 'checkbox') {
//If it is a check-box ensure the box is unchecked
checkboxes[i].checked = false;
}
}
$(document).ready(function()
{
//define Element by ID and create variable
var $checked = $('#field_human');
//define default state for attribute before handler function trigger
$("#submit").attr("disabled", !$checked.checked)
//On element handler trigger define function to execute each time handler is triggered
$checked.click(function()
{
//State to define instance on method
if ($checked.prop('checked'))
{
//return true
//remove element attribute state 'disabled'
$('#submit').removeAttr('disabled');
}
if($('#contactForm input').val() != '')
{
$('#submit').removeAttr('disabled');
}
else {
//return false
//set element attribute state 'disabled'
$("#submit").attr("disabled", !$checked.checked);
}
//return to ready-state to wait for handler to trigger again
return;
});
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<form class="form-horizontal" role="form" method="post" action="" id="contactForm" name="contactForm">
<div class="form-group">
<label for="inputblk" class="col-sm-3 control-label">Input Block</label>
<div class="col-sm-9">
<input name="inputblk" class="form-control" />
</div>
</div>
<div class="form-group">
<label for="human" class="col-sm-3 control-label">Are You <strong><u>Human</u>?</strong></label>
<div class="col-sm-9">
<input id="field_human" class="field_human" type="checkbox" name="human" />
</div>
</div>
<div class="form-group">
<div class="col-sm-9 col-sm-offset-3">
<button id="submit" name="submit" type="submit" class="btn btn-dark btn-block btn-lg">Send</button>
</div>
</div>
</form>
1st:
inputs that you think are required, make it required! like below:
<input style="width:100%" name="video" class="form-control" id="video" placeholder="Youtube Video Link" required >
2nd:
Make your selection based on this attribute and check if values of these inputs are not empty. Disable the submit button if so.
3rd:
Make event listener to all inputs that have required attribute to listen user inputs.
something like this:
var l = $("[required='']");
function enableSubmit(l) {
if (l.length == 0) {
$("[name=post]").removeAttr('disabled');
} else {
for (var m = 0; m < l.length; m++) {
if (l[m].value.length == 0) {
$("[name=post]").attr("disabled", "disabled");
return;
}
}
$("[name=post]").removeAttr('disabled');
}
}
for (var m = 0; m < l.length; m++) {
l[m].addEventListener('input', function () {
enableSubmit(l);
});
}
First of all you need to add a disabled property to you input button by default like:
<input disabled name="post" type="submit" value="Share Video Updates" class="postbtn_video" style="background:black;color:white; height:30px;float:left" />
then in your jquery you need fire up a validate function that will check for all the inputs and if they are not empty you can simply remove the disabled property from your input button like:
$(document).on('keyup', "input:not([type='submit']", function () {
//set it to true by default
var valid = true;
//getting all the inputs except input submit
var inputTextboxes = $("input:not([type='submit'])");
inputTextboxes.each(function(e) {
//it enters this only if the valid is true for any one value, if valid is set to false at any point it won't check it for next inputs - works for first time
if (valid != false){
if ($(this).val()) {
valid = true;
}else{
valid = false;
}
}
else{
break; //breaks the loop
}
});
if (valid) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
Hope this helps
jQuery(function() {
var currentCount = 0;
jQuery('#addMoreEmail').click(function() {
currentCount = cloning('#MoreEmailDetails', '#MoreEmails', currentCount);
return false;
});
function cloning(from, to, counter) {
var clone = $(from).clone();
//console.log(clone);
counter++;
// Replace the input attributes:
clone.find(':input').each(function() {
var name = jQuery(this).attr('name').replace(0, counter);
var id = jQuery(this).attr('id').replace(0, counter);
jQuery(this).attr({
'name': name,
'id': id
}).val();
});
// Replace the label for attribute:
clone.find('label').each(function() {
var newFor = jQuery(this).attr('for').replace(0, counter);
jQuery(this).attr('for', newFor);
});
// Replace the text between html tags:
clone = clone.html().replace(1, counter);
jQuery(to).before(clone);
return counter;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="MoreEmailDetails">
<div class="form-group users">
<input type="text" required="required" id="LeadEmailDetail0FirstName" value="" name="data[LeadEmailDetail][0][first_name]">
<label for="LeadEmailDetail0FirstName">First Name</label>
<input type="text" id="LeadEmailDetail0LastName" value="" name="data[LeadEmailDetail][0][last_name]">
<label for="LeadEmailDetail0FirstName">First Name</label>
<select id="LeadEmailDetail0CountryId" class="select-replace select2-offscreen" name="data[LeadEmailDetail][0][country_id]" tabindex="-1" title="Country">
<option value="">Choose a country</option>
<option value="2">SOUTHEASTERN EUROPE</option>
</select>
<label for="LeadEmailDetail0CountryId">Country</label>
<input type="checkbox" id="LeadEmailDetail0PrimaryEmail" value="1" name="data[LeadEmailDetail][0][primary_email]">
<label for="LeadEmailDetail0PrimaryEmail">Primary Email</label>
</div ">
</div">
<div id="MoreEmails"></div>
<input type="submit" value="Add More" id="addMoreEmail">
In above code input type text and checkbox working fine (adding dynamic fields after click add more) but i m getting below error in case select option
TypeError: jQuery(...).attr(...) is undefined
You need to add a null check for jQuery(this).attr('name')) . JSFIDDLE
Following is the modified JS code block.
clone.find(':input').each(function() {
if(jQuery(this).attr('name')) {
var name = jQuery(this).attr('name').replace(0, counter);
var id = jQuery(this).attr('id').replace(0, counter);
jQuery(this).attr({
'name': name,
'id': id
}).val(); }
});
<pre>
<script>
// here i want to check form validation
//if i use for loop txtbox2 is not exist in my form so i am getting Js error
//Don't write individual validation
//check element is exist or not if exist check for validation
//I need know how to check an element is exist or not
</script>
<form
<input type="text" id="txtbox1" name="txtbox1" />*
<input type="text" id="txtbox3" name="txtbox3" />*
<input type="text" id="txtbox4" name="txtbox4" />*
<input type="text" id="txtbox5" name="txtbox5" />*
<input type="text" id="txtbox15" name="txtbox15" />*
<input type="text" id="txtbox28" name="txtbox28" />*
</pre>
Apply a class to them:
<input type="text" id="txtbox1" name="txtbox1" class="txt" />
<input type="text" id="txtbox3" name="txtbox3" class="txt" />
<input type="text" id="txtbox4" name="txtbox4" class="txt" />
<input type="text" id="txtbox5" name="txtbox5" class="txt" />
<input type="text" id="txtbox15" name="txtbox15" class="txt" />
<input type="text" id="txtbox28" name="txtbox28" class="txt" />
and go about like this:
function validate(){
var elms = document.getElementsByTagName('input');
for (var i = 0; i < elms.length; i++){
if (elms[i].className === 'txt'){
if (elms[i].value === ''){
alert('Make sure to fill in all required fields');
// now focus it
elms[i].focus();
return false;
}
}
}
return true;
}
And then call the above function like this:
<form ............ onsubmit="return validate();">
Post your code.
Easiest way to validate is by using jquery validate plugin.(Why write your own code when somebody else has done the same?).
An example
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#feedbackform").validate();
});
</script>
<body>
<form id = "feedbackform" method = "POST" action = "">
<h3><span>Contact Us</span></h3>
<fieldset>
<legend>Contact form</legend>
<label for="id_name">Name *</label>
<input id="id_name" class="required" type="text" name="name" />
<label for="id_email">Email</label>
<input id="id_email" type="email" name="email" class="email"/>
<label for="id_comments">Message *</label>
<textarea id="id_comments" class="required" name="comments"></textarea>
<button type="submit">Send</button>
</fieldset>
</form>
The elements that you want to validate add class="required". I hope the example provided is self-explainatory
You can get a reference to the element and check if the reference is null or not:
for (var i=1; i<=100; i++) {
var elem = document.getElementById('txtbox' + i);
if (elem != null) {
...
}
}
Another approach is to look at the elements in the form, but then you need a way to access the form of course:
var elems = document.getElementById('IdOfTheForm').elements;
for (var i=0; i<elems.length; i++) {
var elem = elems[i];
if (elem.tagName == 'INPUT' && elem.type == 'text' && elem.id.length > 6 && elemt.id.substr(0,6) == 'txtbox') {
...
}
}