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";
}
Related
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.
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.
So I was reading this SO question earlier, and I am currently trying to get a basic implementation of Unobtrusive javascript working, but I don't know where I'm struggling. Normally this is something I would struggle with for much longer until I figure it out on my own, but I'm starting to get in a bit of a time crunch...
I have a several elements within my HTML document with a class called "RMButton", and I'm trying to make all of my elements with this class call a function called "RemoveQBox" (For clarity. The QBox is a DIV element, and the objects of class "RMButton" are small buttons that remove the div from the document). RemoveQBox, is already written and works just fine when I use inline JS to call it (Ex: REMOVE), but for some reason my binding within JS isn't really working out. Anybody know what I'm missing here?
Top of my Javascript file
var DBSetFields = [];
var NumQBoxes = 1;
window.onload = function() {
RMNodeList = document.getElementsByClassName("RMButton");
for (var i = 0; i < RMNodeList.length; ++i) {
console.log(RMNodeList[i]);
RMNodeList[i].onclick = RemoveQBox;
}
};
TLDR: How do I bind all elements of a particular class to a function in Javascript?
edit:
function RemoveQBox(e){
console.log("Remove");
var RemoveButton = this; //this == e.currentTarget
console.log(RemoveButton);
var QBox = RemoveButton.parentNode;
QBox.remove();
NumQBoxes -= 1;
}
This question already has answers here:
Detect element tag name by its class
(5 answers)
Closed 9 years ago.
Hi guys i only wanted to ask how to get the tag name of an element that has a class name, im trying this:
function copyElement(){
$('body').keypress(function(event) {
if(event.which == 99){
var elementToCopy = $('.highlight').attr('tag');
alert(elementToCopy);
var newElement = $(document.createElement(elementToCopy));
}
});}
But im always getting undefined! :( help please.
Try this
$('.highlight').prop("tagName").toLowerCase();
var tag = this.nodeName.toLowerCase(); // native JS
var tag = $(this)[0].nodeName.toLowerCase(); // the jquery equiv.
var tag = $('.SomeClass')[0].nodeName.toLowerCase(); // the jquery equiv. with selector
This will go through each tag with that class.
$('.highlight').each(function() {
alert(this.tagName);
});
This question already has answers here:
Attaching jQuery plugin calls to dynamically loaded elements via jQuery,on()
(3 answers)
Closed 9 years ago.
I have an HTML page, which contains many select boxes, to beautify those boxes I have used "select2", What I have done is:
$(document).ready(function() { $("select").select2(); });
This makes all of the select boxes to get transform like "select2".
But now I am generating the tables on a button click(after the document is ready), therefore the newly generated select boxes doesn't looks like "select2", Please help me if there is any function that detects the change in document?
Something like:
$(document).change(function() { $("select").select2(); });
In at least some browsers (not any current version of IE, though), you can do this, via a MutationObserver (this is the new DOM4 thing, not the old DOM3 mutation events, which you want to stay away from).
But I don't recommend it, just call select2 again after your code that appends the new selects.
Another option is to use a timer: Get a NodeList of all select elements on the page:
var allSelects = document.getElementsByTagName('select');
...and poll checking its length (NodeLists are live, you don't have to re-query):
var lastLength = 0;
setInterval(function() {
if (allSelects.length !== lastLength) {
lastLength = allSelects.length;
// Hook up the new ones here
}
}, 1000); // 1000ms = 1 second
You could put a class on them to keep track of which ones are already done (if select2 doesn't already do that).
But again, you have code adding select elements, just re-trigger there.
You can try something like this:
function checkDocumentChange() {
// Run a simple task to check whether any new "selects" were added
var old_value = checkDocumentChange.num_selects || 0;
var new_value = $("select").length;
if (old_value != new_value) {
$("select:not(.already_done)").select2();
}
checkDocumentChange.num_selects = new_value;
setTimeout(checkDocumentChange, 100);
}
DOM events are not recommended to use since those are deprecated.
Better approach would be, of course, to call .select2() right after you insert select into DOM. So that you will not have to delegate this to some checker or event.
You can try DOMNodeInsertedIntoDocument
$(document).on('DOMNodeInsertedIntoDocument', function() {
}
Or mutation observer
use this id or class
in this code
var id = document.getelementbyid("id for select 1 or 2");
//here the code