What I want to do in javascript is generate a random "code" based on text already entered in a field in a form.
What I have is a form, with a text input: name="youname"
Then, below this I have an input field: name="generated_ref"
What I would like to do, it when the user clicks on the "Generated Ref" field, is populate it with a ref, of 3 letters and 4 numbers.
Below is what I have already, but it used a-z rather than the data entered into the text field above
function makeref()
{
oFormObject = document.forms['newuser'];
oFormElement = oFormObject.elements["user[generated_ref]"];
var Stamp = new Date()
var hours = Stamp.getHours()
var mins = Stamp.getMinutes()
var text = "";
var possible = "abcdefghijklmnopqrstuvwxyz";
for( var i=0; i < 3; i++ ) //only allow 3 letters
text += possible.charAt(Math.floor(Math.random() * possible.length));
oFormObject.elements["user[generated_ref]"].value = text + hours + mins;
}
You can see in the above code, I generate 3 letters from a-z and 4 numbers from the hour and minute of the current time.
What I want to do, is replace var possible = "abcdefghijklmnopqrstuvwxyz"; with the text enters in "Your Name"
Hope this makes sense!
Andrew
I haven't used javascript in a while, but I believe what you want is to take the input box and use:
var possible = inputbox.value
See if that works.
I'm a little confused though, because I don't see the code for a place to input the user text in there, though it might just be that I haven't used javascript in too long for me to recognize it.
Previous comment posted as answer:
document.getElementById("<field>").value
Related
I'm trying to build a PicoBlaze simulator in JavaScript into which the user enters the assembly code. I've tried to make an interface which displays the line numbers in the assembly code that the user enters and highlights the assembly code syntactically. However, the line numbering doesn't work correctly in some cases. If you click into the div with contenteditable that the user is supposed to type the assembly code in (called assemblyCode), and you press enter two times, it will claim there are four lines of code, even though there are just three of them. The JavaScript which controls the div left to it that displays the lines of code (called lineNumbers) is this:
function setUpLineNumbers() {
const assemblyCode = document.getElementById("assemblyCode").innerText;
const numberOfLines = Math.max(
(assemblyCode.match(/\n/g) || []).length,
1
);
let lineNumbersHTML = "";
for (let i = 1; i <= numberOfLines; i++)
lineNumbersHTML += i + ".<br/>";
document.getElementById("lineNumbers").innerHTML = lineNumbersHTML;
}
Can you figure out what is going on there?
It seems that the structure of the code panel is one <div> per line and some of the <div> contents can end with <br>. .innerText converts this to a string such that each <div> generates a \n and each <br> also generates a \n.
Rather than trying to count the number of \n, count the number of <div>.
Change your function to:
function setUpLineNumbers() {
const assemblyCode = document.getElementById("assemblyCode");
const numberOfLines = assembly.childNodes.length;
let lineNumbersHTML = "";
for (let i = 1; i <= numberOfLines; i++)
lineNumbersHTML += i + ".<br/>";
document.getElementById("lineNumbers").innerHTML = lineNumbersHTML;
}
I have a string - project description ( as part of an object ) coming from a user form submission that is shown on a page of a report. If the line numbers exceed 24 I want to show the rest of the string on a new page. My initial idea was to cut it based on characters but this can't be done precisely as if line breaks are made when submitting the form, the characters can't be calculated as we donĀ“t know if the line break was made in the middle of a line or the end or wherever. I don't know what could be the solution?
How can I cut a string based on number of lines?
This is what I have done so far:
function countLines (el) {
let projectDetails = $rootScope.report.description;
var el = document.getElementById(el);
var divHeight = el.offsetHeight
var lines = divHeight / 17;
//console.log("Lines counted: " + lines);
if(lines > 24) {
$scope.secondDescriptionPage = true;
$scope.projectDetailsTextFirstPart = // this should be calculated
//$scope.projectDetailsTextSecondPart = // this should be calculated )
}
}
With the -webkit-line-clamp CSS property you can cut text by a certain number of lines. See MDN for details. It will not work in IE11 however.
hi this is my first question, sorry if it is stupid but i stumble upon this code
function format(input){
var num = input.value.replace(/\./g,'');
if(!isNaN(num)){
num = num.toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{1})/g,'$1.');
num = num.split('').reverse().join('').replace(/^[\.]/,'');
input.value = num;
}
else{ alert('just numeric values please');
input.value = input.value.replace(/[^\d\.]*/g,'');
}
}
i don't really understand how it works, but basically it formats an input in real time to this format "9.9.9.9.9" but i want it to have it like this "9.9.9.9.9.". How can i add that last period?
thanks beforehand
If all you need to do is add the period to the end of the string, just do:
num + ".";
For your entire function, if you are taking a string like "12345" and just want to put a period after each number and at the end, then there are easier ways to do it than what you have:
text = text.replace(/(.)/g, '$1.');
Will do it.
input.value = num+'.';
or like this
var num = b.split('').reverse().join('').replace(/^[\.]/,'').replace(/$/, ".");
/$/ means end of the string
or like this
var num = b.split('').reverse().join('').replace(/^(.{1})(.+)/, '$2$1');
Take a look at this post:
Move n characters from front of string to the end
enjoy
I'd like to use jQuery to echo text as it is typed, into a text area below the input line, and as it does, put random pre-selected words on the end of that repeated data. Each time a new letter is typed as input, I'd like some other "random" word appended each of the 3 "repeats", kind of a jumble.
Input= "true blue"
TextArea =
true blue black<br/>
true blue car<br/>
true blue sock<br/>
If the input = "true blues"
TextArea =
true blues snake<br/>
true blues grass<br/>
true blues red<br/>
All new results because "s" was typed. (or as close to "new/random" as can be easily)
I'm going to have 200 words in an array, and with each key press I'd like the appended words to change (onkeyup?). If they can appear random or can be randomly picked from a larger list/file.
Input from the form is repeated for 3 lines in the text area, and 3 random words are also appended basically. Onkeypress echo input + random_word (x3).
Interesting challenge.
I've played with it for a couple of hours and have come up with a rudimentary, inelegant attempt - brute force.
FIDDLE
JS
var spacecount = 0;
var sumcodes = 0;
var wordarray = 0;
var randword = ['gould','horowitz','bach','scarlatti','handel','vivaldi','corelli','albinoni','allegri','pinnock',];
$(function(){
$(document).keyup(function(e){
var char1 = String.fromCharCode(e.keyCode);
$('#keycode').html(e.keyCode);
$('#charcode').html(char1);
$('#texthere').append(char1);
sumcodes = sumcodes + e.keyCode;
if (e.keyCode == 32)
{
spacecount=spacecount + 1;
$('#spacecount').html(spacecount);
}
if (spacecount > 2)
{
spacecount = 0;
wordarr = Math.floor(Math.random() * 10) + 1
$('#texthere').append(randword[wordarr] + ' ');
$('#sumcodes').html(sumcodes);
sumcodes = 0;
}
});
});
The random number generator is not that robust. I tried to relate it to the sum of the ASCII character codes, but was unsuccessful (I'll play a bit more).
I'm trying to use Javascript to parse text that has been entered in a text box - which would combine a variety of user-generated variables to create random activities. This might make more sense looking at the example. Some example input might be:
Activity
#Home
#Out
#Home
Read #book for #time
Clean up #room for #time
#Out
Eat at at #restaurant
#book
Enders Game
Lord of the Rings
#room
bedroom
garage
basement
#restaurant
Red Robin
McDonalds
Starbucks
#time
15 minutes
30 minutes
45 minutes
60 minutes
Pound/and signs would be used to separate different categories.
The output would then be determined randomly from the given input, for example:
"Eat at Starbucks."
or
"Read Lord of the Rings for 60 minutes."
or
"Clean garage for 30 minutes."
Is this doable? It seems like it should be fairly straightforward, but I do not know where to start. Any suggestions?
Thanks,
Albert
How about:
var myText = ...; // Input text
var lines = myText.split("\n");
var numLines = lines.length;
var i;
var currentSection;
var sections = Array();
var phrases = Array();
// parse phrases
for (i = 0; i < numLines; i++) {
var line = lines[i];
if (line.indexOf('#') == 1) {
// start of e.g. time section, handled in nex loop
break;
} else {
// phrase
phrase.push(line);
}
}
// parse sections
for ( ; i < numLines; i++) {
var line = lines[i];
if (line.indexOf('#') == 1) {
// start of next section, handled in nex loop
currentSection = line;
sections[currentSection] = new Array();
} else {
// add section entry
sections[currentSection].push(line);
}
}
It's not too sophisticated, but does the job. Didn't test it though, but something like this should work. And where is the fun if this'd just work ;D
No issue at all. Split the textbox value into an array based on line break characters. Then, go through the array one element at a time, sorting the values into variables for each section. Finally, use JavaScript's random number generator to randomly determine which of each group to select. Output to the user by assigning the value to an HTML element.