Trying to write some html to a div in 001, 002, 003 style format but I can't get it to work.
Here's the code:
function loadpics(x, url) {
var txt, i;
txt = "";
for(i = 1; i < x; i++) {
txt = txt + String.format("%03d", i) + "<br/>";
}
document.getElementById("myDiv").innerHTML = txt;
}
When I hopefully get it to work, I intend to load some images to the div like so:
function loadpics(x, url) {
var txt, i;
txt = "";
for(i = 1; i < x; i++) {
txt = txt + "<img src=\"" + url + "/t/" + String.format("%03d", i) + ".jpg\"></img><br/>";
}
document.getElementById("myDiv").innerHTML = txt;
}
Can't get the string formatting to work though. Not exactly sure what I'm doing wrong.
If anyone can put me straight it would be most appreciated.
Try using pad() instead of String.format().
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
Add this to your page
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
And replace txt=txt... with this
txt += "<img src='" + url + "/t/" + pad(i,3) + ".jpg'></img><br/>";
Also have a look at this topic
Related
I got webpage with JS code that get randomize Object from array and show it's value with Jquery .html() code in some div.
That work great.
When I click on a another page on the website it also look great, but when I click back on the browser, the code what created max the JavaScript Variables and I get the wrong text in the wrong placement
Any Tip what should I look for?
function showMoodaa(size, divID, countshow) {
if (typeof(countshow) === 'undefined')
countshow = 1;
var rndBanner = "";
var htmlcode = "";
if (modaoot[size] != undefined) {
if (countshow > 1) {
var countMoodaa = modaoot[size].length;
if (countMoodaa > countshow) {
countMoodaa = countshow;
}
rndBanner = Math.floor(Math.random() * modaoot[size].length);
for (i = 0; i < countMoodaa; i++) {
if ((rndBanner + i) >= modaoot[size].length) {
htmlcode = htmlcode + (modaoot[size][rndBanner + i - countMoodaa].html);
window.numBanner = window.numBanner + modaoot[size][rndBanner + i - countMoodaa].id + ",";
} else {
htmlcode = htmlcode + (modaoot[size][rndBanner + i].html);
window.numBanner = window.numBanner + modaoot[size][rndBanner + i].id + ",";
}
}
} else {
rndBanner = Math.floor(Math.random() * modaoot[size].length);
window.numBanner = window.numBanner + modaoot[size][rndBanner].id + ",";
htmlcode = modaoot[size][rndBanner].html;
}
} else {
htmlcode = "<!-- no size like this in array-->";
}
$("#" + divID).append(htmlcode);
}
showMoodaa(2, "pos1");
showMoodaa(2, "pos2");
showMoodaa(10, "pos1", 2);
var swTitle = {};
var favorite = [];
$.each($("input[name='Title']:checked"), function() {
favorite.push($(this).val());
console.log($("input[name='Title']:checked"));
});
swTitle.domain = favorite;
var List = {};
for (var m = 0; m < favorite.length; m++) {
var swTitleObj = [];
$.each($('input[name="' + swTitle.domain[m] + '"]:checked'), function() {
console.log(swTitle.domain[m]);
swTitleObj.push($(this).attr("class"));
console.log(swTitleObj);
});
List[swTitle.domain[m]] = swTitleObj;
}
var swSkillData = " ";
$.each(List, function(key, value) {
console.log(key + ":" + value);
swSkillData += '<li>' + key + ' ' + ':' + ' ' + value + '</li>';
});
Output will be like:
Fruits:Apple,Banana,Orange,Grapes
I want my output be like:
Fruits:Apple,Banana,Orange & Grapes
I have an array of keys and values separated by commas. I want to insert "and" and remove the comma before the last checked element. Kindly help me out with this issue.
I think you can reduce your code, with an option of adding and before the last element like,
var inputs=$("input[name='Title']:checked"),
len=inputs.length,
swSkillData='',
counter=0;// to get the last one
$.each(inputs, function() {
sep=' , '; // add comma as separator
if(counter++==len-1){ // if last element then add and
sep =' and ';
}
swSkillData += '<li>' + this.value + // get value
' ' + ':' + ' ' +
this.className + // get classname
sep + // adding separator here
'</li>';
});
Updated, with and example of changing , to &
$.each(List, function(key, value) {
console.log(key + ":" + value);
var pos = value.lastIndexOf(',');// get last comma index
value = value.substring(0,pos)+' & '+value.substring(pos+1);
swSkillData += '<li>' + key + ' ' + ':' + ' ' + value + '</li>';
});
Snippet
var value ='Apple,Banana,Orange,Grapes';var pos = value.lastIndexOf(',');// get last comma index
value = value.substring(0,pos)+' & '+value.substring(pos+1);
console.log(value);
Here is an easy and customizable form of doing it.
(SOLUTION IS GENERIC)
$(document).ready(function() {
var ara = ['Apple','Banana','Orange','Grapes'];
displayAra(ara);
function displayAra(x) {
var str = '';
for (var i = 0; i < x.length; i++) {
if (i + 1 == x.length) {
str = str.split('');
str.pop();
str = str.join('');
str += ' and ' + x[i];
console.log(str);
$('.displayAra').text(str);
break;
}
str += x[i] + ',';
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Fruits : <span class="displayAra"></span>
str = str.replace(/,(?=[^,]*$)/, 'and')
I solved my own issue. I replaced my last comma with "and" using the above regex. Thanks to Regex!!!
I have a bit of code that requires printing underscores but to the line above it, how would i do this? I'm not sure how to print the underscore to the previous line, not much experience with javascript. thanks!
var landscape = function() {
var result = "";
var flat = function(size) {
for (var count = 0; count < size; count++)
result += "_";
};
var hill = function(size) {
result += " /";
for (var count = 0; count < size; count++)
result += ""+
"_";
result += " \\";
};
//BUILD SCRIPT
flat(3)
hill(4);
flat(6);
hill(1);
flat(1);
//END SCRIPT
return result;
it makes this ___ /____ \______ /_ \_`enter code here`enter code here`
and i want this
_____ ___
___/ \__/ \____/\_
You can keep track of the two lines separately and then concatenate them just before returning the result.
JS:
function landscape() {
var resultTop = '';
var resultBottom = '';
function hill(size) {
resultTop += ' ';
resultBottom += '/';
for (var i = 0; i < size; i++) {
resultTop += '_';
resultBottom += ' ';
}
resultTop += ' ';
resultBottom += '\\';
}
function flat(size) {
for (var i = 0; i < size; i++) {
resultTop += ' ';
resultBottom += '_';
}
}
flat(3);
hill(4);
flat(6);
hill(1);
flat(1);
var result = resultTop + '<br/>' + resultBottom;
return result;
}
Here's a fiddle.
One workaround is to print a unicode character that draws a line on top. Turns out there is such a character: the Upper One-eighth Block
It's "\u2594" in unicode escape or ▔ as HTML entity or you can simply copy/paste the literal character from the example below:
____/▔▔▔▔\____/▔▔\___
No errors in the console are present, though the function does not seem to be adding the dashes like it is intended to do. Also, the code creates formatting problems on the site meaning something is wrong with this.
Code:
$('#Inventory_accountNumber').blur(function(){
var accounts = $(this).val;
var accountsNum = [];
accountNum = accounts.split(",");
for(var i=0;i<accountNum.length;i++) {
var newstr = '';
if(accountNum[i].length == 24) {
newstr += accountNum[i].substring(0,4) + '-';
newstr += accountNum[i].substring(4,7) + '-';
newstr += accountNum[i].substring(7,10) + '-';
newstr += accountNum[i].substring(10,14) + '-';
newstr += accountNum[i].substring(14,20) + '-';
newstr += accountNum[i].substring(20,24) + '-';
newstr += '0000-000';
accountNum[i] = newstr;
}
else if(accountNum[i].length == 32) {
newstr += accountNum[i].substring(0,4) + '-'
; newstr += accountNum[i].substring(4,7) + '-';
newstr += accountNum[i].substring(7,10) + '-';
newstr += accountNum[i].substring(10,14) + '-';
newstr += accountNum[i].substring(14,20) + '-';
newstr += accountNum[i].substring(20,24) + '-';
newstr += '0000-000';
accountNum[i] = newstr;
}
}
accountNum.join(',');
$(this).val = accountNum;
});
JSFiddle
This is your culprit:
var accounts = $(this).val;
That should read:
var accounts = $(this).val();
What you have there is a function reference, not the value of the function's return statement.
var accounts = $(this).val();
or
var accounts = $(this);
accountNum = accounts.val().split(",");
If you try to debug or print in your console.. an inputselector.val prints out the whole function
Also, down below
$(this).val = accountNum; is the wrong way of setting the value, use $(this).val(accountNum);
Admittedly not a js expert. - How can I remove the trailing <br> on the last element? Feel free to comment on the general approach and make comments or suggestions. Thanks!!
$(document).ready(function() {
$.getJSON("{% url "relationship_sidebar_ajax" app_label=app_label model=model object_id=object.id %}", function(data) {
var str = ""
for (var item in data) {
var itemData = data[item];
str += '<dt>' + item + '</dt>';
for (idata in itemData) {
str += '<dd>' + itemData[idata].href;
if (itemData[idata].is_owned) {
str += ' <i class="icon-lock"></i>';
}
str += ' ' + data[item][idata].add_href + '</dd>';
}
str += '<br />'
}
$('#relations').append(str)
});
})
Use an array to hold the lines, and then join them with <br/> at the end.
$(document).ready(function() {
$.getJSON("{% url "relationship_sidebar_ajax" app_label=app_label model=model object_id=object.id %}", function(data) {
var arr = []
for (var item in data) {
var itemData = data[item];
var str = '<dt>' + item + '</dt>';
for (idata in itemData) {
str += '<dd>' + itemData[idata].href;
if (itemData[idata].is_owned) {
str += ' <i class="icon-lock"></i>';
}
str += ' ' + data[item][idata].add_href + '</dd>';
}
arr.push(str);
}
$('#relations').append(arr.join('<br />'));
});
})
Well, the last five characters of your string will always be <br /> so you could always just append str.substring(0, str.length - 5). It might be preferrable to wrap the dt and subsequent dd elements in a div.
if you want to remove the br tag in the beigining of string this would be helpful.
var str = "<br />Some string";
var regex = /^(<br\/>|<br \/>)/;
alert(str.replace(regex,""));