Sort User Input and Print It - javascript

I have this problem that I've been working on for a few hours with no luck. I'm supposed to write JavaScript code that prompts the user to enter 3 names (one at a time). The program should sort and display the names on different lines in ascending order.
I can get the program to prompt the user to enter the names but having difficulty sorting them and displaying them correctly.
<html>
<head>
<title>Day 3 - Example 1</title>
</head
<body>
<center>
<script language="javascript">
var na1,na2,na3;
na1=prompt("Enter your first name:","");
na2=prompt("Enter your second name:","");
na3=prompt("Enter your third name","");
var na1_na2 = compare(na1, na2);
var na1_na3 = compare(na1, na3);
var na2_na3 = compare(na2, na3);
var first, second, third;
if (na1_na2 === -1) {
if (na1_na3 === -1) {
first = na1;
if (na2_na3 === -1) {
second = na2;
third = na3;
} else {
second = na3;
third = na2;
}
} else {
first = na3
second = na1;
third = na2;
}
} else {
}
function compare(name1, name2) {
name1 = name1.toLowerCase();
name2 = name2.toLowerCase();
if (name1 === name2) return 0;
var lengthOfShorterName = Math.min(name1.length, name2.length)
for (var i = 0; i < lengthOfShorterName; i++) {
if (name1.charAt(i) > name2.charAt(i)) return 1;
if (name1.charAt(i) < name2.charAt(i)) return -1;
}
if (name1.lenght < name2.length) return -1;
return 1;
}
</script>
</center>
</body>
</html>

Just put the names into an array and use Array.sort to order them.
// Create a new, empty array
var names = [];
// Prompt for the names and put each into the array:
names.push(prompt("Enter your first name:",""));
names.push(prompt("Enter your middle name:",""));
names.push(prompt("Enter your last name:",""));
// Sort the names:
names.sort();
// Print the results:
names.forEach(function(value){
console.log(value);
});

Related

Javascript - a problem with a two-step text input word conversion

