Javascript create input field using a select element - javascript

I am trying to create a simple website that calculates a card game score. The website will prompt a user to enter the number of players and return that number of fields for name inputs.
However, as my code stands currently, when a user enters the number of players, the website only shows one field for maybe a second and disappears. I was hoping that someone could help me (a novice programmer) on how to create input text fields dynamically with Javascript. Thanks!
//*****script.js*****
let response = parseInt(document.getElementById("players").value);
const playerNames = () => {
let player;
for (let i = 0; i < response; i++) {
player = document.createElement('input');
player.type = 'text';
document.body.appendChild(player);
};
}
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<form class="start" action="index.html" method="post">
<p>How many players?</p>
<select id="players" class="" name="">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<input type="submit" value="Submit" onclick="playerNames()"/>
</form>
<script src="script.js"></script>
</body>
</html>

You need not wrap your fields in a <form>. If you do this, since your button is type of submit: by default your browser will attempt to submit the form to another page & redirect. You can simply use <div> as a wrapper. Once you do this, you can remove the HTML attributes action & method since these attributes are no longer essential to your code base as you are no longer submitting a form.
As for the script, simply move the gathering of the input inside of the function not outside. So onclick event, that is the time you get the input from the <select>
<body>
<div class="start">
<p>How many players?</p>
<select id="players" class="" name="">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<button onclick="playerNames()">Submit</button>
</div>
<script>
//*****script.js*****
const playerNames = () => {
let response = parseInt(document.getElementById("players").value);
let player;
for (let i = 0; i < response; i++) {
player = document.createElement('input');
player.type = 'text';
document.body.appendChild(player);
};
}
</script>
</body>

When you submit the action takes hold and index.html is loaded. Use event.preventDefault() to stop this load. place response inside the function so each time submit is pressed it captures the value of the select box
//*****script.js*****
const playerNames = () => {
event.preventDefault();
let response = parseInt(document.getElementById("players").value);
let player;
for (let i = 0; i < response; i++) {
player = document.createElement('input');
player.type = 'text';
document.body.appendChild(player);
};
}
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<form class="start" action="index.html" method="post">
<p>How many players?</p>
<select id="players" class="" name="">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<input type="submit" value="Submit" onclick="playerNames()"/>
</form>
<script src="script.js"></script>
</body>
</html>

Related

How to enable disable text input while making my function modular

Here is my script, what my goal is if other is selected in select, the other text input beside it will be enabled, this is what i've got so far, any approach will be really appreciated, I have 4 questions like this and I want it to be modular, best approach for doing my function to be reuseable.. How do I properly do this without any problem posting my data as 2 name inputs will generate 2 post variables in php.. T_T
<script type="text/javascript" charset="utf-8">
function validate()
{
var ddl = document.getElementById("cause_pain");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == "OTHER")
{
document.getElementsByClassName("causepain")[0].removeAttribute("name");
document.getElementsByClassName("causepain1")[0].removeAttribute("disabled");
}
}
</script>
<form action="test.php" method="GET">
<select class="select causepain" id="cause_pain" name="cause_pain" onchange="validate()">
<option value="" selected="selected">Select Cause of Pain</option>
<option value="ARTHRITIS">ARTHRITIS</option>
<option value="RHEUMATISM">RHEUMATISM</option>
<option value="OLD AGE">OLD AGE</option>
<option value="ACTIVE LIFESTYLE WHEN YOUNGER">ACTIVE LIFESTYLE WHEN YOUNGER</option>
<option value="OTHER">OTHER</option>
</select>
<input class="causepain1" type="text" id="cause_pain" name="cause_pain" size="40" onkeyup="clean('this.id')" disabled>
<input type="submit" id="submit"/>
</form>
This method is reusable and pretty straight forward. Using data attributes, you could specify the element that needs to be shown on the specific option element. Also before showing any input element hide the elements that were attributed to the previous selection.
Example:
<form action="test.php" method="GET">
<select class="select causepain" id="cause_pain" name="cause_pain">
<option value="" selected="selected">Select Cause of Pain</option>
<option value="ARTHRITIS">ARTHRITIS</option>
<option value="RHEUMATISM">RHEUMATISM</option>
<option value="OLD AGE">OLD AGE</option>
<option value="ACTIVE LIFESTYLE WHEN YOUNGER">ACTIVE LIFESTYLE WHEN YOUNGER</option>
<option value="OTHER" data-show="cause_pain_other">OTHER</option>
</select>
<input class="causepain1" type="text" id="cause_pain_other" name="cause_pain" size="40"
onkeyup="clean('this.id')" disabled style="display: none;">
<input type="submit" id="submit"/>
</form>
<script type="text/javascript" charset="utf-8">
var selectedOpt;
function selectionChanged(e) {
if (selectedOpt && selectedOpt.dataset.show) {
var showEl = document.getElementById(selectedOpt.dataset.show);
showEl.disabled = true;
showEl.style.display = 'none';
}
selectedOpt = this.querySelector('[value="'+e.target.value+'"]');
if (selectedOpt.dataset.show) {
var showEl = document.getElementById(selectedOpt.dataset.show);
showEl.disabled = false;
showEl.style.display = 'block';
}
}
document.querySelector('select').addEventListener('change', selectionChanged);
</script>
Your selectedOpt should be an object if you're using multiple selects on the same page and then just add the element to the object with the id as an index:
var selectedOpt = {};
...
selectedOpt[this.id] = this.querySelector('[value="'+e.target.value+'"]');

