Add user input to array // Javascript - javascript

This is the code I have so far. When the user enters a word into the input box, I want that word to be stored in an array via the Add Word button. Once a number of words have been entered, the user clicks the Process Word button and I want all the words in the array to appear. How would I do this? Also could someone also explain why when nothing is entered into the input box "field is empty" does not appear?
function begin() {
var word = "List of words";
var i = returnword.length
if (userinput.length === 0) {
word = "Field is empty"
}
document.getElementById('message2').innerHTML = word
while (i--) {
document.getElementById('message').innerHTML = returnword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
var arrword = [];
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}

Addword()
Your function contains an array arrword. If you keep it inside your function it will be reset every time you call the function. You need to keep your array of words outside the function
Empty input
The empty input message should be shown when you click on the Add word button. Check the input and display a message if needed
Display word
You can simply use join() to display you array
var arrayOfWord = [];
var inputElement = document.getElementById('userinput');
var errorElement = document.getElementById('error');
var wordsElement = document.getElementById('words');
function addWord() {
errorElement.innerHTML = "";
var word = inputElement.value;
if (word.trim() === "")
errorElement.innerHTML = "Empty input";
else
arrayOfWord.push(word);
inputElement.value = "";
}
function process(){
words.innerHTML = arrayOfWord.join(' - ');
}
#error {
color: tomato;
}
#words {
color: purple;
}
Enter a word <input id="userinput" /><button onclick="addWord()">Add word</button>
<div id="error"></div>
<button onclick="process()">Process</button>
<div id="words"></div>

you can do something a bit clearer with jQuery! :)
if you handle the input with jquery you can write something like:
var arrWord = [] // your array
/* Attaching a click handler on your "Add Word" button that will
execute the function on user click */
$("#addWordButtonID").on("click", function () {
var wordTyped = $('#textInputID').val() // your var that collect userInput
if (wordTyped.length != 0) { // your if statement with length === 0 condition
arrWord.push(wordTyped) // adding word typed to the array
}
})
to add jquery to your html page, just add
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
in your html header

