How to insert data into an element without changing it using JavaScript | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How to insert data into an element without changing it using JavaScript

I want output like this: "L2 U B' R2 D2 U' R D U2 F'" https://code.sololearn.com/W4uEea72A3DW/?ref=app

26th Jan 2018, 9:02 AM
Demid Metelnikov
Demid Metelnikov - avatar
4 Answers
+ 3
Change $("#res").html("R"); to $("#res").append("R ");
26th Jan 2018, 9:28 AM
ThreeG
ThreeG - avatar
+ 3
Thx)
26th Jan 2018, 9:30 AM
Demid Metelnikov
Demid Metelnikov - avatar
+ 1
You can simplify your code, so your JS section could look like this: array = ["R ", "R' ", "R2 ", "L ", "L' ", "L2 ", "U ", "U' ", "U2 ", "F ", "F' ", "F2 ", "D ", "D' ", "D2 " ]; // array with elements $(function(){ $("#gen").click(function rand(){ arr_random=Math.floor(Math.random()*15); // generates random index of array $("#res").append(array[arr_random]); // appends element of array with random index }); }); It does the same thing.
26th Jan 2018, 10:09 AM
ThreeG
ThreeG - avatar
+ 1
Moreover, you can do this without jQuery, so you don't need to include jQuery file in head section, and you will need to apply onclick event to your button like this: <button id="gen" onclick="rand()"> And your JS section will look like this: array = ["R ", "R' ", "R2 ", "L ", "L' ", "L2 ", "U ", "U' ", "U2 ", "F ", "F' ", "F2 ", "D ", "D' ", "D2 "]; // array with elements function rand(){ arr_random=Math.floor(Math.random()*15); // generates random index of array res=document.getElementById("res"); res.innerHTML+=array[arr_random]; // a+=x means a=a+x }
26th Jan 2018, 10:13 AM
ThreeG
ThreeG - avatar