Find empty input elements inside a collection - jQuery - javascript

I am trying to find the empty input types like textbox, select and li elements inside a jQuery resultset.
My resultset is (requiredfields) -
$requiredFields = $(".f-form-required.f-form-field").filter(function(){
if($(':input:not([type="hidden"])'))
return $(this);
});
And on that resultset I want to query for empty inputs like textbox, select and li elements. But it seems I am doing something wrong. Can someone suggest me how to do that.
Currently I am doing this to get empty textboxes but not working -
var emptyInputs = 0;
$requiredFields.filter(function(){
$('input[type=text]').each(function(){
if (this.val == "") {
emptyInputs = emptyInputs + 1;
}
});
});
I am trying to do same for finding out empty dropdown/select elements and list / li elements over $requiredFields collection.

There is no val property. Try using .val() instead or this.value:
var emptyInputs = 0;
$requiredFields.filter(function(){
$('input[type=text]').each(function(){
if (jQuery(this).val() == "") {
emptyInputs = emptyInputs + 1;
}
});
});
or:
var emptyInputs = 0;
$requiredFields.filter(function(){
$('input[type=text]').each(function(){
if (this.value == "") {
emptyInputs = emptyInputs + 1;
}
});
});

I think you arn't using .filter() quite as it is expected to be used. Consider something like this:
<html>
<body>
<div>
<input type="text" id="text1" class="f-form-required f-form-field" />
<input type="text" id="text2" class="f-form-required f-form-field" value="test" />
<input type="text" id="text3" class="f-form-required f-form-field" />
</div>
</body>
</html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function test(){
var $requiredFields = $('.f-form-required.f-form-field');
var $errorFields = $requiredFields.filter(function () {
var $this = $(this);
return $this.is('input') && $this.val() === '';
});
var errorCount = $errorFields.length;
console.log('errors:' + errorCount);
}
$(document).ready(function(){
test();
}
</script>

Related

prevent users from entering duplicate entries in text inputs in javascript

I have a DOM in which I want to prevent users from entering duplicate entries in html text input.
The above DOM is not in user's control. It is coming through php.
At this moment, I am focussing only on name="code[]".
This is what I have tried:
$(function(){
$('input[name^="code"]').change(function() {
var $current = $(this);
$('input[name^="code"]').each(function() {
if ($(this).val() == $current.val())
{
alert('Duplicate code Found!');
}
});
});
});
Problem Statement:
I am wondering what changes I should make in javascript code above so that when a duplicate code is entered, alert message "Duplicate code Found" should come up.
you need to add an eventlistener to each item, not an eventlistener for all. Then count inputs with same value, if there's more than 1, it's a duplicate.
Also ignore not-filled inputs.
Check following snippet:
$('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');
});
$('#createInput').on('click', function(){
let newInput = document.createElement("input");
newInput.name = 'code[]';
newInput.type = 'text';
newInput.className = 'whatever';
$('#inputGroup').append(newInput);
// repeat the eventlistener again:
$('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');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="inputGroup">
<input name="code-1" type="text" class="whatever">
<input name="code-2" type="text" class="whatever2">
<input name="code-3" type="text" class="whatever3">
</div>
<input type="button" id="createInput" value="Add input">
Edit:
now works with dynamically created elements. The class 'e' works as flag to not insert 2 event listeners to the same node element, otherwise they will run in cascade, provoking unwanted behaviour.
You can use something like this, that converts the jQuery object to an Array to map the values and find duplicates. I added an option to add a style to the duplicated inputs, so the user knows which ones are duplicated.
function checkDuplicates(){
var codes = $('input[name^="code"]').toArray().map(function(element){
return element.value;
})
var duplicates = codes.some(function(element, index, self){
return element && codes.indexOf(element) !== index;
});
return duplicates;
}
function flagDuplicates(){
var inputs = $('input[name^="code"]').toArray();
var codes = inputs.map(function(element){
return element.value;
});
var duplicates = 0;
codes.forEach(function(element, index){
var duplicate = element && codes.indexOf(element) !== index;
if(duplicate){
inputs[index].style.backgroundColor = "red";
inputs[codes.indexOf(element)].style.backgroundColor = "red";
duplicates++
}
});
return duplicates;
}
$('input[name^="code"]').on("change", function(){
//var duplicates = checkDuplicates(); // use this if you only need to show if there are duplicates, but not highlight which ones
var duplicates = flagDuplicates(); // use this to flag duplicates
if(duplicates){
alert(duplicates+" duplicate code(s)");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="code-1" type="text">
<input name="code-2" type="text">
<input name="code-3" type="text">

I want to disable the button if specific text has been found in any label

I want to disable the button if specific text has been found in any label.
The following code doesn't run because aTags[i].innerText is not equal to searchText all the time which is wrong because the label has inner text = "a" and the searchText variable have "a" as text - I need it to run in IE
<html>
<script language="javascript">
$(document).ready(function () {
var aTags = document.getElementsByTagName("label");
var searchText = "a";
var found;
for (var i = 0; i < aTags.length; i++) {
if (aTags[i].innerText == searchText) {
document.getElementById('choose').disabled=true;
break;
}
else
{
alert("failed")
}
}
});
</script>
<label> a </label> <br/>
<label> b </label> <br/>
<label> c </label> <br/>
<input type='button' value='choose' id='choose' />
</html>
Seems like there should be easier ways to do that with jQuery
$(function () {
var searchText = "a";
$('#choose').prop('disabled', function() {
return $('label').filter(function(_,el) {
return $.trim( $(el).text() ) === searchText;
}).length > 0;
});
});
FIDDLE
The issue is that your label contains " a " (with the spaces), but you're comparing with "a" (no spaces).
If you want to ignore the spaces, you can use jQuery's $.trim(...) to trim the text off the innerText.
But as you're using jQuery, you can dramatically reduce that code:
$(document).ready(function() {
var searchText = "a";
var found = false;
$("label").each(function() {
found = $.trim($(this).text()) === searchText;
if (found) {
return false; // No need to keep looking
}
});
$("#choose").prop("disabled", true);
});
Since you're already using jQuery, you can do what you like with much less complexity.
This will work:
(function ($) {
var searchText = "a";
$('label').each(function(){
if ($.trim($(this).text()) === searchText) {
$('#choose').prop('disabled', true);
}
});
})(jQuery);
You have to trim label's text. Try with:
if (aTags[i].innerText.trim() == searchText)
or without trim method:
if (aTags[i].innerText.replace(/^\s+|\s+$/g, '') == searchText)
If you want to match if a substring exists you can try with
aTags[i].innerText.indexOf(searchText) > -1
instead of
aTags[i].innerText == searchText

JQuery Validated Form Not Submitting

I have a form that I am using on my site and it is validated with some simple JQuery validation. Problem is it's not submitting or doing anything really when I change the values. Here is my code:
<form id="radForm" method="post" action="events.php?type=rad">
<div class="searchBoxLeft searchBoxRad"></div>
<div class="searchBoxMiddle">
<input id="radSearch" type="text" class="searchBoxInput searchBoxShort" value="<?php echo $yourradius; ?>" />
<label class="searchBoxLabel">Mile Radius of Your Address</label>
</div>
<div id="radButton" class="searchBoxRight"></div>
<div class="clearLeft"></div>
</form>
<script>
$(document).ready(function()
{
var radsearchok = 0;
//Rad search
$('#radSearch').blur(function()
{
var radsearch=$("#radSearch").val();
if(radsearch < 2){
$('#radSearch').addClass("searchError");
radsearchok = 0;
}
else if(radsearch > 50){
$('#radSearch').addClass("searchError");
radsearchok = 0;
}
else{
$('#radSearch').addClass("searchSuccess");
radsearchok = 1;
}
});
// Submit button action
$('#radButton').click(function()
{
if(radsearchok == 1)
{
$("#radForm").submit();
}
else
{
$('#radSearch').addClass("searchError");
}
return false;
});
//End
});
</script>
Can anyone see what is wrong with this?
You need to go back and set the .val() property again of your form, otherwise it will take the original value of .val() not radsearch;
Not sure if you actually want to update .val() though or just attach a property. Some options:
Right before the closing brace of .blur --> }); add"
$("#radSearch").val(radsearch);
Or:
Add a hidden input to your form with a new ID like:
<input type='hidden' name='radsearchHidden' />
and then do the same before the end of .blur:
$("#radsearchHidden").val(radsearch);
I made some changes to your code (http://jsfiddle.net/zdeZ2/2/) which I'll describe below:
<div id="radButton" class="searchBoxRight"></div> I assume you have something in there=> <input id="radButton" class="searchBoxRight" type="button" value="rad button">
I rewrote your validator with blur as follows. As suggested it coroses the radSearch value to an integer before comparisions The changes remove the searchError and searchSuccess classes before validating. I also made some optimizations for you.
//Rad search
$('#radSearch').blur(function () {
//remove classes from previous validating
var $this = $(this).removeClass("searchError").removeClass("searchSuccess");
var radsearch = $this.val() | 0; //radsearch is an integer
if (radsearch < 2 || radsearch > 50) {
$this.addClass("searchError");
radsearchok = 0;
} else {
$this.addClass("searchSuccess");
radsearchok = 1;
}
});
Can be equivalently written as:
//Rad search
$('#radSearch').blur(function () {
var $this = $(this);
var radsearch = $("#radSearch").val() | 0; //radsearch is an integer
var valid = radsearch < 2 || radsearch > 50;
$this.toggleClass("searchError", !valid)
.toggleClass("searchSuccess", valid);
radsearchchok = valid ? 1 : 0;
});

jQuery, same function for multiple ids

i want to clear specified input if the value is not number. function works for one ID, but i want it to work for multiple. of course i can write function multiple times but i dont want to do that.
the following code gets effect only for input with id "d". i dont know how to identify other ids. can anyone help?
<input id="d" />
<input id="d2" />
<input id="d3" />
<script type="text/javascript">
$('#d,d2,d3').keyup(function(){
if($('#d,d2,d3').val() != "") {
var value = $('#d,d2,d3').val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var intRegex = /^\d+$/;
if(intRegex.test(value)) {}
else {
$(this).val('');
}
}
});
</script>
Instead of $('#d,d2,d3') use $('#d, #d2, #d3') and for the if statement use $(this).val()
You can use starts with selector instead of putting in multiple ids like this:
$('[id^=d]')
Above selector will work for all elements whose ids start with d eg d1, d2, d3 and so on.
Here is how your code should be (fixing other errors as well):
$('[id^=d]').keyup(function(){
if(this.value != "") {
var value = this.value.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var intRegex = /^\d+$/;
if(intRegex.test(value)) {}
else {
this.value = '';
}
}
});
$('input[id^=d]').keyup(function() {
var val = $.trim( this.value ); // or $.trim( $(this).val() )
if (val != "") {
var value = val.replace(/^\s\s*/, '').replace(/\s\s*$/, ''),
intRegex = /^\d+$/;
if (intRegex.test(value)) {
// do something
} else {
$(this).val('');
}
}
});​
[id^=d] is a start with selector that means, id start with d.
Read about jQuery start selector
You forgot the # for d2 & d3. And also a this.
$('#d,#d2,#d3').keyup(function(){
if($(this).val() != "") {
var value = $(this).val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var intRegex = /^\d+$/;
if(intRegex.test(value)) {}
else {
$(this).val('');
}
}
});
You forgot the hash for the other two Ids:
$('#d,#d2,#d3')
see also
jQuery Multiple ID selectors
You can add class attribute
<input id="d" class="A"/>
<input id="d2" class="A"/>
<input id="d3" class="A"/>
use following selector by class name
$('.A').keyup

If input box contains certain number of characters

<input type="text"/> <button>Go</button>
<div id="example">
</div>
How can I .append "Blah" in #example if input contains 5 characters when button is clicked, and .append "Other" if it doesn't?
var example = $('#example'); //get example div
var input = $('input').get(0); //get first input in the set of inputs
$('button').click(function(){ //bind click handlers to (any) button
var value = input.value; //get the (first) input's value
if(value.length === 5){ //check the value
example.append('Blah');
} else {
example.append('Other');
}
});
$('button').click(function() {
var $example = $('#example');
if ($('input').val().length == 5) {
$example.append('Blah');
} else {
$example.append('Other');
}
});
http://jsfiddle.net/zerkms/cks45/
$(function(){
$('button').click(function(){
if($('input').val().length == 5){
$('#example').append('blah');
}else{
$('#example').append('Other');
}
});
});
Pure JS way
var butt = document.getElementsByTagName("button")[0],
input = document.getElementsByTagName("input")[0],
example = document.getElementById("example");
butt.onclick = function(){
if(input.value.length == 5){
example.textContent += "blah";
}else{
example.textContent += "other";
}
}
​
Live Demo
​
$('button').on('click',function() {
$('#example').text(
$('#example').text() +
($('input[type=text]').val().length==5?'Blah':'Other')
);
} );
If you didn't want to use jquery you could do...
HTML
<input id="input1" type="text"/> <button onclick="go('input1')">Go</button>
<div id="example">
</div>
JavaScript
function go(inputId){
document.getElementById("example").innerHTML += document.getElementById(inputId).value.length === 5 ? "bla" : "other";
}
This involved changing the HTML to include an id for the input and an onclick event handler for the button.

Categories

Resources