HTML javascript not working

I have this html with javascript, but I don't know why it's not working. It's right now supposed to calculate the values of the two textboxes when the button is pressed. However nothing is happening.
Code:
<!DOCTYPE html>
<html>
<body>
<h1>HTML Räpellys 2</h1>
<select id="mathType">
<option value="0">Addition</option>
<option value="1">Subtraction</option>
<option value="2">Multiplication</option>
<option value="3">Division</option>
<option value="4">Shift Left</option>
<option value="5">Shift Right</option>
<option value="6">Increment</option>
<option value="7">Decrement</option>
<option value="8">AND</option>
<option value="9">OR</option>
<option value="A">XOR</option>
</select>
<p></p>
<form>
Value 1: <input type="text" id="val1" value=""></input>
<p></p>
Value 2: <input type="text" id="val2" value=""></input>
</form>
<p></p>
<button onclick="mathFunc">Calculate!</button>
<p></p>
<script>
function mathFunc() {
var box1 = document.getElementById("val1").value;
var box2 = document.getElementById("val2").value;
if (document.getElementById("mathType").value == 0) {
document.write(box1 + box2);
}
}
</script>
<noscript>Java is required to display this element!</noscript>
</body>
</html>
The issue is that the function should be called on click: onclick="mathFunc()".
Generally, I would recommend you not to use document.write in the code but for debugging purposes use browser console and console.log function.
MDN: https://developer.mozilla.org/en/docs/Debugging_JavaScript#Console.log_in_Browser_Console
the <form> tag should contain the form elements...
eg
<form>
<select...
then I'd also make sure I don't get the string value of the input fields byt wrapping them with parseFloat(). eg:
var box1 = parseFloat( document.getElementById("val1").value ) ;
you also need to call the function as a function, basically what VisioN said above:
onclick="mathFunc()"

Local Storage With JavaScript

I want to store a string locally so when the user reloads the page it saves what was last there.
I looked at this and tried to implement it.
I had this code which basicllay has a button and a dropdown list of colors to change the background.
When I close and reopen the doc I want it to be the color that I saved.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="">
<label>
<select id="color">
<option value="#FFFFFF">White</option>
<option value="#FF0000">Red</option>
<option value="#FFCC00">Orange</option>
<option value="#FFFF00">Yellow</option>
<option value="#00FF00">Green</option>
<option value="#0000FF">Blue</option>
<option value="#663366">Indigo</option>
<option value="#FF00FF">Violet</option>
</select>
</label>
<input type="button" onClick="inputForm()" value="change color"/>
<form>
<script language="JavaScript">
<!--
function inputForm(){
var color = document.getElementById("color");
var outputContents=color.value;
document.body.style.backgroundColor = outputContents;
}
//-->
</script>
</body>
</html>
I made this code to do that but it didn't work
<!DOCTYPE html>
<html>
<head>
</head>
<body onload="storeColor()">
<form action="">
<label>
<select id="color">
<option value="#FFFFFF">White</option>
<option value="#FF0000">Red</option>
<option value="#FFCC00">Orange</option>
<option value="#FFFF00">Yellow</option>
<option value="#00FF00">Green</option>
<option value="#0000FF">Blue</option>
<option value="#663366">Indigo</option>
<option value="#FF00FF">Violet</option>
</select>
</label>
<input type="button" onClick="inputForm()" value="change color"/>
<input type="button" onClick="storeColor()" value="save color"/>
<script>
var outputContents;
function inputForm(){
var color = document.getElementById("color");
outputContents=color.value;
document.body.style.backgroundColor = outputContents;
}
function storeColor(){
// Store
localStorage.color = outputContents;
// Retrieve
document.body.style.backgroundColor = outputContents;
}
</script>
<form>
</body>
</html>
Local storage in JavaScript is uses (key, value) pairs of strings so if you wanted to save the value This is my test value. you would need to give it a key that you can get it from later, for example myTestValue.
So in code this would be
// set the value in window.localStorage
window.localStorage.setItem('myTestValue', 'This is my test value.')
// get the value from window.localStorage
window.localStorage.getItem('myTestValue')
Here is some more information: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
You code is almost complete. You only need to apply background color on window load. I added one more function applyColor:
function applyColor(color) {
color = color || localStorage.color;
document.body.style.backgroundColor = color;
// Select corresponding option in selectbox
var select = document.getElementById("color");
for (var i = 0; i < select.options.length; i++) {
if (select.options[i].value == color) {
select.options[i].selected = true;
return;
}
}
}
applyColor();
Also note that when page is loaded we should also select the option from selectbox corresponding to currently saved color.
Demo: http://jsfiddle.net/sd2Cx/

