How to make an array of the User's input - javascript

The code is supposed to randomly select from the user input to generate a random one.
The HTML includes a form where the user can input values which are saved, but I do not know how to store them in an array in javascript where the let decision is what stores them. When the user inputs an option, they press submit where the javascript appends a child with the option that was input (this is not included) In the javascript, but what is included is the random decision button, if let decision was an array, the button would randomly choose from the array.
The HTML:
let btn = document.getElementById('decide');
let output = document.getElementById('output');
const option_input_el = document.createElement('input');
option_input_el.classList.add('text');
option_input_el.type = 'text';
option_input_el.value = task;
option_input_el.setAttribute('readonly', 'readonly');
let decision = []; /*how to make array of the user inputs*/
btn.addEventListener('click', function() {
var chosen = decision[Math.floor(Math.random() * decision.length)];
output.innerHTML = chosen;
});
//this is our code for the decicon
<body>
<!--Our input of choices-->
<div id="center">
<header>
<h1 id="Title">Input Your Choices</h1>
<form id="form">
<input type="text" id="newT" placeholder="Options" />
<input type="submit" id="sumbitT" value="Add" />
</form>
</header>
</div>
<main>
<section class="option-list">
<h2 id="option">Your Options</h2>
<div id="options"></div>
</section>
<div class="container">
<button id="decide"> Let's Decide! </button>
<div id="output">DECISION</div>
</div>
</main>

your HTML code didn't work properly for what you wanted to achieve, so I had to rework it.
to make an array from user input, you can use push to the input.value to an array.
I used only two functions to do what you asked for. and what happens is simple:
1- when the user click add button, it get user's input then
2- push it into an array.
3- display it in the options div.
4- when the user click decide button, it will select a random value from the displayed array. then display it on the decision div.
var input = document.getElementById("input");
var inputArr = [];
var addBtn = document.getElementById("add-btn");
var display = document.getElementById("options-list");
var decideBtn = document.getElementById("decide-btn");
var resultDisplay = document.getElementById("random-output");
addBtn.addEventListener("click", addAnddisplay);
function addAnddisplay() {
inputArr.push(input.value);
display.textContent = inputArr;
}
decideBtn.addEventListener("click", decide);
function decide() {
var decision = inputArr[Math.floor(Math.random() * inputArr.length)];
resultDisplay.textContent = decision ;
}
<h1 id="Title">Input Your Choices</h1>
<input type="data" id="input" placeholder="Options" />
<button id="add-btn">Add</button>
<!-- <input type="submit" id="add-btn" value="Add" /> -->
<h2>Your Options</h2>
<div id="options-list"></div>
<button id="decide-btn"> Let's Decide! </button>
<div id="random-output"></div>

Related

Trying to change Speech bubble text when User submits name input

I have 2 javascript files.
js file 1 contains the time delay for a speech bubble to appear with animation
see js file 1 code
let bubble = document.getElementById("speach-bubble");
let noDisplay; bubble.style.display ="none";
const delay = setTimeout(bubbleAnimate,1500)
function bubbleAnimate()
{
noDisplay = bubble.style.display ="block";
bubble.style.animation="slidein 0.5s 1";
}
with js file 2 I am trying to make a function that when user clicks submit after typing in their name the speech bubble changes to "welcome to your to-do App" + name
this is what I have so far
let welcome ="Welcome to your To-Do App"
windows.onload = function()
{
document.getElementById("userName").onsubmit = function()
{
let text = document.getElementById("nameId");
let changebox = document.getElementById("speach-bubble").innerHTML = welcome + " " + text;
}
}
this is the elements I am working on within my HTML file
<div class=container>
<div class= base>
<div class = screen>
<img src="images/WarGreymon_Render.png" alt="Wargreymon">
<div id ="speach-bubble"> What is your
name?
<div id = "bubble-text">
</div>
</div>
</div>
<div class = "nameInput">
<form id ="userName">
<input type="text" id ="nameId" name="name" placeholder="Type your name here...">
<input type="submit" id ="submit" value="Submit">
</form>
</div>
</div>
is there a way to link js file 1 to js file 2 so that I can influence the speech bubble after userinput has been submitted.

Reset button on form not working for javascript?

I am trying to reset every input that has been entered on this form when the "reset" button
gets clicked. Below is my code that I tried using, the reset button wont reset anything.
Thank you.
<form id="todoForm">
<input type="text" id="todoInput" placeholder="Input new note..">
<input type="text" id="description" placeholder="Input description..">
<button type="button" id="button" onclick="todoList()">Submit</button>
<button type="button" id="reset" onclick="resetForm()">Reset</button>
</form>
<ol id="todoList">
</ol>
function todoList() {
var item = document.getElementById("todoInput").value
var text = document.createTextNode(item)
var addItem = document.createElement("li")
addItem.appendChild(text)
document.getElementById("todoList").appendChild(addItem)
var item = document.getElementById("description").value
var text = document.createTextNode(item)
var addItem = document.createElement("p")
addItem.appendChild(text)
document.getElementById("todoList").appendChild(addItem)
}
function resetForm() {
document.getElementById(todoList).reset();
}
Don't add a reset button.
Assuming this is a todo app users can just delete the todo after creating it. Adding a reset button probably won't provide much value to users, instead it will most likely frustrate ones that click it by mistake.

