How to clear innerHTML of spans - javascript

I have a basic form in html, when user leave blank fields I show a message in spans that I created via javascript, so far so good. But if I click 'submit' button again and again, the messages are printed again and again Above the message that has already been printed, I mean overlapping.
I tried the element.innerHTML = ''; and this. Maybe I'm implementing it badly since it does not work.
var myForm = document.getElementsByTagName('form')[0];
var formFields = document.getElementsByTagName('label');
myForm.addEventListener('submit', function(){
event.preventDefault();
var statusMessageHTML = [];
// create empty spans
for(i = 0; i < formFields.length; i++){
statusMessageHTML[i] = document.createElement('span');
statusMessageHTML[i].className = 'status-field-message';
formFields[i].appendChild(statusMessageHTML[i]);
}
// print a string in empty spans
for(i = 0; i < formFields.length; i++){
statusMessageHTML[i].innerHTML = "Error Message"
}
return false;
});
PD: I want to solve this using pure javascript.
CODEPEN

To prevent this, you can create and append those spans in advance, and just modify their text when the submit button is clicked.
For example, rearrange your code as following:
var myForm = document.getElementsByTagName('form')[0];
var formFields = document.getElementsByTagName('label');
// create empty spans in advance
var statusMessageHTML = [];
for(var i = 0; i < formFields.length; i++) {
statusMessageHTML[i] = document.createElement('span');
statusMessageHTML[i].className = 'status-field-message';
formFields[i].appendChild(statusMessageHTML[i]);
}
myForm.addEventListener('submit', function(event) {
event.preventDefault();
// change the text of spans
for(var i = 0; i < formFields.length; i++)
statusMessageHTML[i].textContent = 'Error Message';
});
Note:
You have to include corresponding variable name (i.e., event) in the function's parameters before using it.
span.textContent may be preferable to span.innerHTML in your case.
It is pointless to return a value in the addEventListener's callback function. The returned value is simply discarded.
It is a good practice to declare all variables (e.g., i) before using them.
You can also construct those spans directly in HTML, since they are kind of "static" in the structure.
Updated
If I understand it correctly, you prefer:
Create those spans as placeholders when it is the first time the user submits.
Rewrite values in spans when the response of the ajax request is received.
If the submit button is clicked multiple times, just clear previous values in spans, and the following process remains the same.
Then I believe you just need to wrap the whole part in a if-else block:
var myForm = document.getElementsByTagName('form')[0];
var formFields = document.getElementsByTagName('label');
var statusMessageHTML = [];
var isFirstSubmit = true;
myForm.addEventListener('submit', function(event) {
event.preventDefault();
if(isFirstSubmit) {
// create empty spans
for(var i = 0; i < formFields.length; i++) {
statusMessageHTML[i] = document.createElement('span');
statusMessageHTML[i].className = 'status-field-message';
formFields[i].appendChild(statusMessageHTML[i]);
}
isFirstSubmit = false;
} else {
// clear previous values
for(var i = 0; i < formFields.length; i++)
statusMessageHTML[i].textContent = '';
}
});
And rewrite the values when you get the response (possibly wrapped in a callback function, since it is an AJAX request):
function callback(response) {
for(var i = 0; i < formFields.length; i++)
statusMessageHTML[i].textContent = /*values in response*/;
}

Related

How to read back data from LocalStorage

