Check if all inputs of class have value [duplicate] - javascript

This question already has answers here:
Selecting empty text input using jQuery
(10 answers)
Closed 3 years ago.
I have a class .address added to a couple of my inputs. Basically, I want to check if all of them have been filled out. I know this is possible by iterating over the class like this:
var valueForAll = true;
$('.address').each(function (i, obj) {
if ($(this).val() == "") {
valueForAll = false;
}
});
if (valueForAll == true) {
// Do something
}
else {
// Do something else
}
I don't think this is an ideal solution though. So I found the :empty selector. Which works like this:
$("input:empty").length == 0;
However, doing this for my class always shows a length of 6. I don't know why.
$(".address:empty").length == 0;
Edit:
This is not a duplicate question as this one attached from #chrispbacon. This question focuses on how to check if all inputs of a class have been filled, not all elements inside a div. I cannot find any thread on Stack Overflow that focuses on how to check if all inputs have a value of a class without iterating over the class.

https://developer.mozilla.org/en-US/docs/Web/CSS/:empty
:empty
Is used to find elements that have no children. Not for inputs that do not have a value.
https://developer.mozilla.org/en-US/docs/Web/CSS/:blank
:blank
Is an up and coming pseudoselector for empty inputs, but coverage is still being added for browsers.

Related

Javascript get all input elements that contain values [duplicate]

This question already has answers here:
Select inputs that doesn't have value attribute with querySelector
(2 answers)
querySelectorAll detecting value in input
(2 answers)
Closed 3 years ago.
I'm using the querySelectorAll() JS function to retrieve all elements under a datagrid table (aspx page) , that datagrid contains several checkboxes / textboxes , there's a save button which should only be enabled when the following rule is satisfied :
At least 1 checkbox needs to be checked OR at least one textbox needs to contain text ( not empty )
Is there a way to check if any of the textbox input elements returned by querySelectorAll() , has a value ?
function validate() {
var search = document.getElementById("myGrdID").children;
//var hasAnyText = search[0].querySelectorAll("input:valid");
var hasAnyChecked = search[0].querySelectorAll("input:checked");
console.log("Any check? " + hasAnyChecked.length);
}
i'd like to avoid using Jquery , already managed to get all the checked input elements , couldn't find a way yet to find all the textboxes with values (any value not a specific string).
Are you able to use the filter function ?
var results = hasAnyChecked.filter(input => input.value != null)
Edit : comment below me has a point, but if you use those kind of selectors you won't be able to check multiple scenarios :
var results = hasAnyChecked.filter(input => input.value !== null || input.value !== false) // Handles both text inputs and checkboxes