assign a javascript variable value depends on html drop down list section

I have a drop html list. If I select an option from dropdown, I have to assign dropdown value to the javascript variable and display it on html
Here is my code
HTML:
<form method="post">
<select id="dropdown" name="dropdown" onchange="changeHiddenInput(this)">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<input type="hidden" name="hiddenInput" id="hiddenInput" value="" />
<button onclick="changeHiddenInput (objDropDown)">Try it</button>
</form>
<div id="result"> </div>
Javascript:
function changeHiddenInput (objDropDown)
{
var objHidden = document.getElementById("hiddenInput");
objHidden.value = objDropDown.value;
var a = objHidden.value;
result.innerHTML = a || "";
}
But whenever I am submitting the values,it giving error. anything wrong here ?
DEMO
On your demo, you've selected the default onLoad option in jsfiddle.
This causes the site to wrap your entire code within a callback function, meaning that your showit function is not a global function as required by DOM0 inline event handlers.
Change this option to no wrap(head) and it will work.
The code you have will work good on a page, assuming you have the <script> tags for the javascript.
Fiddle here
About your <button onclick="changeHiddenInput (objDropDown)">Try it</button>, objDropDown is not defined... and also add type="button" otherwise the default is a submit button.
I made some changes for the demo, so my code is:
html
<form method="post">
<select id="dropdown" name="dropdown" onchange="changeHiddenInput(this)">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<input type="hidden" name="hiddenInput" id="hiddenInput" value="" />
<button onclick="changeHiddenInput (objDropDown)">Try it</button>
</form>
<div id="result"> </div>
javascript
var select;
window.onload = function () {
select = document.getElementById('dropdown');
console.log(select);
}
function changeHiddenInput(objDropDown) {
console.log(objDropDown);
var objHidden = document.getElementById("hiddenInput");
objHidden.value = objDropDown.value;
var a = objHidden.value;
result.innerHTML = a || "";
}

while loop is not working in javascript code?

In this code I'm trying to generate dynamic text fields based on the input of select field which handled by addInput(divname) function using on change event but the while loop inside addInput function is not working and when i remove while loop its working. i have to generate selected no. of text fields... and also the text fields should change when i select different number...
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="adduniv.php" method="post">
University Name: <input type="text" name="college">
No. of branches:
<div id="dynamicInput">
<select name="branches" id="branches" onchange="if (this.selectedIndex) addInput('dynamicInput');;" ">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
</div>
<script>
var counter = 0;
var limit = 3;
function addInput(divName)
{
var k=parseInt(document.getElementById("branches"));
var newdiv;
while(k>0)
{
newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
k--;
}
}
</script>
<input type="submit" value="submit" />
</form>
</body>
</html>
var k=parseInt(document.getElementById("branches"))
You can't parseInt a DOM element.
Suspect you meant
var k=parseInt(document.getElementById("branches").value,10)
with thanks to the comment from Shikiryu re: specifying the radix explicitly.
document.getElementById("branches") returns a DOM-Node, but what you need to do, is to get the value of this DOM-Node. So try the following to generate k.
var k=parseInt(document.getElementById("branches").value);
change the line
var k=parseInt(document.getElementById("branches"));
to
var k=parseInt(document.getElementById("branches").value);
i think you forgot to add .value to document.getElementById("branches")
parseInt(document.getElementById("branches"));
will result in NaN as far as I can tell. You are trying to parse a whole DOM node as an integer, what did you expect? You might want to get the value property from it:
parseInt(document.getElementById("branches").value, 10);
Ok, I know the problem was solved, but I would try do this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Creating input fields</title>
<script>
function addInput(nr_branches) {
var nCounter = 0;
//-- Cleaning all elements
var divB = document.getElementById('divBranches');
if(divB.hasChildNodes()) {
while(divB.childNodes.length >= 1) {
divB.removeChild(divB.firstChild);
}
}
while(nCounter < nr_branches) {
//-- Create a input field
var input = document.createElement("input");
input.type = 'text';
input.name = 'branche_nr_' + nCounter;
input.placeholder = 'Branche Nr.' + nCounter;
//document.getElementById("divBranches").innerHTML = "<input type='text' name='branche_nr_'"+ nCounter +" placeholder='Branche Nr."+ nCounter +"' />";
document.getElementById('divBranches').appendChild(input);
nCounter++;
}
}
</script>
</head>
<body>
<form name="frm" action="adduniv.php" method="post">
<input type="text" name="college" placeholder="University Name" />
<select name="branches" id="branches" onchange="addInput(this.value)">
<option value="0">-select your branche-</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
<div id="divBranches"></div>
<input type="submit" value="submit" />
</form>
</body>
</html>

Categories

Resources