Once checkbox is active there are various <p> tags that get class "result". What I do with them is following:
function submit(){
alert("in submit");
var user_choice = document.getElementsByClassName("result");
for (var i = 0; i < user_choice.length; i++){
console.log(user_choice[i].innerHTML);
}
localStorage.setItem('storage',user_choice);
}
I hope this makes an HTMLcollection. After that, at submitted.html page (redirect there after pressing submit button) I wanna console.log all the items. So I write this:
window.onload = function() {
if ( localStorage.getItem('storage')) {
var got_user_choice = localStorage.getItem('storage');
for (var i = 0; i < got_user_choice.length; i++){
console.log(got_user_choice[i].innerHTML);
}
}
}
As long as it's a HTMLcollection (read array) I operate with it in terms of array. But what I get in console is just undefined. What's wrong with my code?
Local storage can only contain strings, not DOM elements. You should make an array of all the elements, and convert that to JSON.
function submit(){
alert("in submit");
var user_choice = document.getElementsByClassName("result");
var html = [];
for (var i = 0; i < user_choice.length; i++){
console.log(user_choice[i].innerHTML);
html.push(user_choice[i].innerHTML);
}
localStorage.setItem('storage',JSON.stringify(html));
}

Javascript HTML include results in duplicate includes in random places

This problem has me absolutely stumped. I'm trying to include HTML snippets with Javascript and it works, but for some reason it decides to also include duplicate snippets in various other locations.
Here is a screenshot of what I mean:
It also varies the number and location of these random includes.
This is the function I use to include. It searches through the document and finds div elements with the attribute include="x.html"
function include() {
var allElements;
var fileName;
var includeRequest;
allElements = document.getElementsByTagName("*");
for (var i = 0; i < allElements.length; i++) {
if (allElements[i].getAttribute("include")) {
fileName = allElements[i].getAttribute("include");
includeRequest = new XMLHttpRequest();
includeRequest.open("GET", fileName, true);
includeRequest.onreadystatechange = function() {
if (includeRequest.readyState == 4 && includeRequest.status == 200) {
allElements[i].removeAttribute("include");
allElements[i].innerHTML = includeRequest.responseText;
include();
delete includeRequest;
includeRequest = null;
}
}
includeRequest.send();
return;
}
}
}
This is the function that gets tags from an html file containing articles, and adds them to the list of tags in the box on the right. As you can see, in one place the footer is added to the list instead of the tag. I don't know why.
function getTags() {
var taglist = document.getElementById("taglist");
var tagsRequest = new XMLHttpRequest();
tagsRequest.open("GET", "blogstubs.html", true);
tagsRequest.responseType = "document";
tagsRequest.onreadystatechange = function() {
if (tagsRequest.readyState == 4 && tagsRequest.status == 200) {
var tagsResponse = tagsRequest.responseXML;
var tags = tagsResponse.getElementsByClassName("tag");
var tags = getUnique(tags);
var len = tags.length;
for (var i = 0; i < len; i++) {
var li = document.createElement("li");
li.appendChild(tags[i]);
taglist.appendChild(li);
}
delete tagsRequest;
tagsRequest = null;
}
}
tagsRequest.send();
}
Javascript only solution please. Ideas?
I copied your website (I hope you don't mind) and tested it with my changes, it seems to be working now without this bug. Here's what I did:
1) I created a new function, don't forget to change the name to whatever you prefer:
function newFunction(allElements, includeRequest) {
allElements.removeAttribute("include");
allElements.innerHTML = includeRequest.responseText;
include();
delete includeRequest;
includeRequest = null;
}
2) I changed the include() function to look like this:
function include() {
var allElements;
var fileName;
var includeRequest;
allElements = document.getElementsByTagName("*");
for (var i = 0; i < allElements.length; i++) {
if (allElements[i].getAttribute("include")) {
var element = allElements[i];
fileName = element.getAttribute("include");
includeRequest = new XMLHttpRequest();
includeRequest.open("GET", fileName, true);
includeRequest.onreadystatechange = function() {
if (includeRequest.readyState == 4 && includeRequest.status == 200) {
return newFunction(element, includeRequest);
}
}
includeRequest.send();
return;
}
}
}
I think the problem was caused by async nature of AJAX requests, like I said in the comment. So you need to pass the variables to your AJAX call instead of using the global scope, that's why you need this new callback function.
In other words, in the original code the AJAX variable allElements[i] wasn't in sync with your loop's allElements[i], so while in your loop it would be 5, in AJAX function (which executed separately and not in order with the loop) it would be 3, 6 or whatever else. That is why it would append the html to the element that seems random. Think of AJAX as of someone who doesn't care about the order of your loops, someone who really doesn't like to wait while someone else is counting and does everything in his own order.