Here I am making a word conversion tool which changes a certain word X into Y, or X to Y to Z by using javascript.
Progress: HERE
Here is the entire javascript:
var conversion = {
"one":"two",
};
var conversion2 = {
"two":"three",
};
var maxLength = Object.keys(conversion)
.reduce((a, b) => a.length > b.length ? a : b)
.length;
function convert (text) {
var converted = "";
var cur = 0;
while (cur < text.length) {
var testedPhoneme;
var symbol = undefined;
for (var length = maxLength; length > 0; length --) {
testedPhoneme = text.substr(cur, length);
if (conversion[testedPhoneme]) {
symbol = conversion[testedPhoneme];
break; // stop the loop
}
}
if (symbol) {
converted += symbol;
cur += testedPhoneme.length;
}
else {
converted += text[cur]
cur++;
}
}
return converted
}
var maxLength2 = Object.keys(conversion2)
.reduce((a, b) => a.length > b.length ? a : b)
.length;
function convert2 (text) {
var converted2 = "";
var cur2 = 0;
while (cur2 < text.length) {
var testedPhoneme2;
var symbol2 = undefined;
for (var length = maxLength2; length > 0; length --) {
testedPhoneme2 = text.substr(cur2, length);
if (conversion2[testedPhoneme2]) {
symbol2 = conversion2[testedPhoneme2];
break; // stop the loop
}
}
if (symbol2) {
converted2 += symbol2;
cur2 += testedPhoneme2.length;
}
else {
converted2 += text[cur2]
cur2++;
}
}
return converted2
}
function onInputTextChange(txt) {
var outputTextareaElem = document.getElementById("output_textarea");
var div = document.createElement("div");
var outputHtmlEntities = convert(txt);
div.innerHTML = outputHtmlEntities;
outputTextareaElem.value = div.innerText;
}
function onOutputTextChange(txt) {
var outputTextareaElem2 = document.getElementById("output_textarea2");
var div = document.createElement("div");
var outputHtmlEntities2 = convert2(txt);
div.innerHTML = outputHtmlEntities2;
outputTextareaElem2.value = div.innerText;
}
In the page that I made so far, there are three <textarea>s; Input, Output and Output2.
Currently, thanks to this piece of code;
var conversion = {
"one":"two",
};
var conversion2 = {
"two":"three",
};
If one is typed into Input, Output renders two. If two is manually typed into Output, three gets rendered in Output2.
Here is the problem, I want to render three in Output2 only through typing one into Input, but a direct two-step conversion seems unavailable yet. In other words, Input > Output (one > two) and Output > Output2 (two > three) conversion is available, but Input > Output > Output2 (one > two > three) is unavailable.
What needs to be done to solve this? Any help would be appreciated.
Ok, not exactly what you asked, but I could do something that works
Here is the example : https://jsfiddle.net/alias_gui3/8knw57u0/94/
how to use it :
to add new characters OR new languages/scripts
just complete the dictionnary :
var dictionnary = [
{
latin: "u",
japanese: "う",
emoji: "👋"
// add any script for every characters
},{
latin: "ku",
japanese: "く",
emoji: "👀"
},{
latin: "tsu",
japanese: "つ",
emoji: "🤖"
}
// add any character with the same format
]
to add new textareas :
give your textarea a recognizable id (eg. id="cyrillic")
then connect your textarea with this method:
// connect your textareas below !!
addTextArea(
document.querySelector("#latin"),
"latin"
);
addTextArea(
document.querySelector("#japanese"),
"japanese"
);
addTextArea(
document.querySelector("#emoji"),
"emoji"
);
// add new textarea with a new language here
then all the connections are done, you can edit all your textareas, if they recognise a character they will translate it in all the other textareas
full code
var dictionnary = [
{
latin: "u",
japanese: "う",
emoji: "👋"
// add any script for every characters
},{
latin: "ku",
japanese: "く",
emoji: "👀"
},{
latin: "tsu",
japanese: "つ",
emoji: "🤖"
}
// add any character with the same format
]
// calculate the max length for each language :
var max = {}
dictionnary.forEach(
char => {
Object.keys(char).forEach(script => {
max[script] = max[script]
? char[script].length > max[script]
? char[script].length
: max[script]
: char[script].length
})
}
)// now max contains the maximum length of sequence
// for each language
function findSymbol (
originSymbol,
originScript,
destinationScript
) {
for (var i = 0; i < dictionnary.length; i++) {
var char = dictionnary[i];
if (char[originScript] === originSymbol) {
return char[destinationScript]
}
}
return false // if not found
}
function translate (
text,
originScript,
destinationScript
) {
var cur = 0;
var translated = "";
var maxLength = max[originScript]
while (cur < text.length) {
var testedPhoneme;
var symbol = false;
for (var length=maxLength; length > 0; length--) {
testedPhoneme = text.substr(cur, length);
symbol = findSymbol(
testedPhoneme,
originScript,
destinationScript
)
if (symbol) {
break; // stop the loop
}
}
if (symbol) {
translated += symbol;
cur += testedPhoneme.length;
}
else {
translated += text[cur];
cur++;
}
}
return translated
}
var textareas = []; // the list of your textareas
function addTextArea(element, originScript) {
textareas.push({
element: element,
script: originScript
})
element.addEventListener("input", function (e) {
signalTextChanged(element, originScript)
});
}
function signalTextChanged (
originElement,
originScript
) {
var originText = originElement.value;
textareas.forEach(function (textarea) {
if (textarea.element !== originElement) {
var translated = translate(
originText,
originScript,
textarea.script
)
textarea.element.value = translated;
}
})
}
// connect your textareas below !!
addTextArea(
document.querySelector("#latin"),
"latin"
);
addTextArea(
document.querySelector("#japanese"),
"japanese"
);
addTextArea(
document.querySelector("#emoji"),
"emoji"
);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
</script>
</head>
<body>
<center>
<h1>Latin to foreign script converter 3</h1>
<p>type in u, ku, tsu in the FIRST panel</p>
<textarea
id="latin"
autofocus=""
placeholder="type text in latin ! (u ku or tsu)"
rows="10"
style="width:300px"></textarea>
<textarea
id="japanese"
rows="10"
placeholder="type text in japanese !"
style="width:300px"></textarea>
<textarea
id="emoji"
rows="10"
placeholder="type text in emojis !!"
style="width:300px"></textarea>
</center>
</center>
</body>
</html>
I'm not sure if I fully understand what you're trying to achieve here
There are some duplications in your code, what if you'll have 10 fields for output, will you create a special function for each of them?
Try to simplify things.
One way would be to loop through all of your lists as follows:
Put all your conversation in a list
var lists = [conversion, conversion2];
Add isInNextList function to check if your text is a key in the next list
function isInNextList(index, key) {
if (lists.length < index) {
return false;
}
return Object.keys(lists[index]).includes(key);
}
change your onInputTextChange function as follow:
function onInputTextChange(txt) {
var index = 0;
var text = txt;
while (isInNextList(index, text)) {
var outputTextareaElem = document.getElementById(
'output_textarea_' + index
);
var div = document.createElement('div');
text = lists[index][text]; //next key
index++;
div.innerHTML = text;
outputTextareaElem.value = div.innerText;
}
}
change your output textarea's ids to contain the index
id="output_textarea_0"
id="output_textarea_1"
There are other improvements that can be made like:
Creating the output fields dynamically,
Clear output fields etc.