taking form input value into a new created div "note"

I have a school project, where they asked us to create a form where you input values, and when you click submit, a new note will shoe and will be filled with the values from the form.
My problem is that I can't understand how to write the function that creates the notes with the values from the form.
I already did the form and the design for the page. Also started the function to create the note.
This is the form:
<form id="form1">
Mission Details: <textarea name="Details" rows="3" cols="20"></textarea> <br> <br>
Mission Due Date: <input type="Date" name="Date"> <br> <br>
Mission Due Time: <input type="Text" name="Time"> <br> <br>
<button type="button" onsubmit="createNote()"> Submit </button>
<button type="button" onclick="Clear()"> Clear </button>
</form>
This is the script i started:
function CreateNote(event) {
var form = event.currentTarget;
var details = form.Details.value;
var date = form.Date.value;
var time = form.Time.value;
}
var form = document.getElementById('form1');
form.onsubmit = CreateNote();
This is the div for the note and note content:
<div class="note">
<div class="noteDetails">
</div>
</div>
Eventually, the note will have a background from an image in a CSS file, and inside that note, it will have the values from the form.
1. Create a template for your note, lets say you display your text with <p></p>.
2. Leave it with empty values. Give it an id, lets call it "details".
3. After you have the desired values, use document.getElementById("details"), and fill the <p> with the value.
<div class="note">
<div class="noteDetails">
<p id="details"></p>
</div>
</div>
then in your JavaScript you can use
var stringInput = "Some String";
var detailsElement = document.getElementById("details");
detailsElement.innerHTML = " stringInput;
You can now use your div noteDetails. Inside it create three p elements with id details, date and time.
eg:
<div class="noteDetails">
<p id="details"></p>
<p id="date"></p>
<p id="time"></p>
</div>
Change your button element to:
<button type="button" onclick="createNote()"> Submit </button>
Note: your using createNote() in html and using CreateNote in JS
and inside your createNote function just add
function createNote() {
var form = document.getElementById('form1');
var details = form.Details.value;
var date = form.Date.value;
var time = form.Time.value;
var detailsPara = document.querySelector('#details');
detailsPara.innerText = details;
var datePara = document.querySelector('#date');
datePara.innerText = date;
var timePara = document.querySelector('#time');
timePara.innerText = time;
}
remove lines from your code
var form = document.getElementById('form1');
form.onsubmit = CreateNote();
UPDATE: if input values are to be shown immediately then add these to html
Mission Details: <textarea name="Details" rows="3" cols="20" oninput="createNote()"></textarea> <br> <br>
Mission Due Date: <input type="Date" name="Date" oninput="createNote()"> <br> <br>
Mission Due Time: <input type="Text" name="Time" oninput="createNote()"> <br> <br>

Add input to form if button is clilcked

