How to check if same input is given using jQuery? - javascript

I've around 100 input fields with class name questionOrder. I have to check if user given any duplicate entry on the form input.
Currently trying something similar like this:
$('.questionOrder').on('input', function(){
var inp = this.value;
$('.questionOrder').each(function(){
if(inp==this.value){
console.log('match');
}else{
console.log('not match');
}
})
})
Problem here when inputting on a field it also checking it with itself

Try to remove this element from the selector with not() like:
$('.questionOrder').not(this).each(function(){
Working Code Example:
$('.questionOrder').on('input', function(){
var inp = this.value;
$('.questionOrder').not(this).each(function(){
if(inp==this.value){
console.log('match');
}else{
console.log('not match');
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="questionOrder" value="first"/>
<input type="text" class="questionOrder" value="second"/>
<input type="text" class="questionOrder" value="third"/>
<input type="text" class="questionOrder"/>

You can try siblings function -
$('.questionOrder').on('input', function(){
var inp = this.value;
$(this).siblings().each(function(){
if(inp==this.value){
console.log('match');
}else{
console.log('not match');
}
})
})

Alternative answer in pure DOM with event delegation ( without jQuery)
document.body.addEventListener('input', function(event) {
var target = event.target;
switch (true) {
case target.matches('.questionOrder'):
var questions = Array.from(document.querySelectorAll('.questionOrder'))
.forEach(function(q) {
if (q != target) {
if (target.value == q.value) console.log('match');
else console.log('not match');
}
})
return false;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="questionOrder" value="first" />
<input type="text" class="questionOrder" value="second" />
<input type="text" class="questionOrder" value="third" />
<input type="text" class="questionOrder" />

Related

How to shorten repetitive validation code

$('#add_product_form').on('submit',function(){
if ($('#product_date').val() == '') {
$('#product_date').addClass('border-danger');
}else{
$('#product_date').removeClass('border-danger');
}
if ($('#product_name').val() == '') {
$('#product_name').addClass('border-danger');
}else{
$('#product_name').removeClass('border-danger');
}
if ($('#select_category').val() == '') {
$('#select_category').addClass('border-danger');
}else{
$('#select_category').removeClass('border-danger');
}
if ($('#select_brand').val() == '') {
$('#select_brand').addClass('border-danger');
}else{
$('#select_brand').removeClass('border-danger');
}
if ($('#product_price').val() == '') {
$('#product_price').addClass('border-danger');
}else{
$('#product_price').removeClass('border-danger');
}
if ($('#product_quantity').val() == '') {
$('#product_quantity').addClass('border-danger');
}else{
$('#product_quantity').removeClass('border-danger');
}
})
This is one form with many fields. How can we shorten this code? I have tried same code in vanilla Javascript and obviously it contains more lines of code. Is there any better way to write this type of code?
It's best to make a function for repetitive things like this:
function validate($selector) {
$selector.toggleClass('border-danger', $selector.val() == '')
}
$('#add_product_form').on('submit',function(){
validate($('#product_date'));
validate($('#product_name'));
validate($('#select_category'));
validate($('#select_brand'));
validate($('#product_price'));
validate($('#product_quantity'));
});
You can use an each loop.
Adding a common class to the elements would simplify initial selector or use something like $(this).find(':input[required]').each...
$('#add_product_form').on('submit', function() {
$('#product_date,#product_name,#select_category,#select_brand,#product_price,#product_quantity').each(function() {
$(this).toggleClass('border-danger', !this.value);
});
});
Instead of having to maintain a list of fields in your JavaScript, use the required attribute and leverage this in your script. This also will leverage the browsers inbuilt validation. If you don't want to use the inbuilt validation you can use a different attribute as I've done below. If you want to use the normal required attribute, just use that instead of data-custRequired
$("#form").submit(function() {
var valid = true;
$(this).find("[data-custRequired]").each(function() {
var itemValid = true;
if (this.tagName === "FIELDSET") {
itemValid = $(this).find(":checked").length > 0;
}
//Otherwise validate normally
else {
itemValid = $(this).val() !== ""
}
$(this).toggleClass("danger-border", !itemValid );
if(!itemValid)
{
valid = false;
}
});
console.log("Form Valid = " + valid);
return false;
})
label {
display: block;
}
.danger-border {
border: red 1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form">
<label>First Name <input type="input" name="firstName" data-custRequired /></label>
<label>Last Name <input type="input" name="lastName" data-custRequired /></label>
<label>Comment <input type="input" name="comment"></label>
<fieldset data-custRequired>
<legend>Can we contact you - required</legend>
<label><input type="radio" name="contact"> Yes </label>
<label><input type="radio" name="contact">No </label>
<label><input type="radio" name="contact">Maybe </label>
</fieldset>
<input type="submit">
</form>
Vanilla Javascript
Not a whole lot more needed
document.getElementById("form").addEventListener("submit", function(event) {
var requiredElements = this.querySelectorAll("[data-custRequired]");
var valid = true;
for (var i = 0; i < requiredElements.length; i++) {
var itemValid = true;
var el = requiredElements[i];
if (el.tagName === "FIELDSET") {
itemValid = el.querySelectorAll(":checked").length > 0;
} else {
itemValid = el.value !== "";
}
//To support IE 10 we don't use the inbuilt toggle
if (itemValid) {
el.classList.remove("danger-border");
} else {
el.classList.add("danger-border");
valid = false;
}
}
console.log("Form Valid = " + valid);
event.preventDefault();
return false;
})
label {
display: block;
}
.danger-border {
border: red 1px solid;
}
<form id="form">
<label>First Name <input type="input" name="firstName" data-custRequired /></label>
<label>Last Name <input type="input" name="lastName" data-custRequired /></label>
<label>Comment <input type="input" name="comment"></label>
<fieldset data-custRequired>
<legend>Can we contact you - required</legend>
<label><input type="radio" name="contact"> Yes </label>
<label><input type="radio" name="contact">No </label>
<label><input type="radio" name="contact">Maybe </label>
</fieldset>
<input type="submit">
</form>

Disable form submit button if all input and textarea are empty except one

I need to enable a submit button only when each input fields has a value except one. The except one.
HTML:
// start of form
<input type='text /> // cant be blank
<input type='text /> // cant be blank
<input type='text /> // cant be blank
<textarea type='text /> // cant be blank
<button type='submit'>Submit</button>
// end of form
<input id='subscription-input' type='text /> // exclude this one only
[...]
JS:
function doCheck(){
var allFilled = true;
$('input[type=text]').not('#subscription-input').each(function(){
if($(this).val() == ''){
return false;
}
});
if (allFilled) {
// Apply active css and enable button
$('button[type=submit]').removeClass('form-submit--plain').addClass('form-submit--active');
$('button[type=submit]').prop('disabled', !allFilled);
}
}
$(document).ready(function(){
$('input[type=text]').keyup(doCheck).focusout(doCheck);
});
Basically I need a way to get the textarea field so I thought adding wilecard (*) would work:
$('*[type=text]').not('#subscription-input').each(function(){...}
How to get the input and textarea fields?
Apply the same class to all the fields and attach event to that class with a not for the ID:
function doCheck() {
var allFilled = true;
$('.form-fields:not(#subscription-input)').each(function() {
if ($(this).val() == '') {
allFilled = false;
}
});
$('button[type=submit]').prop('disabled', !allFilled);
if (allFilled) {
$('button[type=submit]').removeAttr('disabled');
}
}
$(document).ready(function() {
doCheck();
$('.form-fields').keyup(doCheck);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' class='form-fields' />
<input type='text' class='form-fields' />
<input type='text' class='form-fields' />
<textarea class='form-fields'></textarea>
<input id='subscription-input' class='form-fields' type='text' />
<button type='submit'>Submit</button>
change code to:
function doCheck(){
var allFilled = true;
$('input[type=text]:not(#subscription-input),textarea').each(function(){
if($(this).val() == ''){
allFilled=false;
}
});
if (allFilled) {
// Apply active css and enable button
$('button[type=submit]').removeClass('form-submit--plain').addClass('form-submit--active');
$('button[type=submit]').prop('disabled', !allFilled);
}
}
$(document).ready(function(){
$('input[type=text]').keyup(doCheck).focusout(doCheck);
});
Here you go with the solution https://jsfiddle.net/ehjxvz4j/1/
function doCheck(){
var allFilled = true;
$('input[type=text]').not('#subscription-input').each(function(){
if($(this).val() == ''){
allFilled = false;
}
});
if($('textarea').val() == ''){
allFilled = false;
}
if (allFilled) {
// Apply active css and enable button
$('button[type=submit]').removeClass('form-submit--plain').addClass('form-submit--active');
}
$('button[type=submit]').prop('disabled', !allFilled);
}
$(document).ready(function(){
$('input[type=text], textarea').focusout(doCheck);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' />
<input type='text' />
<input type='text' />
<textarea></textarea>
<button type='submit' disabled>Submit</button>
<input id='subscription-input' type='text'/>

making all input fields borders red when no one at least was filled in

I am not good enough with javascript. Simply I have a form with some input fields. The user has to fill in at least one of them. I had already found the right code to do this. This code tells the user there is an error using an alert message. But I want to make all input fields borders red instead of this alert message using the same code.
HTML
<form id="myform" action="" method="post">
<input name="destination" class="form-control" type="text" >
<input name="thingstodo" class="form-control" type="text">
<input name="gsearch" class="form-control" type="text">
<button type="submit" name="search">Search</button>
</form>
JavaScript
$(function(){
$("#myform").submit(function(){
var valid=0;
$(this).find('input[type=text]').each(function(){
if($(this).val() != "") valid+=1;
});
if(valid){
return true;
}
else {
alert("error: you must fill in at least one field");
return false;
}
});
});
Thanks
You can do it by setting the CSS style. This is done most easily with jQuery syntax.
$(function(){
$("#myform").submit(function(){
var valid = 0;
$(this).find('input[type=text]').each(function(){
if($(this).val() != "") {
valid++;
$(this).css("border-color", "initial");
}
else {
$(this).css("border-color", "red");
}
});
if (valid > 0) { return true; }
else { return false; }
});
});
Modify the code like so
$(function(){
$("#myform").submit(function(){
var valid=0;
$(this).find('input[type=text]').each(function(){
if($(this).val() != "") valid+=1;
else
$(this).style.border = "solid 1px red"
});
if(valid){
return true;
}
else {
return false;
}
});
});
How about this ?
$(function(){
$("#myform").submit(function(){
var dirty = false;
$('input[type=text]').each(function(){
if($(this).val().length){
dirty = true;
}
});
if(!dirty){
$('input[type=text]').each(function(){
$(this).css('border','1px solid red');
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" action="" method="post">
<input name="destination" class="form-control" type="text" >
<input name="thingstodo" class="form-control" type="text">
<input name="gsearch" class="form-control" type="text">
<button type="submit" name="search">Search</button>
</form>

Disable submit button until all form inputs have data

I'm trying to disable the submit button until all inputs have some data. Right now the button is disabled, but it stays disabled after all inputs are filled in. What am I doing wrong?
$(document).ready(function (){
validate();
$('input').on('keyup', validate);
});
function validate(){
if ($('input').val().length > 0) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
Here's a modification of your code that checks all the <input> fields, instead of just the first one.
$(document).ready(function() {
validate();
$('input').on('keyup', validate);
});
function validate() {
var inputsWithValues = 0;
// get all input fields except for type='submit'
var myInputs = $("input:not([type='submit'])");
myInputs.each(function(e) {
// if it has a value, increment the counter
if ($(this).val()) {
inputsWithValues += 1;
}
});
if (inputsWithValues == myInputs.length) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
<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="submit" value="Join">
Vanilla JS Solution.
In question selected JavaScript tag.
HTML Form:
<form action="/signup">
<div>
<label for="username">User Name</label>
<input type="text" name="username" required/>
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" />
</div>
<div>
<label for="r_password">Retype Password</label>
<input type="password" name="r_password" />
</div>
<div>
<label for="email">Email</label>
<input type="text" name="email" />
</div>
<input type="submit" value="Signup" disabled="disabled" />
</form>
JavaScript:
var form = document.querySelector('form')
var inputs = document.querySelectorAll('input')
var required_inputs = document.querySelectorAll('input[required]')
var register = document.querySelector('input[type="submit"]')
form.addEventListener('keyup', function(e) {
var disabled = false
inputs.forEach(function(input, index) {
if (input.value === '' || !input.value.replace(/\s/g, '').length) {
disabled = true
}
})
if (disabled) {
register.setAttribute('disabled', 'disabled')
} else {
register.removeAttribute('disabled')
}
})
Some explanation:
In this code we add keyup event on html form and on every keypress check all input fields. If at least one input field we have are empty or contains only space characters then we assign the true value to disabled variable and disable submit button.
If you need to disable submit button until all required input fields are filled in - replace:
inputs.forEach(function(input, index) {
with:
required_inputs.forEach(function(input, index) {
where required_inputs is already declared array containing only required input fields.
JSFiddle Demo: https://jsfiddle.net/ydo7L3m7/
You could try using jQuery Validate
http://jqueryvalidation.org/
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
And then do something like the following:
$('#YourFormName').validate({
rules: {
InputName1: {
required: true
},
InputName2: { //etc..
required: true
}
}
});
Refer to the sample here.
In this only input of type="text" has been considered as described in your question.
HTML:
<div>
<form>
<div>
<label>
Name:
<input type="text" name="name">
</label>
</div>
<br>
<div>
<label>
Age:
<input type="text" name="age">
</label>
</div>
<br>
<div>
<input type="submit" value="Submit">
</div>
</form>
</div>
JS:
$(document).ready(function () {
validate();
$('input').on('keyup check', validate);
});
function validate() {
var input = $('input');
var isValid = false;
$.each(input, function (k, v) {
if (v.type != "submit") {
isValid = (k == 0) ?
v.value ? true : false : isValid && v.value ? true : false;
}
if (isValid) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
});
}
Try to modify your function like this :
function validate(){
if ($('input').val() != '') {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
and place some event trigger or something like onkeyup in jquery.But for plain js, it looks like this :
<input type = "text" name = "test" id = "test" onkeyup = "validate();">
Not so sure of this but it might help.
Here is a dynamic code that check all inputs to have data when wants to submit it:
$("form").submit(function(e) {
var error = 0;
$('input').removeClass('error');
$('.require').each(function(index) {
if ($(this).val() == '' || $(this).val() == ' ') {
$(this).addClass('error');
error++;
}
});
if (error > 0) {
//Means if has error:
e.preventDefault();
return false;
} else {
return true;
}
});
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form>
<form action="google.com">
<input type="text" placeholder="This is input #1" class="require" />
<input type="text" placeholder="This is input #2" class="require" />
<input type="submit" value="submit" />
</form>
</form>
Now you see there is a class called require, you just need to give this class to inputs that have to have value then this function will check if that input has value or not, and if those required inputs are empty Jquery will prevent to submit the form!
Modify your code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="submit" value="Join">
<script>
$(document).ready(function (){
validate();
$('input').on('keyup', validate);
});
function validate(){
$("input[type=text]").each(function(){
if($(this).val().length > 0)
{
$("input[type=submit]").prop("disabled", false);
}
else
{
$("input[type=submit]").prop("disabled", true);
}
});
}
</script>
function disabledBtn(_className,_btnName) {
var inputsWithValues = 0;
var _f = document.getElementsByClassName(_className);
for(var i=0; i < _f.length; i++) {
if (_f[i].value) {
inputsWithValues += 1;
}
}
if (inputsWithValues == _f.length) {
document.getElementsByName(_btnName)[0].disabled = false;
} else {
document.getElementsByName(_btnName)[0].disabled = true;
}
}
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="submit" value="Join" id="yyyyy" disabled name="fruit">

JQuery - filter labels that start with typed in text

i have this list of cities(checkbox and label) and an input field:
<input class="search-filter" type="text"/>
<form autocomplete="off" id="city-search-form" name="city-search-form" action="" method="">
<div id="list" class="multiselect">
<input id="city-id-1" class="css-checkbox" type="checkbox" />
<label for="city-id-1" name="" class="css-label">abc</label>
<input id="city-id-2" class="css-checkbox" type="checkbox" />
<label for="city-id-2" name="" class="css-label">bce</label>
<input id="city-id-3" class="css-checkbox" type="checkbox" />
<label for="city-id-3" name="" class="css-label">cde</label>
<input id="city-id-4" class="css-checkbox" type="checkbox" />
<label for="city-id-4" name="" class="css-label">rgp</label>
</div>
</form>
i am using this jquery code to filter the checkboxes + labels by the words i type in, but the code is not working. How can i filter and show only the labels that start with typed words.
function listFilter(list) {
var input = $('.search-filter');
$(input)
.change( function () {
var filter = input.val();
$('.css-label').filter(function(filter) {
if($('.css-label').text().search(filter) == 0){
.....hide();
}
else {
.......show();
}
});
})
.keyup(function () {
input.change();
.....
}
});
}
$(function () {
listFilter($("#list"));
});
}($));
Try
function listFilter(list, input) {
var $lbs = list.find('.css-label');
function filter(){
var regex = new RegExp('\\b' + this.value);
var $els = $lbs.filter(function(){
return regex.test($(this).text());
});
$lbs.not($els).hide().prev().hide();
$els.show().prev().show();
};
input.keyup(filter).change(filter)
}
jQuery(function($){
listFilter($('#list'), $('.search-filter'))
})
Demo: Fiddle
You can use :contains() selector for filtering:
var input = $('.search-filter');
input.change( function () {
var filter = input.val();
if(filter.length == 0) { // show all if filter is empty
$('.css-label').each(function() {
$(this).show();
$(this).prev().show();
});
return;
}
// hide all labels with checkboxes
$('.css-label').each(function() {
$(this).hide();
$(this).prev().hide();
});
// show only matched
$('.css-label:contains("'+filter+'")').each(function() {
$(this).show();
$(this).prev().show();
});
}).keyup(function() {
$(this).change();
});
jsfiddle
Too late to be accepted as correct but here is an attempt that I was working on before my job got in the way. Thought I may as well post it.
It is case insensitive and supports multiple words (thanks to Arun P Johny for that).
demo
$('.search-filter').keyup(function (e) {
var text = $(this).val();
var $elems = $('.css-label, .css-checkbox');
if (text.length < 1) {
$elems.show();
}
else{
$elems.hide();
var sel = $('label').filter(function () {
return $(this).text().match("\\b", "i" + text)
}).attr('for');
$('#'+sel + ',[for=' + sel + ']').show();
}
});
i have a code below to get the label name
<!DOCTYPE html>
<html>
<head>
<SCRIPT src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</SCRIPT>
<SCRIPT>
$(document).ready(function(){
alert($(".css-label").text());
});
</SCRIPT>
</head>
<body>
<div id="list" class="multiselect">
<input id="city-id-1" class="css-checkbox" type="checkbox" />
<label for="city-id-1" name="" class="css-label">abc</label>
</div>
</body>
</html>
hope this will help you

Categories