javascript & html - creating new checkbox option everytime user enters item in textbox - javascript

So basically I'm creating a program that allows the user to create and manage a ‘to-do list’. This will allow the user to add new items, remove selected items, highlight/un-highlight selected items, and sort the items, etc. I'm currently working on the add button, but I'm extremely confused with different functions in HTML and code that will allow me to manipulate the DOM.
When the user clicks the add button and the item name is valid, a new item should be added to the page’s to-do list (which esentially creates a new checkbox for every item the user adds). The checkbox is basically so the item can be selected/deselected, as well as the text that was in the item name textbox when the add button was clicked.
I guess I have two problems right now. I'm trying to verify that the item name is at least 1 character long. I wrote code in my "addHandler.js" file but when I write nothing in the textbox and click on the add button on my HTML browser, no error message pops up. I don't know why it's ignoring my function. Another thing I'm struggling with is the part that creates a new checkbox for every valid item that is added. I know how to create a checkbox on my HTML page, but I don't understand how to get my program to create a new one per item that the user inputs.
Any help or push in the right direction would be appreciated. I'm also new to HTML and javascript, so explaining stuff in simple terms would also make me really grateful.
todo.html code:
<html>
<head>
<title>Checklist</title>
</head>
<body>
<div><h1>My to-do list</h1></div><br />
<div id ="myCheckList">Enter an item:</div>
<div>Type something: <input type="text" id="textbox"></input></div>
<button type="button" id="addBut">Add item</button>
<button type="button" id="removeBut">Remove items</button>
<button type="button" id="toggleBut">Toggle highlight</button>
<button type="button" id="sortBut">Sort items</button>
<script src="addHandler.js"></script>
</body>
</html>
addHandler.js code:
function init(){
let button = document.getElementById("addBut");
button.onclick = buttonClicked;
let tb = document.getElementById("textbox");
tb.onblur = validate;
}
function add(){
let someEle = document.getElementById("myCheckList");
someEle.innerHTML = 'You added an item';
}
function validate(){
if(document.getElementById("textbox").value.length == 0){
alert("You need to enter something");
}
}

You should have a wrapper that contains your checkbox items that you can append new elements to.
<div id="checklist_items"></div>
Then you can use the following function to create a new div that contains a checkbox and the entered text, and then append it to your checklist:
function addItem() {
var input = document.getElementById("textbox");
var wrapper = document.getElementById("checklist_items");
if(input.value.trim() != "") {
var new_element = document.createElement("DIV");
new_element.innerHTML = '<input type="checkbox"> '+input.value;
wrapper.appendChild(new_element);
}
else {
alert("You must enter at least 1 character.");
}
}
I would also use the following to add the function to your button:
document.getElementById("addBut").addEventListener("click", addItem);

Related

How can I pass a variable from a JS input to HTML?