Javascript For Loop iteration multiple inputs number-limits

On a javascript homework assignment for my javascript class, the assignment requires a ".js" for loop iteration to list the names of the pets a user inputs (3 is the limit).
There are three horizontally spaced text-input boxes and regardless of what text boxes the user inputs pet names into, the "message" (id) output below the submit button will display pets' names inputted up to the limit imposed by the user (<= 3). Once the pets' names are inputted and submit button clicked, the page will display the pets' names starting from the left most text box the user has inputted in and going towards the right, until the user's chosen input limitation (<= 3) has reached its limit; therefore, if a user selects 2 as the limitation, only the left-most text boxes with pet names inputted will be displayed below the submit button.
So far I have tried referring to the pet id's and pet names as memberid ('pet' + 'cntr'), membername, and together in the for loop iteration they are given the id of members += membered + membername;
if (myNumPets == '' || myNumPets > 3) {
$('numpets_error').innerHTML = " Please enter the number of
pets you have ";
myTruth = true;
} else {
if (myNumPets < '4') {
$('numpets_error').innerHTML = "";
myTruth = false;
}
}
if (myNumPets == 0) {
myNumPetsEntered = 0;
} else {
if (myNumPets == 1) {
myNumPetsEntered = 1;
} else {
if (myNumPets == 2) {
myNumPetsEntered = 2;
} else {
if (myNumPets == 3) {
myNumPetsEntered = 3;
}
}
}
}
cntr = '';
members = "";
for (cntr = 1; cntr <= myNumPetsEntered; cntr++) {
var memberid = "pet" + cntr;
console.log("MID " + memberid);
var membername = $(memberid).value;
members += memberid + membername;
}
$('message').innerHTML = members;
In this present code, when the number limitation is '1', only the first input box displays the inputted pet's name in the 'message' area below the submit button; however, I would like the inputted pet's name to appear there regardless of whether the inputted pet's name is in the first and left-most input box or one of the two that are to the right of it, and I want the same to be true of the other number limitations (2 and 3).
In your for loop you're just blindly grabbing the value of N text inputs, where N = myNumPetsEntered.
If myNumPetsEntered == 1 and you've typed the pet's name into the second input box, the loop will never see that value. You'll want to do some validation to make sure you've actually grabbed a value.
I don't know how involved this homework assignment is, but you might also be interested in validating whether or not the number of text boxes with values is at least equal to (or greater than) the number of pets names the user said they were going to input.
You can also clean up those nested if statements - assuming you've got logic in place preventing myNumPets from being a negative value, you could just use:
if (myNumPets <= 3) {
myNumPetsEntered = myNumPets;
}
For a start, this chunk code can be cleaned up a lot. The current logic is messy. Just imagine if the limit was 8 instead of 3.
if (myNumPets == 0) {
myNumPetsEntered = 0;
} else {
if (myNumPets == 1) {
myNumPetsEntered = 1;
} else {
if (myNumPets == 2) {
myNumPetsEntered = 2;
} else {
if (myNumPets == 3) {
myNumPetsEntered = 3;
}
}
}
}
My suggestion is to change to a range like this:
if ((myNumPets >= 0) && (myNumPets <= 3)) {
myNumPetsEntered = myNumPets;
}
To be honest, I am trying to make sense of the rest of the question. Think you are after something like the following:
var petCount = 0;
function petAdd(e) {
// stop the default button function
e.stopPropagation();
e.preventDefault();
// make sure only 3 pet names are entered.
if (petCount >= 3) {
alert("There is a max of 3 pet names");
return;
}
// do we have a new pet name?
var pet = document.getElementById("petNameInput");
if ((pet.value) && (pet.value.trim())) {
// we do have a name, add the name to the display
var displayName = document.getElementById("petNameDisplay");
// is it the first name?
if (petCount == 0) {
displayName.textContent = "My pet name(s) are: "+ pet.value.trim();
} else {
displayName.textContent += ", "+ pet.value.trim();
}
// keep track of the number of names
petCount++;
// clear the old name, ready for the next
pet.value = "";
}
// have we reached 3 names yet? if so, remove the input
if (petCount >= 3) {
var petRow = document.getElementById("petNameRow");
if (petRow) {
petRow.style.display = "none";
}
}
}
// add the method call when the button is pressed
window.onload = function() {
var d = document.getElementById("petAddButton");
if (d) {
d.addEventListener("click",petAdd,false);
}
}
What are you pets' names? <i>max of 3</i><br />
<div id="petNameRow">
<input type="text" id="petNameInput" placeholder="Enter a name here" />
<button id="petAddButton">Add pet</button>
</div>
<div id="petNameDisplay"></div>
Just an observation: This entire block is unnecessary. Why not just myNumPetsEntered = myNumPets? Or better yet, eliminate myNumPetsEntered altogether and use myNumPets in the loop?
if (myNumPets == 0) {
myNumPetsEntered = 0;
} else {
if (myNumPets == 1) {
myNumPetsEntered = 1;
} else {
if (myNumPets == 2) {
myNumPetsEntered = 2;
} else {
if (myNumPets == 3) {
myNumPetsEntered = 3;
}
}
}
}
Anyway. Here's one way to do it. Not sure it satisfies the requirements of your homework assignment, but then I shouldn't be doing your homework anyway.
function onButtonClick () {
// get the pet name inputs
const inputs = document.querySelectorAll('input[name=petname]');
// get the max names value
const max = document.querySelector('input[name=max]').value;
const names =
Array.from(inputs.values()) // convert the 'inputs' NodeList to an array
.map(i => i.value.trim()) // extract the value of each input and strip white space
.filter(Boolean) // filter out anything 'falsy' to eliminate empty values
.slice(0, max); // chop off anything beyond the max number
// string the values together, separated by a comma, and insert the result into the message box.
document.getElementById('message').innerHTML = names.join(', ');
}
label, button {
display: block;
}
input {
margin: 1rem 0;
}
<div>
<label>Number of Pets: <input type="number" min="1" max="3" name="max" value="3" /></label>
<input name="petname" />
<input name="petname" />
<input name="petname" />
<button onClick="onButtonClick()">Go.</button>
<div id="message" />
</div>

