I want add a unique class for each new div after input, how is it in my code?
Add class for this: <div class="thing"></div>
DEMO: http://jsfiddle.net/wAwyR/2/ => please in here(field) typing a number for adding new input.
function unique() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
$('input').live("keyup", function () {
$('.lee').empty();
var $val = $(this).val();
for (var i = 0; i < $val; i++) {
$('.lee').append('<input type="text" name="hi" class="">div class="thing"></div>');
$('input[hi]').next('div').attr('class', unique())
}
});
var increment = 0;
function unique() {
return "u" + increment++;
}
can't that work?
Related
i want to write a short code i have multi contenteditable divs and i use a function to put the value of the div to a textarea please check with me
var myContentArr = ["myContent1", "myContent2", "myContent3", "myContent4", "myContent5", "myContent6"];
var hiddenArr = ["hidden1", "hidden2", "hidden3", "hidden4", "hidden5", "hidden6"];
function myFunction(){
for (var i = 0; i < hiddenArr.length; i++) {
document.getElementById(hiddenArr[i]).value =
for (var i = 0; i < myContentArr.length; i++) {
document.getElementById(myContentArr[i]).innerHTML
}
}
return true;
}
I have this piece of javascript and I need every element "title" to be colored with different randomized color. I accomplished colorize only the first one. It is possible? Thanks
var randomColor = Math.floor(Math.random()*16777215).toString(16);
document.getElementById('title').style.color = randomColor;
<div id="title"><a>TEXT1</a></div>...<div id="title"><a>TEXT2</a></div>...
Just invoke changeColor(); functions.
$(function(){
changeColor();
});
function changeColor() {
var paragraphs = document.getElementsByTagName("p");
for(var i = 0; i < paragraphs.length; i++)
{
var innerText = paragraphs[i].innerText;
var innerTextSplit = innerText.split("");
paragraphs[i].innerText = ""
for(var j = 0; j < innerTextSplit.length; j++) {
var randomColor =getRandomColor();
innerTextSplit[j] = '<span style="color: ' + randomColor + '">' + innerTextSplit[j] + '</span>';
paragraphs[i].innerHTML += innerTextSplit[j];
}
}
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>abcdefthuild</p>
<p>abcdefthuild</p>
<p>abcdefthuild</p>
<p>abcdefthuild</p>
<p>abcdefthuild</p>
As I already commented, you cannot use duplicate IDs, prefer using a class instead and modify your code accordingly.
var getElm = document.getElementsByClassName('title');
for(var i = 0, l = getElm.length; i < l; i++) {
var randomColor = Math.floor(Math.random() * 16777215).toString(16);
getElm[i].style.color = '#' + randomColor;
}
<div class="title"><a>TEXT1</a></div>
<div class="title"><a>TEXT2</a></div>
Some explanation of how the above code works:
I am using getElementsByClassName which will return me an array of elements you want to target, in this case, it's the ones with the class name of title. Then I loop them, generate a new random hex, and assign it to the looped element.
Make sure you don't forget to concatenate your hexcode with #
Use like this .without classname
using document.querySelectorAll().it will select the element.
Then applied each element with color using Array#forEach
And you are missing # in dom for adding color
document.querySelectorAll("div[id='title']").forEach(function(a){
var randomColor = Math.floor(Math.random()*16777215).toString(16);
a.style.color ='#'+randomColor;
})
<div id="title"><a>TEXT1</a></div>
<div id="title"><a>TEXT2</a></div>
<div id="title"><a>TEXT2</a></div>
<div id="title"><a>TEXT2</a></div>
<div id="title"><a>TEXT2</a></div>
<div id="title"><a>TEXT2</a></div>...
HTML
<div class="title"><a>TEXT1</a></div>...
<div class="title"><a>TEXT2</a></div>...
JS
var elements = document.getElementsByClassName('title');
var usedColors = {};
var getRandomColor = function() {
var randomColor = Math.floor(Math.random()*16777215).toString(16);
while(usedColors[randomColor] === 1) {
randomColor = Math.floor(Math.random()*16777215).toString(16);
}
usedColors[randomColor] = 1;
return randomColor;
};
for (var i = 0; i < elements.length; i++ ) {
var randomColor = getRandomColor();
elements[i].style.color = "#"+randomColor;
}
JSFIDDLE
https://jsfiddle.net/1cuwdLye/
Okay so basically what I'm trying to do is to display all the randomly generated strings on the page, after being saved in sessionStorage. So far, my createRandom function works fine on its own, but when I added the returnRandom function both stopped working. I appreciate any suggestions.
Here is the javascript:
function createRandom()
{
var text = "";
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i = 0; i < 5; i++ )
text += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
document.getElementById("randomstring").innerHTML= text;
sessionStorage.setItem(text, text);
returnRandom();
}
document.getElementById("button").addEventListener("click", createRandom, false);
// //returns session storage values
function returnRandom() {
var key = "";
var i = 0;
for (var i = 0, i <= sessionStorage.length - 1, i++) {
key = sessionStorage.key(i);
var item = sessionStorage.getItem(key);
document.getElementById("randomreturn").innerHTML += item;
}
}
And here is the html:
<h2 id="randomstring">Random</h2>
<div id="button">
<p class="buttontext">Click Me</p>
</div>
<h3 id="randomreturn"></h3>
Your for loop expression should have semicolons, not commas
for (var i = 0; i <= sessionStorage.length - 1; i++)
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');
}