I'm taking an input from a user in javascript and using it to display that number of pages. Basically, I ask the user how many items they have. If they say, for example, 4, I need to ask them the name of each item on the next page. Then, on the next 4 pages, they are to input the value of each item one per page and finally, I will display a table of the items, values, and final sum. My question is:
After obtaining the number of items in my javascript file, how do I pass it back to my HTML file? Should I even be passing it back to my HTML file?
When I have the number of items, how do I open that many new files/pages for javascript and HTML based on it? Or can I do it all on one js file? I know it's quite redundant to open a new HTML and JS file for each item but I don't know how to clear the page each time after a button click and display a new input box on the same file.
Sorry if this is a really stupid question, just a confused begginer here. Thank you!
Here's what I have so far:
index.html:
<body>
<h1>Welcome!</h1>
<h2>Ready to track your items?</h2>
<p><button>Start</button></p>
</body>
items.html:
<body>
<h3>How many items do you have?</h3>
<p><input id="numItems"></p>
<script src="main.js"></script>
</body>
main.js:
var numIt = document.getElementById("numItems");
numIt.addEventListener("input", display);
function display(){
var item = parseFloat(numIt.value);
alert("you have " + item+" items");
}
I am not 100% sure, but guess You need to dynamically generate N number of inputs to have users fill in names of each item. As mentioned opening new or creating new html files would not be the best solution, also it can't be done with browser javascript.
So instead why not generate input elements and append them to the DOM, for more info please see DOM w3schools
Small example.
function display(){
var item = parseFloat(numIt.value);
for(var i =0; i<item;i++){
var inpElem = document.createElement("input");
inpElem.setAttribute("name", "item"+i);
inpElem.setAttribute("placeholder", "Input name of the item #"+i);
document.body.appendChild(inpElem);
}
}
Let's say user inputs 2. It will generate
<input placeholder="Input name of the item #1" name="item1" >
<input placeholder="Input name of the item #2" name="item2" >
Also to empty the body - document.body.innerHTML = ""
Probably you can use "pages" (hide all elements except one)
There is an example, you can check it out
const pages = ["page1", "page2", "page3"]
showPage(0)
function hidePages() {
for(const page of pages)
changeElementVisibility(page, false)
}
function showPage(num) {
hidePages()
const pageId = pages[num]
changeElementVisibility(pageId, true)
}
function changeElementVisibility(id, visible) {
document.getElementById(id).style.display = visible ? "" : "none"
}
function secondPageSumbit() {
const itemsCount = document.getElementById("itemsCount").value
document.getElementById("result").innerText = "Items Count: " + itemsCount
}
<head>
<script src="main.js"></script>
</head>
<body>
<div id="page1">
<h1>Welcome!</h1>
<h2>Ready to track your items?</h2>
<p><button onclick="showPage(1)">Start</button></p>
</div>
<div id="page2">
<h3>How many items do you have?</h3>
<p><input id="itemsCount"></p>
<p><button onclick="secondPageSumbit();showPage(2)">Next</button></p>
</div>
<div id="page3">
<h3>Result</h3>
<p id="result"></p>
</div>
</body>

How to POST additional values from inputs outside the form [duplicate]

I've read many blogs and posts on dynamically adding fieldsets, but they all give a very complicated answer. What I require is not that complicated.
My HTML Code:
<input type="text" name="member" value="">Number of members: (max. 10)<br />
Fill Details
So, a user will enter an integer value (I'm checking the validation using javascript) in the input field. And on clicking the Fill Details link, corresponding number of input fields will appear for him to enter. I want to achieve this using javascript.
I'm not a pro in javascript. I was thinking how can I retrieve the integer filled in by the user in input field through the link and displaying corresponding number of input fields.
You could use an onclick event handler in order to get the input value for the text field. Make sure you give the field an unique id attribute so you can refer to it safely through document.getElementById():
If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">. Create new elements by means of document.createElement(), and use appendChild() to append each of them to the container. You might be interested in outputting a meaningful name attribute (e.g. name="member"+i for each of the dynamically generated <input>s if they are to be submitted in a form.
Notice you could also create <br/> elements with document.createElement('br'). If you want to just output some text, you can use document.createTextNode() instead.
Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes() and removeChild() together.
<html>
<head>
<script type='text/javascript'>
function addFields(){
// Generate a dynamic number of inputs
var number = document.getElementById("member").value;
// Get the element where the inputs will be added to
var container = document.getElementById("container");
// Remove every children it had before
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
// Append a node with a random text
container.appendChild(document.createTextNode("Member " + (i+1)));
// Create an <input> element, set its type and name attributes
var input = document.createElement("input");
input.type = "text";
input.name = "member" + i;
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement("br"));
}
}
</script>
</head>
<body>
<input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
Fill Details
<div id="container"/>
</body>
</html>
See a working sample in this JSFiddle.
Try this JQuery code to dynamically include form, field, and delete/remove behavior:
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e) {
e.preventDefault();
if (x < max_fields) {
x++;
$(wrapper).append('<div><input type="text" name="mytext[]"/>Delete</div>'); //add input box
} else {
alert('You Reached the limits')
}
});
$(wrapper).on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container1">
<button class="add_form_field">Add New Field
<span style="font-size:16px; font-weight:bold;">+ </span>
</button>
<div><input type="text" name="mytext[]"></div>
</div>

