I'm trying to generate elements with JS after a Query to a SP List. The problem is I can't make a div innerHTML show changes in a loop. The HTML code is this:
<div style="width: 100%;">
<div class="FXmasonryWrapper" id="letterContainers">
<div class="bioBarTitle" id="letterButtons"></div>
<br>
</div>
</div>
The function that generates the items for letterContainers and letterButtons is this:
<script type="text/javascript">
var letters = new Array;
var foundLetters = '';
//QueryList( Repository, ListName, StartingRow, EndRow, SuccessCallback, FailCallback );
QueryList( '/sites/SKCopspcs/testing/', 'QAVGlossary', 1, 1000, function( sender, args ){
//Success -> queryItems
var foundItems = queryItems.getEnumerator();
var letterButtons = document.getElementById( 'letterButtons' );
var letterContainers = document.getElementById( 'letterContainers' );
var _all = "";
var done = 0;
while( foundItems.moveNext() )
{
var found = foundItems.get_current();
var title = found.get_item( 'Title' ) + '';
var definition = found.get_item( 'n5ud' ) + '';
var letter = found.get_item( 'Category' ) ;
if( !foundLetters.includes( letter ) )
{
foundLetters += letter + ', ';
letters.push( letter );
letterButtons.innerHTML += "<span class=\"bioTitle\" id=\"" + letter + "Span\" onclick=\"Show( this )\">" + letter + "</span>";
letterContainers.innerHTML += "<div class=\"FXmasonry bio\" id=\"" + letter + "\"></div>";
}
document.getElementById( letter ).innerHTML += "" +
"<div class=\"FXmasonryItem\">" +
"<span class=\"titleB\">" + title + "</span>" + "<br>" + definition +
"</div>";
_all += "" +
"<div class=\"FXmasonryItem\">" +
"<span class=\"titleB\">" + title + "</span>" + "<br>" + definition +
"</div>";
}
letterButtons.innerHTML += "<span class=\"bioTitle\" id=\"AllSpan\" onclick=\"Show( this )\">All</span>";
letterContainers.innerHTML += "<div class=\"FXmasonry bio\" id=\"All\"></div>";
document.getElementById( 'All' ).innerHTML = _all;
console.log( letterButtons.innerHTML );
}, function( s, a ){
//Fail\"
alert( 'Could not query list "QAVGlossary"' );
});
</script>
letterContainers generates all of it's items correctly, but letterButtons only shows the first element (A button with letter 'A') and when I log the innerHTML of letterButtons, it contains all the span buttons! But only shows 'A' and in the DOM Explorer it only contains the first element (The 'A' button)! If I copy an paste the generated innerHTML (Which I log in console after everything is "generated") from letterButtons in the DOM Explorer, it shows everything!
Why does this happen?
letterButtons.innerHTML contains all the generated items correctly, but it's only showing one and I can't figure out why. I even surrounded the code with try catch, made logs inside the loop and there are 0 erros. Everything is correctly, except that letterButtons.innerHTML contains the correct value but show only the first element.
P.D: I also tried concatenating the items to a variable string ( _genItems += "<span....>"; ) in the loop and in the end do the same:
letterButtons.innerHTML = _genItems;
And the result is the same but in this case it shows nothing. If I log the letterButtons.innerHTML value it contains all the elements but in the DOM Explorer it shows nothing.
After hours of trying to solve this issue I tried this with this piece of code:
<div style="width: 100%;">
<div class="FXmasonryWrapper" id="letterContainers">
<div class="bioBarTitle" id="letterButtons"></div>
<br>
</div>
</div>
I took out the BarTitle from the Wrapper and now works. I really don't have a reason of why this is happening.
<div style="width: 100%;">
<div class="bioBarTitle" id="letterButtons"></div>
<br>
<div class="FXmasonryWrapper" id="letterContainers"></div>
</div>
Related
I have a foreach function which listing all members of array. I want that member of array is a link which change input value.
I have function for reading input like this
<input type="text" id="syote" name="syote" value="" />
<button id="myBtn" onclick="submitti()">Submit</button>
function submitti(){
let current ="syote"
var txt = ""
let array2 = [
'soita',
'sammuta',
'google',
'listaa',
'oskari',
'tee popup',
'10',
'input alas',
'input ylös',
'värillinen',
'mustavalkoinen',
'kysely'
]
if(syote.value.toLowerCase() == "listaaa"){
document.getElementById("vas-col").className = "vasen";
array2.forEach(myFunction);
document.getElementById("result1").innerHTML = txt;
function myFunction(value, array2) {
txt = txt + "<a href=# onclick=Muuta()>" + value + "</a>" + "<br>";
}
}
function Muuta(value) {
input.value = "asdasdasd";
}
This is working and it change input value to asdasdasd.
I want it change input value same than member of array list.
I tried these without succes:
function myFunction(value, array2) {
txt = txt + "<a href=# onclick=Muuta(value)>" + value + "</a>" + "<br>";
function Muuta(value) {
input.value = value;
}
function myFunction(value, array2) {
txt = txt + "<a href=# title=value onclick=Muuta(this.title)>" + value + "</a>" + "<br>";
function Muuta(value) {
input.value = value;
}
Found some examples also and not working in my case. Like this: javascript change input value by link title
After many hours i find solution for this problem.
With this it works:
if(syote.value.toLowerCase() == "listaa"){
// Näissä kohdissa missä id:ssä on väliviiva täytyy käyttää edessä document.getElementById. Ilman sitä ei muuta classia ja näin ollen scroll ei ilmesty.
document.getElementById("vas-col").className = "vasen scroll";
array.forEach(ListaaKomennot);
result1.innerHTML = txt;
function ListaaKomennot(value, array) {
txt = txt + "<a href='#' title='" + value + "' onclick='MuutaArvo(this.title);'>" + value + "</a>" + "<br>";
}
}
function MuutaArvo(arvo) {
syote.value = arvo;
}
In title is very important to be ' before " and same vice versa after value. Without ' ' it cuts out after whitespace when change value of input to title. If you have only words without whitespace that is not a problem.
It is best to solve yourself, i learned many new things at same time. Inter alia if your html id name is with - tag like i have in oik-col you must use document.getElementById without it, className won't work.
I just wonder that how I can get exact div value?
There are about 10 buttons for each div id= cart value=1 / div id=cart value=2 ....... but when I click each buttons, all I can see is just 1 , I increased index tho.
How can I handle this problem?
<%
String url = "https://store.pinkfong.com/category/soundbook/";
String line = "";
int index = 0;
try {
Document doc;
doc = Jsoup.connect(url).get();
Elements media4 = doc.select("div.container ul li img ");
Elements media5 = doc.select(".title ");
for (int i = 0; i < media5.size(); i++) {
Element src1 = media4.get(i);
Element src2 = media5.get(i);
index++;
String templine = "<div id = 'cart' value= " + index + " >"
+ "<button id='button1' onclick='bb();'>button</button>" + src1.toString();
line += templine;
templine = src2.toString();
line += templine + "</div>";
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
%>
<script>
function bb() {
var num = document.getElementById('cart').getAttribute('value');
alert(num);
}
</script>
<body>
<%=line%>
</body>
An ID should be unique. document.getElementById will always return the first result, so in your case, it's only matching the first "cart".
To solve that, I'd just the id from the <div> and change the bb function slightly. Start by passing in the button that was clicked.
<%
// ...
String templine = "<div value= " + index + " >"
+ "<button id='button" + index + "' onclick='bb(this);'>button</button>" + src1.toString();
// ...
%>
Then your bb function should accept that button and get it's parent's value:
function bb(button) {
var num = button.parentNode.getAttribute('value');
alert(num);
}
This is considered an old-school approach and modern-day developers would use "event delegation" to handle this instead, but that may be outside the scope of this question.
It's because you are using ID. So it gets the first item with the ID of 'cart'.
Iam currently working with jquery mobile and have an dynamic notification panel. Thereby I want to check the count of character in the text to base the styling on. So for example if text of a notification is > 10 than set height to Xpx.
But what I first do is this:
for(var count = 0; count < info.data.length; count++){
var shortmessage = info.data[count][3];
var category = info.data[count][4];
if(category === 'douane'){
douaneHtml = douaneHtml + "<div class='notification-item'>" +
"<div class='ui-grid-a notification-grid'>" +
"<div class='ui-block-a'>" +
"<img class='notification-image' src=" + imgPath + ">"+
"</div>" +
"<div class='ui-block-b'>" +
"<span class='notification-text'>" + shortmessage + "</span>" +
"</div>" +
"</div>";
$('.douane-notification-append').empty().prepend(douaneHtml);
}
}
So basically what I want to do is check:
if ( shortmessage.val().length() > 10 ){
$('.notification-item').css('min-height', '100px');
}
But when I do a console.log(shortmessage.val()); inside the if(category === 'douane') I'll get this in return:
shortmessage.val is not a function
Could someone help me out on this so basically what I want to do is count the characters in shortmessage and based on that do different styling.
This is the output of console.log(info.data[count]);
shortmessage is a String, you need to read the length property :
I've cleaned up with string generation, use an array of strings and join them after. much nicer!
Check if its too short and alter style variable
Then use this in template
for(var count = 0; count < info.data.length; count++){
var shortmessage = info.data[count][3];
var category = info.data[count][4];
var style = '';
// if long message, set the style
if ( shortmessage.length > 10 ){
style = 'min-height: 100px';
}else if ( shortmessage.length > 20 ){
style = 'min-height: 200px';
}else if ( shortmessage.length > 30 ){
style = 'min-height: 300px';
}
if(category === 'douane'){
douaneHtml = [
douaneHtml,
"<div class='notification-item' style='" + style + "'>",
"<div class='ui-grid-a notification-grid'>",
"<div class='ui-block-a'>",
"<img class='notification-image' src=" + imgPath + ">",
"</div>",
"<div class='ui-block-b'>",
"<span class='notification-text'>" + shortmessage + "</span>",
"</div>",
"</div>"
].join('');
$('.douane-notification-append').empty().prepend(douaneHtml);
}
}
If you can, try the new ES2015 strings.
Cleans up code a lot.
douaneHtml = `
${douaneHtml}
<div class='notification-item' style='${style}'>
<div class='ui-grid-a notification-grid'>
<div class='ui-block-a'>
<img class='notification-image' src='${imgPath}'>
</div>
<div class='ui-block-b'>
<span class='notification-text'>${shortmessage}</span>
</div>
</div>`;
Problem : val() method can't be called on string and since the shortmessage contains string message that will throw an error.
Suggested solution : just remove the extra .val() and it will works :
if ( shortmessage.length > 10 ){
$('.notification-item').css('min-height', '100px');
}
NOTE : length is a property so you should remove the () from the length.
Hope this helps.
I´m populating webpage with sharepoint so I do a json to get data with ajax like these:
function completeFleet(data, target, eng) {
var items = data.d.results;
console.log(items);
var prefix = "<div class='row'>";
var sufix = "</div>";
var menu = "<div class='col-md-4'>";
var cat = "";
var spec = "";
var counter = 0;
var obj = null;
for (item in items) {
spec = "";
if (counter == 1) {
menu += "</div><div class='col-md-4'>";
counter = 0;
}
if (eng) {
obj = JSON.parse(items[item].Specifications);
for (var key in obj) {
spec += "<div class='row'><div class='col-md-12 ftBottomSeparator'><span class=' t10'>" + key + "</span> <span class='t06' style='float:right;'>" + obj[key] + "</span></div></div>";
}
menu += "<div class='row ftContainerOut'><div class='col-md-12 ftContainer'><div class='row ftHeader'><div class='col-xs-9 t09'>" + items[item].Title + "</div><div class='col-xs-3 text-right'></div></div><div class='row'><div class='col-md-6' style='padding-top:10px'><img src='" + items[item].Imagen.Url + "' class='img-responsive img-center' style='border:0px solid blue; max-width:150px;max-height:120px;' /></div><div class='col-md-6'>" + spec + "</div></div></div></div>";
} else {
obj = JSON.parse(items[item].Especificaciones);
for (var key in obj) {
spec += "<div class='row'><div class='col-md-12 ftBottomSeparator'><span class=' t10'>" + key + "</span> <span class='t06' style='float:right;'>" + obj[key] + "</span></div></div>";
}
menu += "<div class='row ftContainerOut'><div class='col-md-12 ftContainer'><div class='row ftHeader'><div class='col-xs-9 t09'>" + items[item].Title + "</div><div class='col-xs-3 text-right'></div></div><div class='row'><div class='col-md-6' style='padding-top:10px'><img src='" + items[item].Imagen.Url + "' class='img-responsive img-center' style='border:0px solid blue; max-width:150px;max-height:120px;' /></div><div class='col-md-6'>" + spec + "</div></div></div></div>";
}
counter++;
}
$(target).html("<div class='panel-body'><div class='container-fluid'>" + prefix + menu + sufix + "</div></div>");
}
I have 5 objects different, but one of these don´t show data, my webpage is in english and spanish, in english it charge all data, but in spanish one of these
doesn´t works and I get error at position 36, and position 36 is the item don´t show. Any idea what is wrong here? Regards
These one works
and this no works
---------Update------------
If I comment this line:
//obj = JSON.parse(items[item].Especificaciones);
and put
if(items[item].Especificaciones){
JSON.parse(items[item].Especificaciones);
}
it now runs with image, but now I don´t have my "Especificaciones" lists
Now when I use
var stringifyObj = JSON.stringify(items[item].Especificaciones);
var obj = JSON.parse(stringifyObj);
I get something like these:
make sure value is not null for the corresponding key inside JSON.parse. For example-
JSON.parse(items[item].Specifications)
make sure items have value in item index and items[item] has the property Specifications.
you can check if items[item].Specifications is not null before JSON.parse.
if(items[item].Specifications){
JSON.parse(items[item].Specifications)
}
Update
JSON.parse() is used to convert a string containing JSON notation into a Javascript object. To be valid JSON, strings must be in double quotes.
Try stringify the object and then parse again.
var stringifyObj = JSON.stringify(items[item].Especificaciones);
var obj = JSON.parse(stringifyObj);
The reason for the error is that JSON.parse() expects a String value and items[item].Especificaciones is an Array
"Eslora":100 pies"
You should probably opening the quotes when you start writing a string value
I'm trying to do something pretty simple, but for some reason I can't spot my mistake. The statement at the end of the function seems to be executing prior to the for loop, which I'm sure isn't the case.
var object = {
"key1":"foo",
"key2":"bar"
}
var message = document.getElementById("message");
message.innerHTML = "<table>";
for(var index in object) {
if (object.hasOwnProperty(index)) {
message.innerHTML += "<tr><td>" + index + "</td><td>" + object[index] + "</td></tr>";
}
}
message.innerHTML += "</table>";
I figured this would create the string:
<table>
<tr><td>key1</td><td>foo</td></tr>
<tr><td>key2</td><td>bar</td></tr>
</table>
However, when I inspect element, I'm getting this result:
<div id="message">
<table></table> <!-- why would </table> be in the string before key1 etc.? -->
key1fookey2bar
</div>
When I replace the table with line breaks, it looks like the loop is executing correctly, so I'm not sure what's happening. Can anyone spot my mistake?
It is because you are appending directly to the innerHTML of the message.
Build your html using a variable, and then set message.innerHTML = that variable.
As in:
var messageElement = document.getElementById("message");
var message = "<table>";
for(var index in object) {
if (object.hasOwnProperty(index)) {
message += "<tr><td>" + index + "</td><td>" + object[index] + "</td></tr>";
}
}
message += "</table>";
messageElement.innerHTML = message;