How can I fix this type mismatch error when calling JS from VBScript?

In the onclick event of an HTML button, I call this sub:
Sub SaveStuff(SQLQuery, DOMFieldID, ButtonId, ButtonColour)
dbConn.Execute SQLQuery
Call resetButtonColors(DOMFieldID)
Call changeButtonColor(ButtonId, ButtonColour)
End Sub
resetButtonColors and changeButtonColor are JS functions.
function resetButtonColors(groupName){
var elements = document.getElementsByName(groupName)
for (var i = 0; i < elements.length; i++)
{
elements[i].style.backgroundColor = "rgb(192,192,192)"
}
}
function changeButtonColor(btn, newColor){
var element = document.getElementById(btn);
element.style.backgroundColor = newColor
}
But I am getting a type mismatch error that I don't know how to fix. I tried to cast the values to string but didn't work.

javascript input value changes not taking effect? Calculation field value does not change?

I am using javascript to populate a page which has a calculation field. The calculation field only gets set when i click on the page or tab manually. I don't think javascript is populating the fields until i click tab.
Iv tried runing a methoud to foucus on all the inputs.
function PushTab()
{
//could not get this working as i could not select a input with js and run the trigger function of jq .. mixing js with jquery is bad.
//$(this).trigger({
// type: 'keypress',
// which: 9
//});
var doc = window.frames['main'].window.frames['content'].document;
var tabbables = doc.querySelectorAll("input");
for (var i = 0; i < tabbables.length; i++) {
tabbables[i].focus();
}
}
Could someone tell me how i could trigger all my javascript changes to take affect, something that simulates a users tab or click on page?
Edit
How i change the values.
function SetElementValue(name, value) {
var elementType = "input";
element = GetElement(elementType, name);
if (element != null) {
element.value = value;
return;
}
function GetElement(type, name) {
var doc = window.frames['main'].window.frames['content'].document;
if (doc != null) {
var aTags = doc.getElementsByTagName(type);
var searchText = name;
var found;
for (var i = 0; i < aTags.length; i++) {
if (aTags[i].name.trim() == searchText) {
found = aTags[i];
//alert(found.type);
return found;
break;
}
}
}
return found;
}

How to add/remove a value from stored html

According to the user navigation to pages, i would like to show appropriate side bars. so I am basically getting html of side bar and putting in empty.
and i am storing the sidebar to object. before i add to object i would like to add an id to side bar. i am trying but not working;
here is my try:
var ob = {};
var catcheBars = {};
var sidebar = $('div.sidebar');
var catchedBar = sidebar;
sidebar.empty();
for(i=1; i <= 5; i++) {
if(!ob.hasOwnProperty(i+'page')) {
ob[i+'page'] = catchedBar;
console.log($(ob[i+'page']).find('button').addClass('sidebar'+i)); //not able to add class
}
}
$("#sideBar").html(ob['1page']); //nothing append to live..
console.log(ob);
my try is not working. when i do the mistake, or what is the correct way?
thanks in advance
Update
Live Demo
I removed the empty() function. it works fine.
here is he updated result
var ob = {};
var catcheBars = {};
var sidebar = $('div.sidebar');
var catchedBar = sidebar;
for(i=1; i <= 5; i++) {
if(!ob.hasOwnProperty(i+'page')) {
ob[i+'page'] = catchedBar;
console.log($(ob[i+'page']).find('button').addClass('sidebar'+i)); //not able to add class
}
}
$("#sideBar").html(ob['1page']); //nothing append to live..
console.log(ob);

Categories

Resources