Why is my Javascript not detecting the element I need? [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 4 years ago.
I'm having issues with my javascript in that it doesnt seem to be able to find the elements necessary. The second function with the onload works fine and wont let the form submit without certain fields filled out but the first function seems stuck. Is it not waiting for the DOM to load correctly? Also why cant I put everything under the first function since it waits for the DOM as expected and can find the elements necessary? I'm only using vanilla Javascript. No Jquery yet.
// my-script.js
document.addEventListener("DOMContentLoaded", function(event) {
// this function runs when the DOM is ready, i.e. when the document has been parsed
document.getElementsByClassName(".required").style.backgroundColor="blue";
});
window.onload=function(){
document.getElementById("mainForm").onsubmit = function(e){
var pass = document.querySelector("form textarea").value;
var inputField = document.querySelector(".rectangle > input");
if (inputField.type=="checkbox"){
if (!inputField.checked){
e.preventDefault();
alert("Check the license box")
}
}
if(pass=="" || pass == null){
e.preventDefault();
alert("Enter a description");
}
}
}
When giving a class name to getElementsByClassName() you don't need to use the ..
So the correct line would be:
document.getElementsByClassName("required").style.backgroundColor="blue";
If you are using the '.required' class multiple times you could do something like the following:
var x = document.getElementsByClassName("required");
x[0].style.backgroundColor="blue";
That will style the first element given the required class.
If you want to change the background colour of all the elements that have the required class you can do this by the following:
var x = document.getElementsByClassName("required");
for (i = 0; i < x.length; i++) {
x[i].style.backgroundColor = "blue";
}

JavaScript - cloneNode gives different result [duplicate]

This question already has answers here:
Javascript clone node is not copying all values from cloned to new object
(3 answers)
Closed 5 years ago.
I am trying to clone the form before submition in JavaScript using cloneNode. The original form has an answer for a selected value but not the cloned one. Following is the code.
encodeHTMLCollectionToBase64(document.forms['formen']).submit();
function encodeHTMLCollectionToBase64(form) {
encryptedForm = form.cloneNode(true)
Array.from(encryptedForm).forEach(function(item) {
if (item.childElementCount > 0) {
for(var i=0;i < item.childElementCount;i++) {
item[i].value = btoa(encodeURIComponent(item[i].value));
}
}
else {
item.value = btoa(encodeURIComponent(item.value));
}
});
encryptedForm.style.visibility = 'hidden';
document.body.appendChild(encryptedForm);
return encryptedForm ;
}
Upon inspection I found that the encryptedForm (cloned form) has empty value for one select element but it is there in form (original form). Why is that?
Am i doing something wrong here?
The form's selections are saved in the browser, not in the form's DOM elements, so when you clone it, the selections will not be copied over. It's possible to copy the selections over if you use JavaScript to manage the 'selected' prop on all of your form elements, or you could store the selections in a separate variable and reapply them later.

How to append javascript varible without using jQuery? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I've simple javascript function mentioned below:
<script>
function getValue(val)
{
document.getElementById('answer').value = val;
}
</script>
This function get's called on click of span and returned value gets displayed in input text.
I've three questions:
1] On click of span, if I want to append current value of varible 'val' with previous value; and return appended value to calling function. can you please suggest, how to achieve same without using jQuery?
2] There is one span which is suppose to work like Backspace. So click of span, i want to remove last character from document.getElementById('answer').value [This also without using jQuery]
3] There is one span which is suppose to work like Navigation keys [Right & Left]. So click of span [Let's say right], i want to move cursor position of the input text one character right and similarly for Left [This also without using jQuery]
Can you please suggest some pointers to achieve this?
For your question 1 I think you can do below. Code not tested
function getValue(val)
{
var currentVal = document.getElementById('answer').value
if(currentVal.length > 0 )
currentVal = parseInt(currentVal);
document.getElementById('answer').value = currentVal + val;
}
For question 2 :
Get the value and then do string operation to remove the last char. Its easy little google search for the string operations
For question 3 :
you can use event oncontextmenu for right click. Example below.
How can I capture the right-click event in JavaScript?
For moving cursor check below
Set keyboard caret position in html textbox
+= oprator appends string to existing string(not applicable in this case).
use return keyword to return updated value.
for removing last character use substring.
so try:
function getValue(val)
{
var currentText = document.getElementById('answer').value;
var updatedText = currentText.substring(0,currentText.length-2) + val;
document.getElementById('answer').value = updatedText;
return updatedText;
}

how to select a particular tag from seletected array of tags using Jquery [duplicate]

This question already has answers here:
Selecting the first "n" items with jQuery
(6 answers)
Closed 9 years ago.
I am selecting all tags where href attribute is starting with "picThumbImgA_" as below.
$('a[id^="picThumbImgA_"])')
now i want to update some attributes of first four tag. I can select first as
$('a[id^="picThumbImgA_"]):first')
and last as $('a[id^="picThumbImgA_"]):last')
odd as $('a[id^="picThumbImgA_"]):odd')
and even as $('a[id^="picThumbImgA_"]):even')
But how can I process first four tags only.
Please help me out for the same.
You can try the Zero-based index selector :lt(), like :
$('a[id^="picThumbImgA_"]):lt(4)')
From jQuery's documentation:
Select all elements at an index less than index within the matched set.
You could also use :nth-child(), like:
$('a[id^="picThumbImgA_"]):nth-child(-n+4)')
You can use the jQuery each() function and exit the function by return false when you have processed the first 4.
$('a[id^="picThumbImgA_"])').each(function(index, el) {
if(index < 4) {
//do something
} else {
return false;
}
});

Categories