JavaScript - Looping through elements and checking for length - javascript

I have some code that goes through the elements that end in '_ro' as below:
document.querySelectorAll("[id$=_ro]").forEach(function(element) {
element.readOnly = true;
});
Is there a way I can check to see if there is an input, and if there is a value input, set it to read only?

Try element.nodeName == 'INPUT' to check the node name and element.value.length to check the value length:
document.querySelectorAll("[id$=_ro]").forEach(function(element) {
if(element.nodeName == 'INPUT' && element.value.length)
element.readOnly = true;
});
<input id="name_ro" type="text" value="Jhon"/>
<div id="div_ro">test</div>
<input id="phone_ro" type="text"/>

Related

Select multiple divs for on click function [duplicate]

Hi have a html code like this
<input type="text" value="quantita" id="quantita" name="quantita">
<input type="text" value="prodotto" id="prodotto" name="prodotto">
<input type="text" value="prezzo" id="prezzo" name="prezzo">
Now I'm trying to do a jquery code that add a button if the value of all these id is different from NULL
so I do this
var list = $("#prezzo", "#quantita", "#prodotto").val();
if (list!="")
{...do this...}
else
{....do nothing...}
but it doesn't work
You could do it like this instead
var list = $("#prezzo, #quantita, #prodotto").filter(function() {
return this.value === "";
}).length === 0;
if (list) { // All values set
assuming you meant the value is an empty string, as in no value set, and not actually the string NULL ?
$("#prezzo,#quantita,#prodotto").each(function()
{
if ($(this).val() !="" )
{}
else
{}
});

jQuery - How do I use AND with Selector?

My code's function is to alert user if the ptype textfield is empty.
$("input[name*='ptype']").each(function() {
if ($(this).val() == "") {
$(this).css({'background-color' : '#feffe3'});
e.preventDefault();
alert("Enter Value!");
}
});
However, I need to add another criteria where another field amount is not 0. So that the function get triggered when ptype="" && amount!=0. I'm very new in jQuery, and I'm not sure how to use AND operator in here. I've tried to do some based on other questions but it seems not working.
$("input[name*='ptype'][amount!='0']").each(function() {
$("input[name*='ptype'] , [amount!='0']").each(function() {
What am I missing ?
You can do it with && sign. Code depends on where your amount field is located and what it is. If I guess right it should be something like this:
$("input[name*='ptype']").each(function() {
if ($(this).val() == "" && $(this).parent().find(input[name='amount']).val() != 0) {
$(this).css({'background-color' : '#feffe3'});
e.preventDefault();
alert("Enter Value!");
}
});
That code $("input[name*='ptype'][amount!='0']").each(function() { is valid. You have to check the CSS selectors list.
The problem maybe in your *= selection. input[name*="ptype"] means Selects every element whose name attribute value contains the substring "ptype".
$('input[name*="ptype"][amount!="0"]').each(function() {
if ($(this).val() == "") {
$(this).css({'background-color' : '#feffe3'});
e.preventDefault();
alert("Enter Value!");
}
});
Take a look at this test https://jsfiddle.net/xpvt214o/211871/
« where another field» is the key in question.
So you need a selector to check if a selected element is empty and another element is not zero.
Holà!
Logic problem here.
with $(selector) you can look up for some elements.
There is no AND / OR in selectors for many sets of matching element.
A selector is ONE set of matching elements.
No way this selector can check for an attribute value of another set.
So you have to know your markup and navigate a bit... And take care of variable types.
$("input[name*='ptype']").each(function() {
if ( parseInt( $(this).next("input").val() ) != 0) {
$(this).css({"background-color" : "red"});
alert("Enter Value!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
ptype: <input type="text" name="ptype"><br>
amount: <input type="text" name="amount" value="1">
You have to look for another element's value here, from my understanding. So you have to know what is that "other" element and the methods to use may vary a lot depending on your HTML...
You can use this function in your button.
function check(e){
var verror = false;
$("input[name*='ptype']").each(function(index, value) {
var amount = $($("input[name='amount[]']").get(index)).val();
var ptype = $(this).val();
if(ptype.length <= 0 && amount.length > 0 ){
verror = true;
$(this).focus();
return false;
}
});
if(verror){
e.preventDefault();
alert("Enter Value!");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
ptype: <input type="text" name="ptype[]">
amount: <input type="text" name="amount[]" value="1"> <br>
ptype: <input type="text" name="ptype[]">
amount: <input type="text" name="amount[]" value="2"> <br>
<button type="button" onclick="check(event)">Click</button>
</form>

How to get the number of input tags containing certain text?

My goal is to flag when a user enters the same text into one input that matches at least one other input's text. To select all of the relevant inputs, I have this selector:
$('input:text[name="employerId"]')
but how do I select only those whose text = abc, for instance?
Here is my change() event that checks for duplicate text among all the inputs on the page. I guess I am looking for something like :contains but for text within an input.
var inputsToMonitorSelector = "input[type='text'][name='employerId']";
$(inputsToMonitorSelector).change(function() {
//console.log($(this).val());
var inputsToExamineSelector = inputsToMonitorSelector
+ ":contains('" + $(this).val() + "')";
console.log(inputsToExamineSelector);
if($(inputsToExamineSelector).length > 1) {
alert('dupe!');
}
});
Or is there no such selector? Must I somehow select all the inputsToMonitorSelector's and, in a function, examining each one's text, incrementing some local variable until it is greater than one?
With input you need to use [value="abc"] or .filter()
$(document).ready(function() {
var textInputSelector = 'input[type="text"][name="employerId"]';
$(textInputSelector).on('input', function() {
$(textInputSelector).css('background-color', '#fff');
var input = $(this).val();
var inputsWithInputValue = $(textInputSelector).filter(function() {
return this.value && input && this.value == input;
});
var foundDupe = $(inputsWithInputValue).length > 1;
if(foundDupe) {
console.log("Dupe found: " + input);
$(inputsWithInputValue).css('background-color', '#FFD4AA');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="employerId" value="abc">
<input type="text" name="employerId" value="">
<input type="text" name="employerId" value="">
<input type="text" name="employerId" value="">
[value="abc"] means if the value is abc
[value*="abc"] * means if the value contains abc
[value^="abc"] ^ means if the value starts with abc
[value$="abc"] $ means if the value ends with abc
Note: :contains() not for inputs , and word text not used with inputs and <select>.. inputs and <select> has a value
In your case .. instead of using
$(inputsToExamineSelector).length > 1)
You may need to use .filter()
$(inputsToExamineSelector).filter('[value*="abc"]').length > 1)
OR
$('input[type="text"][name="employerId"]').filter(function(){
return this.value.indexOf('abc') > -1
// for exact value use >> return this.value == 'abc'
}).length;
And to use a variable on it you can use it like
'[value*="'+ valueHere +'"]'
Something like this works. Attach isDuplicated(myInputs,this.value) to a keyup event listener attached to each input.
var myInputs = document.querySelectorAll("input[type='text']");
function isDuplicated(elements,str){
for (var i = 0; i < myInputs.length; i++) {
if(myInputs[i].value === str){
myInputs[i].setCustomValidity('Duplicate'); //set flag on input
} else {
myInputs[i].setCustomValidity(''); //remove flag
}
}
}
Here's another one. I started with vanilla js and was going for an answer like Ron Royston with document.querySelector(x) but ended up with jquery. A first attempt at several things but here you go:
$("input[type='text']").each(function(){
// add a change event to each text-element.
$(this).change(function() {
// on change, get the current value.
var currVal = $(this).val();
// loop all text-element-siblings and compare values.
$(this).siblings("input[type='text']").each(function() {
if( currVal.localeCompare( $(this).val() ) == 0 ) {
console.log("Match!");
}
else {
console.log("No match.");
}
});
});
});
https://jsfiddle.net/xxx8we6s/

Error when taking the length of an input

I want to use .length in this script, but when I add .length, the script fails.
The input:
<input type="text" name="myform" class="myform" placeholder="Full Name" value="" maxlength="20" minlength="6" pattern="[a-zA-Z-']+.{6,40}">
Original (working) code :
if ($.trim($("input[name=myform]").val()) === "") {
$("input[name=myform]").addClass("merror");
return false;
}
});
$("input").change(function() {
$(this).removeClass("merror");
}).trigger("change");
After adding .length:
if ($.trim($("input[name=myform]").length === 6)) {
$("input[name=myform]").addClass("merror");
return false;
}
$("input").change(function() {
$(this).removeClass("merror");
}).trigger("change");
You've misplaced a ) or two.
Adding some space to your if statement shows the problem:
if ($.trim(
$("input[name=myform]").length === 6)
) {
You need a closing ). But even then, you're taking the length of $("input[name=myform]") -- which is the list of inputs with the name "myform". It will certainly be 1.
You want to take the length of the value of that input (after trimming), like so:
if ($.trim( $("input[name=myform]").val() ).length === 6)
{

Check if all inputs are empty

I have multiple inputs on my page, when any them are filled, an "info div" appears on the side;
Now if all the inputs are manually cleared (on keyup), I need to hide that "info div".
How can I check (on keyup) that all of the inputs are empty at the same time?
Cheers
Loop through all the inputs, and if you get to a non-empty one you know they're not all empty. If you complete your loop without finding one, then they are all empty.
function isEveryInputEmpty() {
var allEmpty = true;
$(':input').each(function() {
if ($(this).val() !== '') {
allEmpty = false;
return false; // we've found a non-empty one, so stop iterating
}
});
return allEmpty;
}
You might want to 'trim' the input value before comparing (if you want to treat an input with just whitespace in it as empty). You also might want to be more specific about which inputs you're checking.
Simple solution (ES6) Without jQuery
html
<div class="container">
<input id="input1" />
<input id="input2" />
<input id="input3" />
</div>
JS
document.getElementById('btnCheckEmpty').addEventListener('click', () => {
if (isEveryInputEmpty())
alert('empty');
else
alert('not empty');
});
const isEveryInputEmpty = () => {
var inputs = document.querySelectorAll('.container input');
for (const input of inputs)
if (input.value !== '') return false;
return true;
}
Online Demo

Categories