Hopefully you already have the right html. Then you can modify your script like below:
<script>
var arrword = [];
var returnword;
function begin() {
var word = "List of words";
var i = arrword.length;
if (arrword.length === 0) {
word = "Field is empty";
}
document.getElementById('message2').innerHTML = word;
while (i--) {
document.getElementById('message').innerHTML = arrword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
</script>
var arrword = [];
var returnword;
function begin() {
var word = "List of words";
var i = arrword.length;
if (arrword.length === 0) {
word = "Field is empty";
}
document.getElementById('message2').innerHTML = word;
while (i--) {
document.getElementById('message').innerHTML = arrword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
<button id="addWord" onclick="addword()">Add Word</button>
<button id="processWords" onclick="begin()">ProcessWords</button>
<input type="text" id="userinput" value=" " />
<div id="message2">
</div>
<div id="message">
</div>

Related

How do i remove a calculator from a bot? (its connected to the enter button)

I need to remove the calculator, without removing the function of allowing it to print, I have tried switching things around, and removing things, but still when I type in a number, such as 67, it comes out as 67=67, or more complicated math equations, it dosent except things like PI, this is because it thinks it's some symbol, not a character. The only things that do work are: / = + - /, it dosent accept cubed or squared, or to the power of X
Bot code:
<html>
<body>
<div class="container" id="content">
<p id="out">
</p>
<p id="inp">
<div id="stretchbox" style = "position:fixed; left:80px;">
<input type="text" placeholder="Coin ID #"
id="txt-inp"
autocomplete="off"
autocorrect="off"
autocapitalize="off"
autofocus="autofocus"
spellcheck="false">
</input>
</div>
</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(function() {
var trigger = [
["25184"],
["27123"],
["26124"],
["17453"]
];
var reply = [
["Coin Bot - "],
["Tokyn Blast - "],
["Iron Wolf - "],
["Foxyville - "],
];
var alternative = ["I cant find that Coin ID # right now, make sure that the Coin ID # exist!"];
let textInput = $('#txt-inp');
let messageOutput = $('#out');
let processingStatus = $('<span>Bot: Processing...<br></span>');
let name = 'You';
function println(text) {
let newSpan = document.createElement("SPAN");
let newLine = document.createElement("BR");
let textNode = document.createTextNode(text);
newSpan.appendChild(textNode);
document.getElementById("out").appendChild(newSpan);
document.getElementById("out").appendChild(newLine);
gotoBottom();
}
function print(text) {
let newSpan = document.createElement("SPAN");
let textNode = document.createTextNode(text);
newSpan.appendChild(textNode);
document.getElementById("out").appendChild(newSpan);
}
function gotoBottom() {
window.scrollTo(0,document.body.scrollHeight);
}
function sendMessage() {
let data = {
'reply': textInput.val()
};
if (!data['reply']) {
return;
}
println(name + ': ' + data['reply']);
textInput.val('');
messageOutput.append(processingStatus);
textInput.attr('disabled', 'disabled');
messageOutput.children().last().remove();
textInput.removeAttr('disabled');
output(data['reply']);
}
$('#txt-inp').keypress(function(e) {
if (e.which == 13) {
sendMessage();
}
});
function output(input){
try{
var product = input + "=" + eval(input);
} catch(e){
var text = (input.toLowerCase()).replace(/[^\w\s\d]/gi, ""); //remove all chars except words, space and
text = text.replace(/!/g, "!").replace(/i feel /g, "").replace(/whats/g, "what is").replace(/please /g, "").replace(/ please/g, "");
if(compare(trigger, reply, text)){
var product = compare(trigger, reply, text);
} else {
var product = alternative[Math.floor(Math.random()*alternative.length)];
}
}
println(product);
}
function compare(arr, array, string){
var item;
for(var x=0; x<arr.length; x++){
for(var y=0; y<array.length; y++){
if(arr[x][y] == string){
items = array[x];
item = items[Math.floor(Math.random()*items.length)];
}
}
}
return item;
}
});
</script>
</body>

The sum cannot show although i click on the button

What I want is, after the user enters the number of subjects, the system will show the number of input box according to the number of subjects entered, then when the user clicks on the button, it should show the sum. I tried many ways, but I failed to show the sum, anyone knows what is the mistake I made?
Below is my code:
function select() {
var x = parseInt(document.getElementById('1').value);
if (document.getElementById('1').value == "") {
alert("Please fill up number of subject");
} else if (isNaN(x) == true) {
alert("Please fill up number of subject with number");
} else {
var subject = parseInt(document.getElementById('1').value);
var sum = 0;
for (var num = 1; num <= subject; num++) {
document.write("Enter the mark for subject " + num + " : ");
var value = parseFloat(document.write("<input/><br>"));
sum += value;
}
var calc = document.write("<button>Next</button><br>");
calc.onclick = function() {
next()
};
function next() {
document.write("Total marks: " + sum + "%");
}
}
}
<html>
<body>
Enter the number of subject: <input type="text" onkeypress="return/[0-9]/i.test(event.key)" id="1" value=""><br>
<button onclick="select()">Check</button><br>
</body>
</html>
That's how I have rewritten a big part of your code. I have place inline comments to explain what I do.
function select() {
var x = parseInt(document.getElementById('1').value, 10);
// Getting the div that wraps the initial form.
var formWrapper = document.querySelector('.formWrapper');
// Getting the div, that is going to display the new fields and the results.
var results = document.querySelector('.results');
// I have switch your statement from x == '' to '' === x as it
// consists a good practice
if ( '' === x ) {
alert("Please fill up number of subject");
// I have remove the isNaN(x) == true, because the isNan will
// be either true or false.
} else if ( isNaN(x) ) {
alert("Please fill up number of subject with number");
} else {
// Using parseInt(x, 10) to set the base.
var subject = parseInt(x, 10);
// In this array, I store the auto-generated fields.
var fieldsList = [];
// Removing the first div from the DOM
formWrapper.parentElement.removeChild(formWrapper);
for ( var num = 1; num <= subject; num++ ) {
// I am creating a new field
var newField = document.createElement('input');
// I push the field into the array I made for the fields.
fieldsList.push(newField);
// I append the field in the HTML
results.appendChild(newField);
// I create a <br> tag
var br = document.createElement('br');
// And I append the tag in the DOM
results.appendChild(br);
}
// I create the button that is going to handle the Next functionality
var nextButton = document.createElement('button');
// I set the button text
nextButton.innerText = 'Next';
// I add an Event Listener for the click event.
nextButton.addEventListener(
'click',
function() {
// I reset the sum to 0
var sum = 0;
// I itterate the fields auto-generated and saved in the array
fieldsList.forEach(
function(field) {
// I get the value
sum += parseInt(field.value, 10);
}
);
// I create the field that is going to display the output
let resultText = document.createElement('div');
// I set the text based on the sum
resultText.innerText = "Total marks: " + sum + "%";
// I append the text message to the DOM
results.appendChild(resultText);
}
);
// I append the button to the DOM
results.appendChild(nextButton);
}
}
<html>
<body>
<div class="formWrapper">
Enter the number of subject: <input type="text" onkeypress="return/[0-9]/i.test(event.key)" id="1" value=""><br>
<button onclick="select()">Check</button><br>
</div>
<div class="results"></div>
</body>
</html>

Reverse case (Lowercase/Uppercase) of an input value character by character

By using one input text box and the input type allows only alphabets.The value entered is 'a' and it should be display outside the textbox as 'A'?
If we enter the alphabet small 'a' on input text then it will wanted to display capital 'A' on the outside of the box...
The following is my html code:
<!DOCTYPE html>
<html>
<head>
<!--<script type="text/javascript" href="check.js"></script>-->
</head>
<body>
<input type="text">
<script>
function myFunction()
{
var A = document.getElementById('input').value;
console.log('alphabet'.toUpperCase());
}
</script>
</body>
</html>
To show the input value with case reversed you should:
Call your function in the onkeyup event of your input to update the preview immediately with the inputted string.
And loop through your string and for each character test if it's in
uppercase reverse it to lowercase or make it uppercase if it's
lowercase.
Here's a Snippet DEMO:
function myFunction() {
var A = document.getElementById('input').value;
var output = '';
for (var i = 0, len = A.length; i < len; i++) {
var character = A[i];
if (character == character.toLowerCase()) {
// The character is lowercase
output = output + character.toUpperCase();
} else {
// The character is uppercase
output = output + character.toLowerCase();
}
}
document.getElementById("preview").innerText = output;
}
<input id="input" type="text" pattern="[A-Za-z]" onkeyup="myFunction()" /><span id="preview"></span>
You may use an event for immediatly update the result, while writing.
document.getElementById('input').addEventListener('keyup', function () {
var input = document.getElementById('input').value;
if (!input.match(/^[a-z]*$/i)) {
document.getElementById('output').innerHTML = 'Wrong input';
return;
}
document.getElementById('output').innerHTML = input.split('').map(function (a) {
return a.match(/[a-z]/) ? a.toUpperCase() : a.toLowerCase();
}).join('');
});
<input type="text" id="input">
<div id="output"></div>
function reverseCase(str) {
let newstr = str.split('');
let newarr = [];
//return newstr;
for(i=0; i<newstr.length; i++) {
if(newstr[i] == newstr[i].toLowerCase()){
newarr.push(newstr[i].toUpperCase());
}else
if(newstr[i] == newstr[i].toUpperCase()){
newarr.push(newstr[i].toLowerCase());
}
} return newarr.join('');
}
console.log(reverseCase("Happy Birthday"))

Issue in regular expression

In the below code i have a textbox in which when i enter numeric it should alert that only alphabets are allowed.In which i get the regular expresion and spilt it and store in an array and for loop it and check the regular expression that i enter in my textbox.Pls help to solve the issue.
<input type="text" id="check" onblur="validate()" />
<script type="text/javascript">
function validate() {
var hiddenValue = new RegExp( "[A-Z]~~[a-z]");
// var val = document.getElementById("check").value;
var mySplitResult = new Array();
mySplitResult = hiddenValue.split("~~");
for (i = 0; i < mySplitResult.length; i++) {
document.write("<br /> Array[" + i + " ]= " + mySplitResult[i]);
if (mySplitResult.test(document.getElementById("check").value)) {
alert('check');
return false;
}
}
}
</script>
If you want to test that an input is all letters:
if (!document.getElementById("check").value.test(/^[a-z]+$/i)) {
alert ("Only letters are permitted");
return false;
}
See this fiddle. Will check that only letters are in the textbox otherwise alert.
http://jsfiddle.net/2EDYV/2/
function validate() {
var result = /^([a-zA-Z]+)$/.test(document.getElementById("check").value);
if (!result) {
alert('numeric value found');
}
}

Opening input when writing #Q# in textarea

I have textarea. Now, I want to do that once you write "#q + number#" ( e.g. #q1# ), it will create new input field.
For example if you write: "Hello my name is #q1# and my favorite food is #q2#". It will open two input fields.
And when you delete one of those #q + number#, it will delete the same field that was intended to the #q#
For example: if you write "Hello my name is #q1# and my favorite food is #q2#, and the input fields look like that:
<input type="text" q="1" />
<input type="text" q="2" />
and next that I delete the #q1# it supposed to look like that:
and don't delete the value of q="2" input.
How can I do that in jQuery/JavaScript?
Take a look at this quick fiddle http://jsfiddle.net/NgxvP/1/
Here you have something to start playing with
<html>
<head>
<style>
#inputField { position:relative;
width: 200px;
height: 200px;
background-color: #cda;
}
</style>
<script src="jquery-1.7.1.min.js"></script>
<script>
// in_array function provided by phpjs.org
function in_array (needle, haystack, argStrict)
{
var key = '',
strict = !! argStrict;
if (strict)
{
for (key in haystack)
{
if (haystack[key] === needle)
{
return true;
}
}
}
else
{
for (key in haystack)
{
if (haystack[key] == needle)
{
return true;
}
}
}
return false;
}
var addedFields = new Array();
function checkFields(input, charCode)
{
var text = (charCode) ? input.value + String.fromCharCode(charCode) : input.value;
var pattern = /#q[0-9]#/g;
var matches = text.match(pattern);
if (!matches) { matches = new Array(); }
if (addedFields.length>0 && addedFields.length != matches.length)
{
for (var index in addedFields)
{
if (!in_array('#q'+ index +'#', matches))
{
$('#q'+index).remove();
delete addedFields[index];
}
}
}
if (matches)
{
for (var i=0; i<matches.length; i++)
{
var code = matches[i];
var index = code.match(/[0-9]/)[0];
if ( $('#q'+index).length == 0 )
{
addFields(index);
}
}
}
}
function addFields(i)
{
addedFields[i] = true;
var fields = '';
for (var index in addedFields)
{
fields += '<input type="text" q="'+ index +'" id="q'+ index +'" />';
}
$('#inputField').html(fields);
}
</script>
</head>
<body>
<div id="formID">
<form>
<textarea onkeypress="checkFields(this, event.charCode); return true;" onkeyup="checkFields(this); return true;"></textarea>
<div id="inputField"></div>
</form>
</div>
</body>
</html>
EDITED: to avoid appending unordered input text fields, but showing them always ordered by their index, as commented in dfsq answer
I created a jsfiddle for your convenience http://jsfiddle.net/2HA5s/

Categories

Resources