Combining Javascript Validation Functions

Alright I need help combining the two JavaScript Functions... I have tried multiple times and am not coming up with any luck. There almost identical functions except the fact that I change one number so that it thinks there different textboxes. I tried putting a variable in its place but then it always only validates to the ending number of the loop. Please show me how I may be able to combine these two functions. (Its my only work around and I can not find any examples similar to mine)
First:
<script type="text/javascript">
var QnoText = ['abc_1']; // add IDs here for questions with optional text input
function doSubmit_1() {
var ids_1 = '';
flag_1 = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids_1 = QnoText[i]+'Certificate_1';
if (CkStatus && document.getElementById(ids_1).value == '') {
alert('Please enter certificate number 1.');
document.getElementById(ids_1).focus();
flag_1 = false;
alert('return flag_1');
}
}
return flag_1;
}
</script>
Second:
<script type="text/javascript">
var QnoText = ['abc_2']; // add IDs here for questions with optional text input
function doSubmit_2() {
var ids_2 = '';
flag_2 = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids_2 = QnoText[i]+'Certificate_2';
if (CkStatus && document.getElementById(ids_2).value == '') {
alert('Please enter certificate number 2.');
document.getElementById(ids_2).focus();
flag_2 = false;
alert('return flag_2');
}
}
return flag_2;
}
</script>
You can pass a parameter in your function with the number of the textbox, like this:
var QnoText = ['abc_2']; // add IDs here for questions with optional text input
function doSubmit(n) {
var ids = '';
flag = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids = QnoText[i]+'Certificate_' + n;
if (CkStatus && document.getElementById(ids).value == '') {
alert('Please enter certificate number ' + n + '.');
document.getElementById(ids).focus();
flag = false;
alert('return flag_' + n);
}
}
return flag;
}
doSubmit(1); // for your submit 1
doSubmit(2); // for your submit 2
Is this what you wanted? because is not very clear. If is not feel free to explain.

