innerHTML is not working inside a function - javascript

I'm a beginner in Javascript programming. innerHTML method is not working in a function to update content of a HTML element.
My JS code is :
$(':button').on("click", function() {
// reference clicked button via: $(this)
var buttonElementId = $(this).attr('id');
var sliceId = buttonElementId.charAt(buttonElementId.length - 1);
bringData(sliceId);
})
function bringData(id) {
var a = localStorage.getItem("Blogs")
var b = JSON.parse(a)
console.log(b[id].blogHeader)
document.getElementById("foo").innerHTML = b[id].blogHeader
}
Buttons and element which has id of "foo" are at different HTML pages. I want to update content of that element after clicking any button from other page, but it is not working. The content still remains same. What is my mistake ?
Note : If I use innerHTML property out of a function, it works and content is changing.

Related

appendChild odd behavior in javascript

In the procedure of creating and appending elements to a webpage, I faced an odd behavior of javascript, that is replacing a child with another instead of appending. here is the code:
var window = document.createElement("div"); //the minesweeper game window
window.setAttribute("class", "window");
document.body.appendChild(window);
var title_bar = document.createElement("div");//the title bar of the window
title_bar.setAttribute("class", "title-bar");
window.appendChild(title_bar);
var game_title = document.createElement("span");//the title of the game
game_title.setAttribute("id", "game-title");
game_title.innerHTML = "Minesweeper Online - Beginner!";
title_bar.appendChild(game_title);
var right_corner_div = document.createElement("div");// right corner buttons
title_bar.appendChild(right_corner_div);
var btn_minimize = document.createElement("span");//the minimize button
btn_minimize.setAttribute("class", "btn");
btn_minimize.setAttribute("id", "btn-minimize");
btn_minimize.innerHTML = "-";
right_corner_div.appendChild(btn_minimize);
var btn_close = document.createElement("span");//the close button
btn_close.setAttribute("class", "btn");
btn_close.setAttribute("id", "btn-close");
btn_close.style.marginLeft = "3px";
btn_close.innerHTML = "×";
right_corner_div.appendChild(btn_close);
var top = document.createElement("div");//top of window div, underneath the title bar
title_bar.setAttribute("class", "top");
window.appendChild(top);
but unlike what I expect to see as the result, the latest div with the class attribute of top replaces the first div with the class attribute of title-bar. why does this happen?
You have title_bar here instead of top (second last line in your question):
var top = document.createElement("div");
*title_bar*.setAttribute("class", "top");
window.appendChild(top);
Replace that with top and it should work.
By the way, don't name a variable window in a browser, since that is what the global object reference is assigned to. Call your variable game_window or something else along those lines instead.
Also you probably don't care about the actual HTML class attribute of your elements and should set the className property directly instead:
top.className = "top"; // instead of top.setAttribute("class", "top");

Changing a dynamically created label's text with keyup() issue

I am creating a form dynamically and therefore edit the form elements’ properties. When attempting to change the label, assigning an auto-generated id works fine but when changing this label using the generated id, the function or keyup() from jQuery keeps calling all the previously created label id(s). this means when i want to edit one label, it ends up editing every label.
HTML
<input type="text" id="change-label"><br><br>
<button id="add-button">add label</button>
<div id="add-label"></div>
JavaScript/jQuery
$('#add-button').click(function(){
var div = document.createElement('div');
var textLabel = document.createElement('label');
var labelNode = document.createTextNode('untitled');
textLabel.appendChild(labelNode);
textLabel.id = autoIdClosure();
$('#change-label').val('untitled');
div.appendChild(textLabel);
$('#add-label').append(div);
});
var autoIdClosure = (function(){
var counter = 0;
var labelId = "textInputLabel";
return function(){
counter += 1;
var id = labelId + counter;
editLabelWrapper(id)
return id;
}
})();
function editLabelWrapper(id){
function editLabel(){
var value = $(this).val();
$("#"+id).text(value);
}
$("#change-label").keyup(editLabel).keyup();
}
I’ve already found an alternative using onkeyup="$('#'+globaID).text($(this).val());", but I need to understand what I was doing wrong so I can learn from it.
JSFiddle
I think you are overthinking the matter...
Instead of using an unique id, rather use classes, makes it easier to handle.
So change <div id="add-label"></div> to <div class="add-label"></div>
Then what you want to do is, when a value is given in #change-label you want it in the last div.add-label.
So the function will become this:
$("#change-label").on('keyup', function() {
$('.add-label:last').text( $(this).val() );
});
Next what you want to do is bind a function to #add-button. Once it gets clicked, we want to add a new div.add-label after the last one. And empty the #change-label. You can do that by using this function:
$('#add-button').on('click', function() {
$('.add-label:last').after('<div class="add-label"></div>');
$('#change-label').val('');
});
Updated Fiddle

On search/highlight click -> existing div becomes wrapped with existing span