Is it possible to repeatedly use the same text box to get input from users in HTML & Javascript?

So I have a created a text box using html code along with a button for "confirm"
<input type="text" id="myInput" style="height: 10px; width: 50px" value="">
<button onclick="enter_value()">Confirm</button>
What I intend to do is to use the same text box over and over for different inputs as the website guides the user to do different tasks (which all functions are written in js)
I'm trying to figure out a way to use this same text box for all inputs users have to insert, but so far nothing is working.
I tried creating a function like:
function enter_value(){
var name = document.getElementById("myInput").value;
}
This should be able to store the value of the input in the variable name. Problem is, I want to execute this when button is pressed, but the button is not responding and the variable "name" always returns "Enter Your Input Here" (is this default?)
What am I missing here?
You can definitely re use the same text box to take in more than one piece of information. The question is how do you store the info in the process. So you can keep the onclick handler that you already have, then change what you do with the input based on the state of the page.
Current Step: <div id="current_step">name</div>
<input type="text" id="myInput" style="height: 10px; width: 50px" value="">
<button onclick="enter_value()">Confirm</button>
<div class="results">
<div id="name_result"></div>
<div id="addr_result"></div>
</div>
function enter_value(){
var curStep = document.getElementById("current_step").innerHTML,
curValue = document.getElementById("myInput").value;
//do some error testing here, if it is a bad submission dont continue
if (curValue == "") return false;
if (curStep == "name"){
document.getElementById("name_result").innerHTML = curValue
document.getElementById("current_step").innerHTML = "address"
}
else if (curStep == "address"){
document.getElementById("addr_result").innerHTML = curValue
document.getElementById("current_step").innerHTML = "Done!"
}
document.getElementById("myInput").value = '';
}
You should be able to use this to get started

Taking a HTML form <input> value and using it to modify a <p> tag with Javascript