unexpected output value from procedural code

I have this piece of javascript that won't work. It is supposed to take the user input and store it into the player input variable. Then, it splits the string that is returned and splits it into an array which is then converted into an object by the function oc(). Finally, the function analyzeUserInput finds keywords in the input object and places text into the paragraph element called text accordingly. In this example if the user types in slash, poke, slice, hack, etc and the word "sword" the paragraph element is supposed to say "you did 4 damage!" but it doesn't. here's the code:
<!DOCTYPE html>
<html>
<body>
<p>"oh no theres a monster whatchya gonna do?"</p>
<input id="plyrInput" type="text" />
<button onclick="analyzeUserInput()">Try it</button>
<p id="text"></p>
<script>
var plyrInput;
var plyrInputArray;
var plyrInputAnalysis;
function oc() {
plyrInputArray = plyrInput.split(' ');
var plyrInputObj = {};
for (var i = 0; i < plyrInputArray.length; ++i) {
plyrInputObj[plyrInputArray[i]] = ' ';
}
return plyrInputObj;
}
function analyzeUserInput() {
plyrInput = document.getElementById("plyrInput").text;
oc();
if (plyrInputAnalysis in oc(['use', 'slash', 'hack', 'wield', 'slice', 'sever', 'dismember', 'poke', 'cripple', 'maim', 'mutilate', 'chop', 'rend']) && plyrInputAnalysis in oc(['sword'])) {
document.getElementById("text").innerHTML = "You did 4 damage with your sword!";
}
}
</script>
</body>
</html>
var plyrInput;
var plyrInputArray;
var plyrInputAnalysis;
function oc() {
plyrInputArray = plyrInput.split(' ');
var plyrInputObj = {};
for (var i = 0; i < plyrInputArray.length; ++i) {
//storing these values in an object being blank is not really needed at all!
//plyrInputObj[plyrInputArray[i]] = ' ';
plyrInputObj[i] = plyrInputArray[i]; //acceptable or use the array itself!
}
return plyrInputObj;
}
function analyzeUserInput() {
//plyrInput = document.getElementById("plyrInput").text;//no such property as text
plyrInput = document.getElementById("plyrInput").value;
//you ran this function without storing it so we can't use it
//oc();
var plyrAction = oc();
//you call an undefined variable `plyrInputAnalysis`. So what are we going to do with it?
if (plyrInputAnalysis in oc(['use', 'slash', 'hack', 'wield', 'slice', 'sever', 'dismember', 'poke', 'cripple', 'maim', 'mutilate', 'chop', 'rend']) && plyrInputAnalysis in oc(['sword'])) {
document.getElementById("text").innerHTML = "You did 4 damage with your sword!";
}
}
Now for the fix:
var plyrInput;
var plyrInputArray;
var plyrInputAnalysis;
//added an acitonList for later usage for yourself
var actionList = {
'use':4,
'slash':4,
'hack':4,
'wield':4,
'slice':4,
'sever':4,
'dismember':4,
'poke':4,
'cripple':4,
'maim':4,
'mutilate':4,
'chop':4,
'rend':4
};
function oc() {
plyrInputArray = plyrInput.split(' ');
var plyrInputObj = {};
for (var i = 0; i < plyrInputArray.length; ++i) {
plyrInputObj[i] = plyrInputArray[i];
}
return plyrInputObj;
}
function analyzeUserInput() {
plyrInput = document.getElementById("plyrInput").value;
var plyrAction = oc(); //cached the returned value from oc
for(var item in plyrAction){ //looping through the plyrActions object
if(actionList[plyrAction[item]]){ //if there is a plyrAction that matches the actionsList we'll continue.
document.getElementById("text").innerHTML = "You did "+actionList[plyrAction[item]]+" damage with your sword!";
}
}
}
Though this could seems more complicated than it needs to be I went off your original methodology, you could create a better instance of this code for an RPG game, though it would be good to look into an IIFE to wrap this in and minimize a lot of the code instead of multiple functions.
For instance
function analyzeUserInput() {
plyrInput = document.getElementById("plyrInput").value;
var plyrAction = plyrInput.split(' ');
var plyrInputObj = {};
for (var i = 0; i < plyrAction.length; ++i) {
plyrInputObj[i] = plyrAction[i];
}
for(var item in plyrInputObj ){
if(actionList[plyrInputObj[item]]){
document.getElementById("text").innerHTML = "You did "+actionList[plyrInputObj[item]]+" damage with your sword!";
}
}
}