I have a problem with javascript search and highlight text.
For example, there is existing span element and existing div element.
Problem is that if I click on search button for some reason div element becomes a child of span element.
To explain it better I have created JS fiddle to show the problem:
function highlightSearch() {
$('span').removeClass('highlighted');
var text = document.getElementById('query').value;
var query = new RegExp("(\\b" + text + "\\b(?!([^<]+)?>))", "gim");
var e = document.getElementById("searchText").innerHTML;
var enew = e.replace(/(<span class='highlighted'>|<\/span>)/igm, "");
document.getElementById("searchText").innerHTML = enew;
var newe = enew.replace(query, "<span class='highlighted'>$1</span>");
document.getElementById("searchText").innerHTML = newe;
}
Check problem on : JSfiddle
Well, you are removing all </span> tags from the innerHTML in this line:
var enew = e.replace(/(<span class='highlighted'>|<\/span>)/igm, "");
And therefore also the </span> of .glyphicon. This is why the element becomes wrapped.
Btw: An exception is thrown: ReferenceError: highlightSearch is not defined

DOM: Delete newly created 'article' element with newly created delete button within onclick event?

I have one section element that contains one article element. Also, I have one input button with 'onclick' event. Whenever this event fired, a new article element appended to the section element with unique id.
The newArticle element contains a label, text box and a delete button. All these three elements get created within the on-click event.
document.getElementById("addRow").onclick = function () {
var newCustomerlbl = document.createElement("label");
newCustomerlbl.innerHTML = "Cutomer Name: ";
var newCustomertxt = document.createElement("input");
newCustomertxt.setAttribute("type", "text");
var delBtn = document.createElement("input");
delBtn.setAttribute("type", "button");
delBtn.setAttribute("value", "Delete");
delBtn.setAttribute("id", "btnDelete");
var newArticle = document.createElement("article");
newArticle.appendChild(newCustomerlbl);
newArticle.appendChild(newCustomertxt);
newArticle.appendChild(delBtn);
var customerSection = document.getElementById("customerRecords");
var customerArticles = customerSection.getElementsByTagName("article");
for (var i = 0; i < customerArticles.length; i++) {
var lastDigit = i + 1;
var newArticleValue = "article" + lastDigit;
newArticle.setAttribute("id", newArticleValue);
}
customerSection.appendChild(newArticle);
}
Now what I want is whenever user click upon the newly created appended delete button, only that particular article get deleted without effecting the rest of articles.
Here is the my jsFiddle code.
If you don't want to use jQuery you can add event listeners to your buttons:
delBtn.addEventListener('click', function () {
this.parentElement.remove();
}, false);
https://jsfiddle.net/3nq1v5e1/
You need to bind an event listener on the newly created delete button. Your example code about using $(this) suggest that you are using JQuery, but then again in the rest of the code you are not using any JQuery?
If you are using JQuery, things get real simple, just add something like
$(document).on('click','.btnDelete', function(){
$(this).closest('article').remove();
});
(and remember to give the deletebutton a CLASS rather than ID, as there will be multiple delete buttons).
If you are NOT using JQuery, you need to add the event listener EVERY TIME a new delete button is created
newArticle.appendChild(delBtn);
delBtn.onclick = function(.....
etc.

Java Script : get the string equivalent of a elements ID

my naming convention
id=xxxxx //actual field shown in the screen
id=xxxxxHDN // hidden field containing the enable/disabled status of the component from the set from the controller.
Now what I am trying to do is get the satus of xxxxxHDN to be true/false ,
and accordingly set the components status to disabled /enabled .with java script..
var div = document.getElementById("hiddenFields"); // i hava some 30 hidden fields containing the
var j;
for (j=0;j<div.childNodes.length;j++)
if(div.childNodes[j].value){
alert("inside the loop");
var someElementHDN = div.childNodes[j].id; // my aim is to get the ID=xxxxxHDN
var someElementHDNToString = someElementHDN .toString(); // my aim is to get the string value "xxxxxHDN"
var toRemove = 'HDN'; // the part i wanna remove from 'someElementHDNToString' to make it an id for 'xxxxx'
var equivalantComponentIDAsString = someElementToString.replace(toRemove,'');
$('#' + equivalantComponentIDAsString ).attr('disabled', true);
}
}
Invested a lot of time manupulatiing things above , doesent seems to work . I am new to java scrcript , Where am I missing it?
If you have an element with id like 'fooHDN' and want to find another element with id 'foo', then you can do something like:
var otherElement = document.getElementById(someElement.id.replace(/HDN$/,''));
Assuming that you already have someElement and it's a DOM element.
Your posted js code has error: div does not have a "length", do you mean "div.childNodes.length"?
Anyway, since you're using jQuery already, I think it can become easier as below:
Already tested and it works fine.
$("#hiddenFields input[type='hidden'][id$='HDN']").each(
function () {
var elemId = this.id.replace(/HDN$/, '');
$('#' + elemId).attr('disabled', this.value.toLowerCase() == 'false' ? false : true);
}
);

Categories

Resources