I am trying to take user input in form of a lot of strings. I want to store them in an array, and the input should be seperated by line breaks.
It should be very much like this: https://www.random.org/lists/
I can not grasp where to being - can someone help? I am using JavaScript but any solutions using JS or jQuery would be great!
I have posted my JS. I want the var people from user input, instead of having to populate the array myself.
Thanks,
$(document).ready(function() {
$(".btn").on('click', function() {
var people = ["Markus Eriksson", "Leticia Hoshino", "Yemi Afolabi", "Eskil Fogelström", "Josefina Liedberg", "David Bjørn Bograd", "Tilda Dahlgren", "Damien Vignol", "Sofie Cousu", "Carolina Lindelöw", "Bilal Khan", "Louise Brandrup-Wognsen", "Emilia Lehto", "Albin Hagström",
"Victor Borg", "Anna Stella Lo-Ré", "Loucmane", "Angelica Ruth", "Victoria VL", "Johan Hellström", "Micke Skoglund", "Anna Unger", "Isaac Sennerholt", "Cyndie Léa Vintilescu", "Mahle Rakela Robin", "Louise Ek", "Ibrahim Bajwa", "Abodi Ismail",
"Alex Ashman", "Elin Grass Casalini", "Amanda Schultz", "Abenezer Abebe", "Julia Hoff", "Enny Hellsén", "Michel George", "Abdullahi Hussein", "Teodor Meurling", "Andrea Sami Mogren", "Thea Arpine Gasparyan", "Jakob Eberson"
];
var groupSize = $("input[name=checkListItem]").val();
var groups = [];
$(".group").remove();
// Randomizing function
Array.prototype.shuffle = function() {
var input = this;
for (var i = input.length - 1; i >= 0; i--) {
var randomIndex = Math.floor(Math.random() * (i + 1));
var itemAtIndex = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
return input;
};
people.shuffle();
// Split people into chunks and push new arrays into var groups
while (people.length > 0) {
chunks = people.splice(0, groupSize);
var chunksSpace = chunks.join(', ');
groups.push(chunksSpace);
}
// Append the groups into the DOM
$(document).ready(function() {
for (var i = 0; i < groups.length; i++) {
$('.all-groups').append("<div class='group'><p><span class='groupheader'>Group " + (i + 1) + "</span></br> " + groups[i] + "</p></div>");
}
});
});
});
Pure Javascript
document.getElementById("element_id").value.split("\n");
OR JQuery $("#element_id").val().split("\n");
For your example give your input id='people' and should work, also avoid extra line breaks by .replace(/\n+/g,"\n").
$(document).ready(function() {
// Randomizing function
Array.prototype.shuffle = function() {
var input = this;
for (var i = input.length - 1; i >= 0; i--) {
var randomIndex = Math.floor(Math.random() * (i + 1));
var itemAtIndex = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
return input;
};
$(".btn").on('click', function() {
var people = $("#people").val().replace(/\n+/g,"\n").split("\n");
var groupSize = $("input[name=checkListItem]").val();
var groups = [];
$(".group").remove();
people.shuffle();
// Split people into chunks and push new arrays into var groups
while (people.length > 0) {
chunks = people.splice(0, groupSize);
var chunksSpace = chunks.join(', ');
groups.push(chunksSpace);
}
// Append the groups into the DOM
$(document).ready(function() {
for (var i = 0; i < groups.length; i++) {
$('.all-groups').append("<div class='group'><p><span class='groupheader'>Group " + (i + 1) + "</span></br> " + groups[i] + "</p></div>");
}
});
});
});
var text = $('#total-number').text();
var eachLine = text.split('\n');
alert('Lines found: ' + eachLine.length);
for(var i = 0, l = eachLine.length; i < l; i++) {
alert('Line ' + (i+1) + ': ' + eachLine[i]);
}
Use split to split a multi line string into parts:
var textarea = document.querySelector("textarea");
textarea.addEventListener("change", function(e) {
console.log(textarea.value.split((/[\n\r]/g)));
});
<textarea></textarea>
Regex links:
\r
\n
Related
When a button is clicked i want the results in the array to be listed for example: John Smith 16, Jack Snow 10 etc..
I want to use a loop however the code in my loop is incorrect at the moment as when i click the button all i get is: [object Object].
Can someone provide a possible fix?
function begin() {
listresults();
();
}
var results1 = {name:"John Smith", score:16};
var results2 = {name:"Jack Sow", score:10};
var results3 = {name:"Tessa Flip", score:15};
var results = [results1, results2, results3];
function listresults() {
var text = "";
var total = 0;
var i;
for (i in results) {
text += results[i] + "<br>";
}
document.getElementById('message').innerHTML = text;
}
I would first check that the lengths of the 2 arrays are the same. Then iterate using a for loop:
final int timeLength = TIME.length;
if (timeLength != stat.size()) {
//something may not be right
}
for (int i = 0; i < timeLength; i++) {
System.out.println(time[i]+" "+stat.get(i));
}
You are pushing objects results1, results2, etc in the array 'results'.
So while iterating the array you should access the object properties as shown below:
function listresults() {
var text = "";
var total = 0;
var i;
for (i in results) {
text += results[i]['name'] + ' ' + results[i]['score'] + "<br>";
}
As you are appending objects instead of object values in the filed.
This is the proper way of accessing name and score from object which is returned when you are looping through your array of objects :
function begin() {
listresults();
();
}
var results1 = {name:"John Smith", score:16};
var results2 = {name:"Jack Sow", score:10};
var results3 = {name:"Tessa Flip", score:15};
var results = [results1, results2, results3];
function listresults() {
var text = "";
var total = 0;
for (var i=0; i < results.length; i++) {
text += results[i].name + " " + results[i].score + "<br>";
}
document.getElementById('message').innerHTML = text;
}
Here is an Jsfiddle example
Recommend you to use Array methods(map, join) instead of pure loops
function begin() {
listresults();
}
var results1 = {name:"John Smith", score:16};
var results2 = {name:"Jack Sow", score:10};
var results3 = {name:"Tessa Flip", score:15};
var results = [results1, results2, results3];
function listresults() {
document.getElementById('message').innerHTML =
results.map(function(item) {
return item.name + ' ' + item.score;
}).join('<br>');
document.getElementById('total').innerHTML =
results.map(function(item) {
return item.score;
}).reduce(function(sum, score) {
return sum + score;
}, 0);
}
<button onclick="begin()">begin</button>
<br />
<div id="message"></div>
<div>total: <span id="total">0</span></div>
Use Array.map() and Array.join()
var results1 = {name:"John Smith", score:16};
var results2 = {name:"Jack Sow", score:10};
var results3 = {name:"Tessa Flip", score:15};
var results = [results1, results2, results3];
var res = results.map(item => { return item.name+ " " +item.score });
console.log(res.join(", "));
I'm writing a program in JS for checking equal angles in GeoGebra.
This is my first JS code, I used c# formerly for game programming.
The code is:
var names = ggbApplet.getAllObjectNames();
var lines = new Set();
var angles = new Set();
var groups = new Set();
for(var i=0; i<names.length; i++)
{
if(getObjectType(names[i].e)==="line")
{
lines.add(names[i]);
}
}
for(var i=0;i<lines.size;i++)
{
for(var j=0;j<i;j++)
{
var angle = new Angle(i,j);
angles.add(angle);
}
}
for(var i=0;i<angles.size;i++)
{
var thisVal = angles.get(i).value;
var placed = false;
for(var j=0;j<groups.size;j++)
{
if(groups.get(j).get(0).value===thisVal)
{
groups.get(j).add(angles.get(i));
placed = true;
}
}
if(!placed)
{
var newGroup = new Set();
newGroup.add(angles.get(i));
groups.add(newGroup);
}
}
for(var i=0;i<groups.size;i++)
{
var list="";
for(var j=0;j<groups.get(i).size;j++)
{
list = list+groups.get(i).get(j).name;
if(j != groups.get(i).size-1)
{
list = list+",";
}
}
var comm1 = "Checkbox[angle_{"+groups.get(i).get(0).value+"},{"+list+"}]";
ggbApplet.evalCommand(comm1);
var comm2 = "SetValue[angle_{"+groups.get(i).get(0).value+"}+,0]";
ggbApplet.evalCommand(comm2);
}
(function Angle (i, j)
{
this.lineA = lines.get(i);
this.lineB = lines.get(j);
this.name = "angleA_"+i+"B_"+j;
var comm3 = "angleA_"+i+"B_"+j+" = Angle["+this.lineA+","+this.lineB+"]";
ggbApplet.evalCommand(comm3);
var val = ggbApplet.getValue(this.name);
if(val>180)
{val = val-180}
this.value = val;
ggbApplet.setVisible(name,false)
});
function Set {
var elm;
this.elements=elm;
this.size=0;
}
Set.prototype.get = new function(index)
{
return this.elements[index];
}
Set.prototype.add = new function(object)
{
this.elements[this.size]=object;
this.size = this.size+1;
}
It turned out that GeoGebra does not recognize Sets so I tried to make a Set function.
Basically it collects all lines into a set, calculates the angles between them, groups them and makes checkboxes to trigger visuals.
the GeoGebra functions can be called via ggbApplet and the original Workspace commands via ggbApplet.evalCommand(String) and the Workspace commands I used are the basic Checkbox, SetValue and Angle commands.
The syntax for GeoGebra commands are:
Checkbox[ <Caption>, <List> ]
SetValue[ <Boolean|Checkbox>, <0|1> ]
Angle[ <Line>, <Line> ]
Thank you for your help!
In short, the syntax error you're running to is because of these lines of code:
function Set {
and after fixing this, new function(index) / new function(object) will also cause problems.
This isn't valid JS, you're likely looking for this:
function Set() {
this.elements = [];
this.size = 0;
}
Set.prototype.get = function(index) {
return this.elements[index];
};
Set.prototype.add = function(object) {
this.elements[this.size] = object;
this.size = this.size + 1;
};
Notice no new before each function as well.
I'm not sure what you're trying to accomplish by creating this Set object though - it looks like a wrapper for holding an array and its size, similar to how something might be implemented in C. In JavaScript, arrays can be mutated freely without worrying about memory.
Here's an untested refactor that removes the use of Set in favour of native JavaScript capabilities (mostly mutable arrays):
var names = ggbApplet.getAllObjectNames();
var lines = [];
var angles = [];
var groups = [];
for (var i = 0; i < names.length; i++) {
if (getObjectType(names[i].e) === "line") {
lines.push(names[i]);
}
}
for (var i = 0; i < lines.length; i++) {
for (var j = 0; j < i; j++) {
angles.push(new Angle(i, j));
}
}
for (var i = 0; i < angles.length; i++) {
var thisVal = angles[i].value;
var placed = false;
for (var j = 0; j < groups.length; j++) {
if (groups[j][0].value === thisVal) {
groups[j].push(angles[i]);
placed = true;
}
}
if (!placed) {
groups.push([angles[i]]);
}
}
for (var i = 0; i < groups.length; i++) {
var list = "";
for (var j = 0; j < groups[i].length; j++) {
list += groups[i][j].name;
if (j != groups[i].length - 1) {
list += ",";
}
}
var comm1 = "Checkbox[angle_{" + groups[i][0].value + "},{" + list + "}]";
ggbApplet.evalCommand(comm1);
var comm2 = "SetValue[angle_{" + groups[i][0].value + "}+,0]";
ggbApplet.evalCommand(comm2);
}
function Angle(i, j) {
this.name = "angleA_" + i + "B_" + j;
var comm3 = "angleA_" + i + "B_" + j + " = Angle[" + lines[i] + "," + lines[j] + "]";
ggbApplet.evalCommand(comm3);
var val = ggbApplet.getValue(this.name);
if (val > 180) {
val -= 180;
}
this.value = val;
ggbApplet.setVisible(name, false);
}
Hopefully this helps!
Your function definition is missing the parameter list after the function name.
Also, you're initializing the elements property to an undefined value. You need to initialize it to an empty array, so that the add method can set elements of it.
function Set() {
this.elements=[];
this.size=0;
}
So i have this:
$('#chapters').filter(function() {
var volume_elms = $('.volume');
var chapter_elms = $('.chlist');
for (var i = 0, l = volume_elms.length; i < l; ++i) {
var elm = $(volume_elms[i]);
var celm = $(chapter_elms[i]);
var volume_name = elm.first().text();
var volume_id = elm.first().text().split('removeMe');
var vlist = {
id: volume_id,
name: volume_name,
chapters: []
};
for (var j = 0, ll = celm.children().length; j < ll; ++j) {
var chapter = $(celm.children()[j]);
var chapter_name = chapter.first().text().split('\r\n')[4].trim();
vlist.chapters.push({
name: chapter_name
});
}
json.volumes.push(vlist);
}
});
res.send(json);
And i want to remove some characters from volume_id and i know that .split('removeMe') removes that but it only removes it in that order and you can only use it once
So how can i remove multiple characters and also avoid it that it becomes an array (output is json)
You can use regex to find multiple matches, separated by '|' (or)
value.replace(/FilterMe|FilterMeToo/g, "");
You can replace multiple words Like
.filter('words', function() {
return function (value) {
return (!value) ? '' : value.replace('FilterMe', '').replace('FilterMeTwo', '').replace('FilterMeThree', '');
};
});
var select = [];
for (var i = 0; i < nameslots; i += 1) {
select[i] = this.value;
}
This is an extract of my code. I want to generate a list of variables (select1, select2, etc. depending on the length of nameslots in the for.
This doesn't seem to be working. How can I achieve this? If you require the full code I can post it.
EDIT: full code for this specific function.
//name and time slots
function gennametime() {
document.getElementById('slots').innerHTML = '';
var namelist = editnamebox.children, slotnameHtml = '', optionlist;
nameslots = document.getElementById('setpresentslots').value;
for (var f = 0; f < namelist.length; f += 1) {
slotnameHtml += '<option>'
+ namelist[f].children[0].value
+ '</option>';
};
var select = [];
for (var i = 0; i < nameslots; i += 1) {
var slotname = document.createElement('select'),
slottime = document.createElement('select'),
slotlist = document.createElement('li');
slotname.id = 'personname' + i;
slottime.id = 'persontime' + i;
slottime.className = 'persontime';
slotname.innerHTML = slotnameHtml;
slottime.innerHTML = '<optgroup><option value="1">00:01</option><option value="2">00:02</option><option value="3">00:03</option><option value="4">00:04</option><option value="5">00:05</option><option value="6">00:06</option><option value="7">00:07</option><option value="8">00:08</option><option value="9">00:09</option><option value="10">00:10</option><option value="15">00:15</option><option value="20">00:20</option><option value="25">00:25</option><option value="30">00:30</option><option value="35">00:35</option><option value="40">00:40</option><option value="45">00:45</option><option value="50">00:50</option><option value="55">00:55</option><option value="60">1:00</option><option value="75">1:15</option><option value="90">1:30</option><option value="105">1:45</option><option value="120">2:00</option></optgroup>';
slotlist.appendChild(slotname);
slotlist.appendChild(slottime);
document.getElementById('slots').appendChild(slotlist);
(function (slottime) {
slottime.addEventListener("change", function () {
select[i] = this.value;
});
})(slottime);
}
}
You'll have to close in the iterator as well in that IIFE
(function (slottime, j) {
slottime.addEventListener("change", function () {
select[j] = this.value;
});
})(slottime, i);
and it's only updated when the element actually change
The cool thing about JavaScript arrays is that you can add things to them after the fact.
var select = [];
for(var i = 0; i < nameSlots; i++) {
var newValue = this.value;
// Push appends the new value to the end of the array.
select.push(newValue);
}
Hey guys i need some code that will split an array that holds a string which is an item and amount with the delimiter being the (:). (eg. Gas:30 )
loading the elements from the transArray into the values of hmtl texboxes for the item and amount fields
Please don't be to harsh with the comments this is my first language for a type-language.
Any help is appreciated!
var load = function ()
{
mySetArray(); //Fills the transArray randomly with 1-4 items
var item = '';
var amount = '';
for ( i=1; i<=transArray.length; i++)
{
item = 'item' + i;
amount = 'amount' + i;
transArray.split(":");
}
}
var mySetArray = function ()
{
var myRandom = Math.floor((Math.random() * 100) / 25) + 1; //a number between 1 and 4
transArray = new Array(); //Resets the Array to empty
if (myRandom == 1)
{
transArray[0] = "Food:200";
}
if (myRandom == 2)
{
transArray[0] = "Food:200";
transArray[1] = "Toys:700";
}
if (myRandom == 3)
{
transArray[0] = "Food:200";
transArray[1] = "Toys:700";
transArray[2] = "Mortgage:1800";
}
if (myRandom == 4)
{
transArray[0] = "Food:200";
transArray[1] = "Toys:700";
transArray[2] = "Mortgage:1800";
transArray[3] = "Cable:130";
}
}
window.onload = function ()
{
$("load").onclick = load;
}
To split an array, such as:
transArray[0] = "Food:200";
Just use split:
var newArray = transArray[0].split(':');
// newArray[0] = 'Food', newArray[1] = '200'
change:
for ( i=1; i<=transArray.length; i++) {
item = 'item' + i;
amount = 'amount' + i;
transArray.split(":");
}
to
for ( i=1; i<=transArray.length; i++) {
item = 'item' + i;
amount = 'amount' + i;
var splitted = transArray[i].split(":"); <-- split each item in transArray
console.log(splitted);
}
Here transArray is an array. You should use split on it's values i.e transArray[i].split(":");
So update your code like this :
for ( i=1; i<=transArray.length; i++)
{
item = 'item' + i;
amount = 'amount' + i;
var splittedData = transArray[i].split(":");
// It will give Item in 0th index and amount in 1st field.
}
var arr = new Array();
arr[0] = "Gas:200";
var newArr = arr[0].split(':');
JSFIDDLE DEMO
Call load function where ever you want or as it is (as i have done)
function load()
{
transArray = mySetArray(); //Fills the transArray randomly with 1-4 items
var item = '';
var amount = '';
for ( i=0; i<=transArray.length; i++)
{
ar = transArray[i].split(":");
alert((i+1)+" Item="+ar[0] + " Amount="+ ar[1]); // You ca use it in your own way
}
}
load();
function mySetArray()
{
var myRandom = Math.floor((Math.random() * 100) / 25) + 1; //a number between 1 and 4
transArray = new Array(); //Resets the Array to empty
if (myRandom == 1)
{
transArray.push("Food:200");
}
if (myRandom == 2)
{
transArray.push("Food:200");
transArray.push("Toys:700");
}
if (myRandom == 3)
{
transArray.push("Food:200");
transArray.push("Toys:700");
transArray.push("Mortgage:1800");
}
if (myRandom == 4)
{
transArray.push("Food:200");
transArray.push("Toys:700");
transArray.push("Mortgage:1800");
transArray.push("Cable:130");
}
return transArray;
}