JavaScript - cloneNode gives different result [duplicate] - javascript

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.

Related

Check if all inputs of class have value [duplicate]

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.

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";
}

Removing all dynamic 'data attributes' of an Element [duplicate]

This question already has answers here:
Remove multiple html5 data-attributes with jquery
(7 answers)
Closed 8 years ago.
I have a div where dynamic data- attributes get added on some tags.
(name of data- attributes to be generated dynamically by script, so there is no way my script will know the NAME of data-attribute)
<div data-1223="some data" data-209329="some data" data-dog="some value"> </div>
Now, I want to write a code in which it resets the div by removing all the data attributes and their values.
I can use
$('div').attr('data-209329',"")
but the problem is I don't know the name of data-attribute that will be added.
the data-attribute that will be added is dynamic and I don't have control of it.
removing div and reinserting div is not an option.
Pls help.
thanks in advance
YOu can use like this
var data = $("div").data();
var keys = $.map(data, function (value, key) {
return key;
});
for (i = 0; i < keys.length; i++) {
$("div").removeAttr("data-" + keys[i]);
}
Fiddle
Edit
Suggested by #Mottie
$.each($('div').data(), function (i) {
$("div").removeAttr("data-" + i);
});
Demo
You can use this code :
var data = $('div').data();
for(var i in data){
//for change
$('div').attr("data-"+i,"something");
//for remove
$("div").removeAttr("data-" + i);
}
The $('div').data(); prepare a list of all data attributes in var data variable.
Then you can work with it.
This is fiddle of this solution.
UPDATE
Suggested by #Mottie
$.each($('div').data(), function (i) {
//for change
$('div').attr("data-"+i,"something");
//for remove
$("div").removeAttr("data-" + i);
});
I think that the removeData() function is what you are looking for here. This will remove all data information stored on the element.
The .removeData() method allows us to remove values that were previously set using .data(). When called with the name of a key, .removeData() deletes that particular value; when called with no arguments, all values are removed. Removing data from jQuery's internal .data() cache does not affect any HTML5 data- attributes in a document; use .removeAttr() to remove those.
It will not however remove the actual attributes from the elements. In order to remove the actual attributes, you'll need to extract a list of the existing attributes. You could do this by inspecting the data() function of an element (before running removeData).
The data() function will return an object of key => value pairs that you can then use to remove the actual attributes from the element using removeAttr().

Is there any function in javascript, to detect a change in document? [duplicate]

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

Add multiple element using jquery each? [duplicate]

This question already has answers here:
Why do multiple `.appendTo` calls on a newly created jQuery element only append it once?
(2 answers)
Closed 3 months ago.
I'm new here and I'd like to ask a question about jQuery.
i have some problem with jquery each, and i have code :
$("#search-submit").click(function(){
var item = $("<span>asdf</span>");
$("body").append(item, item);
}
I just can't figure out, why is this simple code don't work. Instead of print "asdf" twice, i just got one "asdf" printed each time i click the button..
this also don't work. this is so silly...
$("body").append(item);
$("body").append(item);
Thanks a lot... and sorry about my bad english
Denny.
You can append a jQuery object only one time, you can clone the object:
$("#search-submit").click(function() {
var item = $("<span>asdf</span>");
$("body").append(item, item.clone());
})
Or append a string:
$("#search-submit").click(function() {
var item = "<span>asdf</span>";
$("body").append(item, item);
})
http://jsfiddle.net/yKyAL/
You can use clone
$("#search-submit").click(function() {
var item = $("<span>asdf</span>");
$("#test").append(item.clone(), item.clone());
});​
Check the fiddle here

Categories