For-loop changing values to upper or lower case depending on their length

I'm trying to make a simple JavaScript program which prompts you to enter a sentence on page load. This sentence is then split up into an array separated by a space " ".
My issue currently is that it's not converting anything to uppercase or lowercase at all. I can't seem to understand why and some help would be appreciated.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>for-loop replacement exercise</title>
<script language="JavaScript" type="text/JavaScript">
var wordString = prompt("Please enter a sentence: ", 0);
var processedString;
var cont = boolean(true);
// this function is called upon page startup
function startMeUp() {
do {
wordString;
if (wordString == "") {
cont = boolean(false);
}
} while(cont);
processString(wordString);
document.write(processedString);
}
// this function is attempting to iterate through a array of strings and anything that is 4 characters long it is put to lower case
// otherwise if the iteration is less than 4 its put to upper case
function processString(someInput) {
var wordArray = someInput.split(" ");
var lengArray = wordArray.length;
for (var i = 0; i < lengArray; i++) {
if (lengArray[i] == 4) {
wordArray[i].toLowerCase();
} else if (lengArray[i] < 4) {
wordArray[i].toUpperCase();
}
}
processedString = wordArray.toString();
}
</script>
</head>
<body onload="startMeUp();">
</body>
</html>
Try assigning the return value to the array index, rather than just calling the function and not storing it:
wordArray[i] = wordArray[i].toLowerCase();
First your not calling startMeUp() so I added that. next you could simplify the code by using a map().
var wordString = prompt("Please enter a sentence: ", '');
startMeUp();
function startMeUp() {
document.write(processString(wordString));
}
function processString(someInput) {
return someInput.split(" ").map(v => {
if (v.length == 4) return v.toLowerCase()
if (v.length < 4) return v.toUpperCase()
return v
}).join(' ')
}

Categories