I'm not really sure the best way to go about this but I've laid the framework.
Basically, I would like to add the functionality so that when my #moreItems_add button is clicked and calls the moreItems function, I simply want to add a new Input field below it, and so on. I want to limit this to 10 fields though, so I show that in the function.
The only trick is, I will be submitting all fields via ajax to save to the database, so I need to try and keep track of an ID with each.
What's the best way to continue the javascript here so that I can append an input field on button press and keep track of IDs for each?
<div class="modal-body">
<form id="Items">
<label id="ItemLabel">Item 1:</label>
<input type="text" name="Items[]">
<button id="moreItems_add" onclick="moreItems()" id="moreItems">More Items</button>
</form>
</div>
<div class="modal-footer">
<input type="submit" name="saveItems" value="Save Items">
</div>
<!-- modal JS -->
<script type="text/javascript">
function moreItems(){
var MaxItems = 10;
//If less than 10, add another input field
}
</script>
You can use the jQuery .insertBefore() method to insert elements right before "more items" button. Below is the code representing this:
var maxItems = 1;
function moreItems() {
if (maxItems < 10) {
var label = document.createElement("label");
label.id="ItemLabel"+maxItems;
label.innerHTML = "Item "+(maxItems+1)+": ";
var input = document.createElement("input");
input.type='text';
input.name = 'item'+maxItems;
$('<br/>').insertBefore("#moreItems_add");
$(label).insertBefore("#moreItems_add");
$(input).insertBefore("#moreItems_add");
maxItems++;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal-body">
<form id="Items">
<label id="ItemLabel">Item 1:</label>
<input type="text" name="Items[]">
<button type="button" id="moreItems_add" onclick="moreItems()" id="moreItems">More Items</button>
</form>
</div>
<div class="modal-footer">
<input type="submit" name="saveItems" value="Save Items">
</div>
Something like this should do the trick:
<!-- modal JS -->
<script type="text/javascript">
var MAX_ITEMS = 10,
added = 0;
function moreItems(){
if (added >= MAX_ITEMS) return;
var newField = document.createElement('input');
newField.type = 'text';
// TODO: Any field setup.
document.getElementById('items').appendChild(newField);
added++;
}
</script>
In terms of tracking each field with an ID, that should always be done by the back-end for data integrity and safety reasons.
some years ago I've wrote an article about making a repeated section using jQuery.
The live example is available on jsFiddle.
In the example you can find that both "add" and "remove" button are available, however you can set just the "add" button for your purpose.
The idea to limit to specific number of repeated boxes is to watch the number of repeatable elements just created in the context. The part of code to change in the live example is rows 13-18:
// Cloning the container with events
var clonedSection = $(theContainer).clone(true);
// And appending it just after the current container
$(clonedSection).insertAfter(theContainer);
There you should check if the number of repeated elements is less than <your desired number> then you will allow the item to be created, else you can do something else (like notice the user about limit reached).
Try this:
const maxItens = 10,
let itensCount = 0;
function moreItems() {
if (itensCount++ >= maxItens) {
return false;
}
let newInput = document.createElement('input');
// use the iterator to make an unique id and name (to submit multiples)
newInput.id = `Items[${itensCount}]`;
newInput.name = `Items[${itensCount}]`;
document.getElementById('items').appendChild(newInput);
return false;
}
Add type "button" to stop submiting the page (also, your button have two ID):
<button id="moreItems_add" onclick="moreItems();" type="button">More Items</button>
The submit button must be inside the form to work:
<form>
<div class="modal-body">
<div id="Items">
<label id="ItemLabel">Item 1:</label>
<input type="text" name="Items[]">
</div>
<button id="moreItems_add" onclick="moreItems()" id="moreItems">More Items</button>
</div>
<div class="modal-footer">
<button type="submit">Save Items</button>
</div>
</form>
To append itens in sequence the button must be outside of div "itens".

How to on click get 2 different data sets with the same class

I basically on click need to insert the data- into a form. The issue is that both forms use the same element classes and when I perform one function it inserts the data but as soon as I click to run the other function it clears the original data. Here is my code:
HTML
<div class="inbox-widget nicescroll mx-box">
<a data-dismiss="modal" data-toggle="modal" href="#con-close-modal">
<div class="inbox-item" data-tag="Followers" data-social_type="twitter">
<p class="inbox-item-date">Click to add</p>
</div>
<div class="inbox-item" data-tag="Friends" data-social_type="twitter">
<p class="inbox-item-date">Click to add</p>
</div>
</a>
<a data-dismiss="modal" data-toggle="modal" href="#con-close-modal">
<div class="inbox-item2" id="chosen_account" data-social_id="12345">
<p class="inbox-item2-date">Click to add social ID</p>
</div>
</a>
<a data-dismiss="modal" data-toggle="modal" href="#con-close-modal">
<div class="inbox-item" id="chosen_account" data-social_id="6789">
<p class="inbox-item-date">Click to add social ID</p>
</div>
</a>
</div>
<form>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="input" id="social_id" type="text" name="social_id" />
<input type="input" id="social_type" type="text" name="social_type" />
<input type="input" id="chart_type" type="text" name="chart_type" value="line"/>
<input type="input" id="chart_tag" type="text" name="chart_tag"/>
</form>
My Jquery:
$('.inbox-item').click(function() {
var social_type_value = $(this).data('social_type');
var social_type_input = $('#social_type');
social_type_input.val(social_type_value);
var chart_tag_value = $(this).data('tag');
var chart_tag_input = $('#chart_tag');
chart_tag_input.val(chart_tag_value);
var social_id_value = $(this).data('social_id');
var social_id_input = $('#social_id');
social_id_input.val(social_id_value);
});
I also created a fiddle to show whats happening: https://jsfiddle.net/p18f3dow/1/
if i got your problem right, you'd want to use one function - but depending on the clicked element add different data... but don't overwrite the already entered data, when clicked element don't contains relevant data...
why not checking, if the data tag exists, in the first place:
$('.inbox-item').click(function() {
if ($(this).data('social_type')) {
var social_type_value = $(this).data('social_type');
var social_type_input = $('#social_type');
social_type_input.val(social_type_value);
}
if ($(this).data('tag')) {
var chart_tag_value = $(this).data('tag');
var chart_tag_input = $('#chart_tag');
chart_tag_input.val(chart_tag_value);
}
if ($(this).data('social_id')) {
var social_id_value = $(this).data('social_id');
var social_id_input = $('#social_id');
social_id_input.val(social_id_value);
}
});
this would be the quick and dirty solution, though.
better one would be like storing the complete clicked data objects and iterating through them, filling the correct fields. see https://jsfiddle.net/p18f3dow/4/
therefore you have to ensure that the part behing the data- in your html always matches your id in the form. (had to change it from data-tag to data-chart_tag)
then all you need is a simple function like that:
$('.inbox-item').click(function() { //when clicked
var stored_data = $(this).data(); //save everything in an object
for (var key in stored_data) { //iterate through the object
if (stored_data.hasOwnProperty(key)) {
$('#' + key).val(stored_data[key]) //create an id with #+key and insert the value
}
}
});

Categories

Resources