If you have any in a list item like 0123 then it will show abcd. again if it 5462 then will show fegc. my html code is below:
<div class="myList">
- 0123
- 5462
- 0542
</div>
Converted output will be
//////////
<div class="myList">
- abcd
- fegb
- afec
</div>
Is it possible to create using javascript?
Try something like this
var str = '0123';
var new_str = '';
for (var i = 0, len = str.length; i < len; i++) {
new_str += String.fromCharCode(97 + parseInt(str[i]));
}
alert(new_str)
The following will take the text from the element and change it accordingly while skipping non integer characters
$('.myList').text(convertNumbersToLetters($('.myList').text()))
function convertNumbersToLetters(numbers) {
new_str = '';
for (var i = 0; i < numbers.length; i++) {
new_str += isInt(numbers[i]) ? String.fromCharCode(97 + parseInt(numbers[i])) : numbers[i];
}
return new_str;
}
function isInt(n) {
return !isNaN(parseInt(n));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myList">- 0123 - 5462 - 0542</div>
This is specific to your question.
alpha = ['a','b','c','d','e','f','g','h','i','j'];
function toNewString(input){
inputArray = input.split('');
for(i=0;i<inputArray.length; i++){
if(!isNaN(inputArray[i]))
inputArray[i] = alpha[inputArray[i]];
}
return inputArray.join('');
}
$('.myList').html(toNewString($('.myList').html()));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="myList">
- 0123
- 5462
- 0542
</div>
Do it like this (#DGS edited)
var str = ['0123', '456'];
var new_str = '';
for(var j=0; j < str.length; j++)
{
for (var i = 0; i < str[j].length; i++) {
new_str += String.fromCharCode(97 + parseInt(str[j][i]));
}
alert(new_str);
new_str = '';
}
Related
I would like to know how to append to the DOM just once after these nested loops.
Also, the variable letters is dynamic, so I would need to 'reset' my appended grid when a new string is passed to letters
let letters = "abcdefghijkl"
for (let i = 0; i < letters.length; i++) {
var musicRowID = `${letters.charAt(i)}01`;
$("#music-grid").append(`<div id="music-row-${musicRowID}" class="row no-gutters"></div>`);
for (let j = 1; j <= 12; j++) {
var columnID = letters.charAt(i) + (j < 10 ? "0" : "") + j;
$(`#music-row-${musicRowID}`).append(
`<div class="col-1"><button id="${columnID}" class="btn bar song">${columnID.toUpperCase()}</button></div>`
);
}
}
Thank you in advance!
EDIT
After the answer from T.J. Crowder I tried to incorporate my code to be able to populate my grid from the inputs, but when I unselect one of the inputs, that row isn't cleared.
let letters = 'abcdefghijkl';
let html = "";
$(".list-checkbox-item").change(function() {
let chosenLetters = $(this).val();
if ($(this).is(":checked")) {
arrayOfChoices.push(chosenLetters);
} else {
arrayOfChoices.splice($.inArray(chosenLetters, arrayOfChoices), 1);
}
letters = arrayOfChoices.sort().join(""); // Gives me a string with chosen letters ordered alphabetically
console.log(
`This is my string in var 'letters' ordered alphabetically (Need to clear grid after each instantiation or append after the loop): %c${letters}`,
"color: red; font-weight: bold; font-size: 16px"
);
for (let i = 0; i < letters.length; i++) {
var musicRowID = `${letters.charAt(i)}01`;
html += `<div id="music-row-${musicRowID}" class="row no-gutters">`; // *** No `</div>` yet
for (let j = 1; j <= 12; j++) {
var columnID = letters.charAt(i) + (j < 10 ? "0" : "") + j;
html += `<div class="col-1"><button id="${columnID}" class="btn bar song">${columnID.toUpperCase()}</button></div>`;
}
html += "</div>";
}
$("#music-grid").html(html);
});
What am I doing wrong?
Assuming #music-grid is empty before you run this code the first time, build up the HTML in a string and then use html() to replace the contents of #music-grid rather than appending to it:
let html = "";
for (let i = 0; i < letters.length; i++) {
var musicRowID = `${letters.charAt(i)}01`;
html += `<div id="music-row-${musicRowID}" class="row no-gutters">`; // *** No `</div>` yet
for (let j = 1; j <= 12; j++) {
var columnID = letters.charAt(i) + (j < 10 ? "0" : "") + j;
html +=
`<div class="col-1"><button id="${columnID}" class="btn bar song">${columnID.toUpperCase()}</button></div>`;
}
html += "</div>";
}
$("#music-grid").html(html);
You also see people building up the HTML in an array and using array.join("") at the end to get a single string, but with modern JavaScript engines it's really a wash either way...
I'm bit new to JavaScript, I'm trying to replacing the array element using regex that matches the string, here is a code which I tried
<button onclick="myFunction()">ClickHere</button>
<p id="demo"></p>
<script>
function myFunction() {
var abc = ["deno", "eno","pqr","lenovo"];
var i,text;
for(i = 0; i < abc.length; i++) {
text += abc[i].replace(/no/i, "po");
document.getElementById("demo").innerHTML = text;
}
}
</script>
I want to replace array element with "po" wherever it encounters "no" in the array element string.
This is what I expect:
abc["depo","epo","pqr","lepovo"]
You can do this for every element:
for(var i=0; i < abc.length; i++) {
abc[i] = abc[i].replace('no', 'po');
}
or using one line
abc = abc.map(function(x){return x.replace('no', 'po');});
or using one line with "arrow functions":
abc = abc.map(x => x.replace('no', 'po'));
After you changed the array, you can convert it to a string using:
var text = 'abc[';
for ( var i = 0 ; i < abc.length ; i++ ) {
text+='\"'+abc[i]+'\"';
if ( i != abc.length - 1) {
text+=',';
}
}
text += ']';
Test:
function myFunction() {
var abc = ["deno", "eno","pqr","lenovo"];
abc = abc.map(x => x.replace('no', 'po')); // see other 2 alternatives above
var text = 'abc[';
for ( var i = 0 ; i < abc.length ; i++ ) {
text+='\"'+abc[i]+'\"';
if ( i != abc.length - 1) {
text+=',';
}
}
text += ']';
document.getElementById("demo").innerHTML = text;
}
<button onclick="myFunction()">ClickHere</button>
<p id="demo"></p>
var i, text;
for(i = 0; i < abc.length, i++) {
text += abc[i].replace("no", "po");
}
console.log(text);
There are three changes required in your code:
Initialiize text with empty string.Because it is undefined by default.
Change abc[i].length to abc.length.
Replace comma with a semicolon after abc[i].length in for loop.
var abc = ["deno", "eno","pqr","lenovo"];
var i;
var text = "";
for(i = 0; i < abc.length; i++) {
text += abc[i].replace("no", "po");
}
I am new to coding Javascript. I am trying to to shuffle list of names inputted on a textarea. The user selects the number of groups desired, and shuffle on click, then show the divided groups as output result. Below is my code but it is not working as it should be, pls help!
<script>
function ArrayToGroups(source, groups){
var groupList = [];
groupSize = Math.ceil(source.length/groups);
var queue = source;
for(var r = 0; r < groups; r++){
groupList.push(queue.splice(0,groupSize));
}
return groupList;
}
function textSpliter(splitText){
var textInput = document.getElementById("inputText").value;
var splitText = textInput.split(',');
var newList = [];
for(x = 0; x <= splitText.length; x++) {
var random = Math.floor(Math.random() * splitText.length);
var p = splitText[random];
newList.push(p);
splitText.splice(p,groupList);
}
for(var i = 0; i < newList.length; i++){
var s = newList[i];
document.getElementById('resInput').value += s + "\n" ;
}
return splitText;
}
</script>
Below is my input and output textareas
</head>
<body>
<form>
<textarea id="inputText" placeholder="text" rows="10" cols="40"></textarea>
<input type="number" name="number" max="6" value="1" id="groupNumber">
<textarea id="resInput" placeholder="text" rows="10" cols="40"></textarea>
<input type="button" name="Shuffle" value="shuffle" onclick="textSpliter()">
</form>
</body>
</html>
function shuffle() {
// Get list
// Example: element1, element 2, ele ment 3, ...
var list = document.getElementById("inputText").value.replace(/\s*,\s*/g, ",").split(",");
// Get number of groups
var n = parseInt(document.getElementById("groupNumber").value);
// Calculate number of elements per group
var m = Math.floor(list.length / n);
// Enought elements
if (n * m == list.length) {
// Create groups
var groups = new Array();
for (i = 0; i < n; i++) {
groups[i] = new Array();
for (j = 0; j < m; j++) {
// Random
rand = Math.floor(Math.random() * list.length);
// Add element to group
groups[i][j] = list[rand];
// Remove element to list
list.splice(rand, 1);
}
}
// Output
var text = "";
for (i = 0; i < n; i++) {
text += "Group " + (i + 1) + ": ";
for (j = 0; j < m; j++) {
if (j != 0) { text += ", "; }
text += groups[i][j];
}
text += "\n";
}
document.getElementById("resInput").value = text;
} else {
alert("Add more elements");
}
}
I rewrote your code. It's pretty self-explanatory.
FIDDLE
function textSpliter() {
var input = document.getElementById("inputText").value;
var names = input.split(",");
var groupSize = document.getElementById("groupNumber").value;
var groupCount = Math.ceil(names.length / groupSize);
var groups = [];
for (var i = 0; i < groupCount; i++) {
var group = [];
for (var j = 0; j < groupSize; j++) {
var random = Math.floor(Math.random() * names.length);
var name = names[random];
if (name != undefined) {
group.push(name);
names.splice(names.indexOf(name), 1);
}
}
group.sort();
groups.push(group);
}
printGroups(groups);
}
function printGroups(group) {
var output = document.getElementById("resInput");
output.value = "";
for (var i = 0; i < group.length; i++) {
var currentGroup = "";
for (var j = 0; j < group[i].length; j++) {
currentGroup = group[i].join(",");
}
output.value += currentGroup + "\r";
}
}
ES6 version ;-)
http://jsfiddle.net/dLgpny5z/1/
function textSpliter() {
var input = document.getElementById("inputText").value;
var names = input.replace(/\s*,\s*|\n/g, ",").split(",");
var groupSize = document.getElementById("groupNumber").value;
var groupCount = Math.ceil(names.length / groupSize);
var groups = [...Array(groupCount)].map(() => Array());
var i = 0
while (names.length > 0) {
var m = Math.floor(Math.random() * names.length);
groups[i].push(names[m]);
names.splice(m, 1);
i = (i >= groupCount - 1) ? 0 : i + 1
}
printGroups(groups);
}
function printGroups(groups) {
var output = document.getElementById("resInput");
output.value = groups.map(group => group.join(',')).join('\r');
}
I have a generic list
<div id="banner">
<div class="oneByOne_item top_offers">
<div class="top_offer_wrap">item1</div>
<div class="top_offer_wrap">item2</div>
<div class="top_offer_wrap">item3</div>
<div class="top_offer_wrap">item4</div>
<div class="top_offer_wrap">item5</div>
<div class="top_offer_wrap">item6</div>
</div>
</div>
But what I want to do is
<div id="banner">
<div class="oneByOne_item top_offers">
<div class="top_offer_wrap">item1</div>
<div class="top_offer_wrap">item2</div>
<div class="top_offer_wrap">item3</div>
</div>
<div class="oneByOne_item top_offers">
<div class="top_offer_wrap">item4</div>
<div class="top_offer_wrap">item5</div>
<div class="top_offer_wrap">item6</div>
</div>
</div>
I could use any advice as to the best way to deal with this situation.
If you remove the <div class="oneByOne_item top_offers"> in your HTML you can use the jQuery functions .slice() and .wrapAll() to add it again like so:
var div = $("#banner > div");
for(var i = 0; i < div.length; i+=3) {
div.slice(i, i+3).wrapAll("<div class='oneByOne_item top_offers'></div>");
}
Hope this helps.
Using pure javascript
function separate() {
var container = document.getElementById('banner');
var divElems = container.querySelectorAll(".top_offer_wrap");
var count = 0;
var newDiv = null;
for (var i = 3; i < divElems.length ; i++) {
if(count == 0) {
newDiv = document.createElement("div");
newDiv.className = 'oneByOne_item top_offers';
container.appendChild(newDiv);
}
var tempDiv = divElems[i];
tempDiv.parentNode.removeChild(tempDiv);
newDiv.appendChild(tempDiv);
count ++;
if(count == 3) {
count = 0;
}
}
}
Not tested though :)
It's not intelligent to do this with javascript. You should do this on the server-side.
If you really want to do it in javascript, you can use the following script:
var banner = document.getElementById('banner');
var children = banner.getElementsByClassName('oneByOne_item')[0].getElementsByTagName('div');
var output = "";
for( var i = 0; i < children.length; i += 3 ) {
var div = "<div class=\"oneByOne_item top_offers\">";
div += children[i].outerHTML;
if( i + 1 < children.length ) {
div += children[i+1].outerHTML;
}
if( i + 2 < children.length ) {
div += children[i+2].outerHTML;
}
div += "</div>";
output += div;
}
banner.innerHTML = output;
The code should be self-explenatory. I use getElementById, getElementsByClassName and getElementsByTagName to select the right element(s) to do the operations on.
Fiddle: http://jsfiddle.net/P95bQ/
you can use jQuery.
like this (already test):
var len = $('.top_offer_wrap').length,
length = len % 3 ? (len / 3) + 1 : len / 3,
html = '';
for(var i = 0; i < length; i++){
html += '<div class="oneByOne_item top_offers">';
for(var j = 1; j < 4 && i * 3 + j <= len; j++){
html += ' <div class="top_offer_wrap">item' + (i * 3 + j)+'</div>';
}
html += '<div>';
}
$('#banner').html(html);
I have a bit of an issue at the moment that I am hoping one of you can help me with. I have tried several things, and I just can't get it. I am trying to print a triangle of asterisks using JavaScript. The program is to ask the user for the amount of rows, and then the direction. I haven't even started with the direction yet because I can't get the rows to work. Odd thing is that I can get it to print out the triangle hard-coding the function call.
This is the JS file:
function myTriangle(){
var result = "";
var totalRows = document.getElementById('rows').value;
var direction = document.getElementById('UpOrDown').value;
for (var i = 1; i <= totalRows; i++){
document.writeln("count");
for (var j = 1; j <= 1; j++)
{
result += "*";
}
result += "<br/>";
}
return result;
}
var answer = myTriangle();
document.getElementById('myDiv').innerHTML = answer;
This is the HTML file:
<!DOCTYPE html>
<head>
<title>Lab 2</title>
<script src="scripts.js", "div.js"></script>
</head>
<body>
<form name="myForm">
<fieldset>
<legend>Input Fields</legend>
rows: <input type="text" id="rows" /><br>
direction: <input type="text" id="UpOrDown" /><br>
press: <input type="button" value="GO!" id="myButton"
onclick="myTriangle();"/>
</fieldset>
</form>
<div id="myDiv">
</div>
</body>
The output will be something like this:
*
**
***
****
*****
Generally there are four types of triangle -
1.)* 2.) *** 3.) * 4.) ***
** ** ** **
*** * *** *
Code for 1 -
var ast = [],
i, j = 4;
for (i = 0; i < j; i++) {
ast[i] = new Array(i + 2).join("*");
console.log(ast[i]);
}
Code for 2 -
var ast = [],
i, j = 4;
for (i = j-1; i >=0; i--) {
ast[i] = new Array(i + 2).join("*");
console.log(ast[i]);
}
Code for 3 -
var ast = [],
i, j = 4;
for (i = 0; i < j; i++) {
ast[i] = new Array(j - i).join(' ') + new Array(i + 2).join("*");
console.log(ast[i]);
}
Code for 4 -
var ast = [],
i, j = 4;
for (i = j-1; i >=0; i--) {
ast[i] = new Array(j - i).join(' ') + new Array(i + 2).join("*");
console.log(ast[i]);
}
To print asterisk in document rather than console -
document.getElementById('anyElement').innerHTML+=ast[i] + '<br />';
document.writeln will completely wipe the page unless it's called while the page is loading.
Therefore it will destroy myDiv, causing the getElementById to fail.
Furthermore, I'm not sure what you're trying to achieve with that <script> tag, but it looks like you need two of them.
EDIT: Oh, and this: for (var j = 1; j <= 1; j++) will only ever iterate once.
EDIT 2: Here's my implementation of a solution.
This isn't a valid script tag.
<script src="scripts.js", "div.js"></script>
You need to break it up into two tags:
<script src="scripts.js"></script>
<script src="div.js"></script>
This is my solution, it uses es2015 .replace() but there is a nice
polyfill for es5 as well here:
var output = document.getElementById('output');
function triangle (size) {
for (var i = 1; i <= size; i++) {
output.innerHTML += '*'.repeat(i) + '<br>';
}
}
triangle(2);
This is a solution in ES3/5
var output = document.getElementById('output');
function triangle(size) {
var allLines = '';
for (var i = 1; i <= size; i++) {
var oneLine = createLine(i);
allLines += oneLine;
}
return allLines;
}
function createLine(length) {
var aLine = '';
for (var j = 1; j <= length; j++) {
aLine += '*';
}
return aLine + "<br/>";
}
output.innerHTML += triangle(3);
<div id='output'></div>