I am fairly new to Javascript and am trying to create a simple madlib application where a user can input a word through an HTML page and have that word appear in a paragraph tag when the user clicks the "submit" button. I am having troubles displaying the word that the user inputs. I know that I am close but for the life of me cannot figure out what I am missing.
Here is the HTML I am using:
<form>
<label>Word</label><input id="word"></input>
<input type="submit" value="submit" id="submitButton"></input>
</form>
<p id="story"> A {userWord goes here} is now part of the story </p>
And the Javascript:
var word = document.getElementById('word').innerHTML,
originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(){
replaceStory(word);
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
return originalStory.innerHTML = story;
};
Here is a JSFiddle: https://jsfiddle.net/5c4j2opc/
I have made a new JSFiddle: https://jsfiddle.net/5c4j2opc/3/ which works.
I changed type="submit" to type="button" to stop the page refreshing when the button is clicked and moved the word variable to the replaceStory function so it doesn't just get called once at the beginning of the script! Hope this helps.
You have to change two things.
The first is you are using innerHTML in a input element, when you want to access input element you need to get the value not the innerHTML, inputs not have this property.
The second one is that you need to pass the event on the onclick event since if you don't do it you can't cancel the submit action and then the page will be submit it automatically and reload the content. Then after you pass the event you have to apply event.preventDefault which will stop the submit for that button. Other option to avoid this problem would be possible to replace the submit button with a <button> tag or <input type="button"> since not of them will trigger the submit action.
You can see a working example https://jsfiddle.net/5c4j2opc/9/
html -> same you have
javascript
var word = document.getElementById('word'),
originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(e){
replaceStory(word.value);
e.preventDefault();
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
return originalStory.innerHTML = story;
};
You initialize wordjust in the beginning of the script. Besides, that the input value is not innerHTML, during that time, the value is empty.
As long as the return value is not set explicitly to false, the form will reload the page and overwrite any result.
Change your code:
var originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(){
var word = document.getElementById('word').value;
replaceStory(word);
return false;
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
originalStory.innerHTML = story;
};
updated fiddle
You had a couple of minor problems. The input type of the submit button should be button rather than submit. Submit does a post request and refreshes the page with the data received.
Initially you had:
var word = document.getElementById('word').innerHTML this would get the initial innerHTML which would be nothing. You have to get the inner text within word every single time the button is clicked to get the most recent text inside the textbox.
Finally, for a input node you should get .value rather than .innerHTML to get the inner text
html:
<form>
<label>Word</label><input id="word"></input>
<input type="button" value="submit" id="submitButton"></input>
</form>
<p id="story"> A {userWord goes here} is now part of the story </p>
javascript:
var word = document.getElementById('word'),
originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(){
replaceStory(word.value);
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
return originalStory.innerHTML = story;
};
I advise you to just understand Javascript first, and after then, focus on learning Jquery because it's much more easier and handy.
By the way if you want to do what you said:
You shouldn't use form tag, because you don't want to send something to server-side and you can use div tag as well instead of form tag.
<div>
<label>Word</label>
<input id="word" type="text"></input>
<button id="submitButton">Submit</button>
</div>
<span>A </span><span id="text">{here}</span><span> is now part of the story</span>
Jquery
$('#submitButton').click(function(){
txt = $('#word').val()
$('#text').text(txt);
});
Don't forget to import Jquery Package.
https://jsfiddle.net/softiran/gt8rr5pe/
You could also allow the user to change your story directly. I know this may not use an input tag, but it was very useful to me.
<div id="story">Once upon a time there was a man named
<p id="added" contenteditable="true" title="Click to change">
Bill</p>. He liked to eat tacos.</div>
I used this in a code that changed the name of the main character of a story into a user-selected name and allowed them to download the story. Hope this helps! All the user has to do is click the name "Bill" and they will be able to change the name to anything they want.

Can I Insert a Javascript Array to my PHP form?

Long story short:
I have a long list of check boxes for adding options to a purchase (TV, Radio, Stove, etc.)
Now I need to insert a LogIn form When they hit next (cut down on the number of quotes created/stored with no customer contact info).
But I was loosing all the options selected and would have to make the customer input again.
So I added an on-click - add to array function for the option id's selected. So that I could collect the ID's before submitting form.
Now the problem... How to send that array to the server with the php form, and I am way to new to Java.
In my research - I can either add the array values to the form action ?optionids=34,891,679,etc
Ugly but O.K.
What I would like is ... If this makes sense.. on-click of next button document.write
My code so far: (in )
<script type="text/javascript">
var numArray = [];
function addToArray(num){
numArray.push(num);
document.getElementById("pTxt").innerHTML = numArray;
return false;
}
</script>
<script>
function jstophp(){
var javavar=document.getElementById("pTxt").value;
document.getElementById("rslt").innerHTML="<?php
$phpvar='"+javavar+"';
echo $phpvar;?>";
}
</script>
I can see the values go in at
<div id="pTxt"></div>
But I can't pull them back out.
Any advice?
You should name your html inputs so that they become an array automatically in the $_POST
<input type="checkbox" name="options[tv]" value="tv">
<input type="checkbox" name="options[radio]" value="radio">
<input type="checkbox" name="options[stove]" value="stove">
Your $_POST will look something like:
options =>
tv => tv,
radio => radio
...
If that is not an option, use a hidden input element rather than a DIV to store your array:
<input type="hidden" id="pTxt" name="idList">
<script>
var numArray = [];
function addToArray(num){
numArray.push(num);
document.getElementById("pTxt").value = numArray;
return false;
}
</script>

Categories

Resources