while loop is not working in javascript code? - javascript

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>

Related

Javascript create input field using a select element

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>

onchange javascript and adding elements

I am having an issue with javascript while trying to add a textfield to my form with "onchange", this is the code:
<!DOCTYPE html>
<html>
<body>
<form id="formdemo">
</form>
<p>Select a new car from the list.</p>
<select id="mySelect" onchange="myFunction()">
<option value="Volvo">33
<option value="1">1
<option value="Audi">Audi
<option value="BMW">BMW
<option value="Mercedes">Mercedes
<option value="Volvo">Volvo
</select>
<script>
function myFunction() {
if (document.getElementById("mySelect").value == "1") {
document.getElementById("formdemo").innerHTML = " First name: <input type = "text" name ="firstname">"
}
}
</script>
</body>
</html>
As you can see, I want to generate a text field when the user chose "1", but The problem is that when I choose the "1" value the text field does not appear.
But when I remove the "input type" code from javascript, code looks like this:
<script>
function myFunction() {
if (document.getElementById("mySelect").value == "1") {
document.getElementById("formdemo").innerHTML = " First name:"
}
}
</script>
It works!!, it shows the "First name:" to site.
Is this method that I am using just for strings or just for adding paragraphs and I should use another method to add forms, or I am using wrong syntax?
Thank you for reading this, have a good day.
Your code is fine, just in the innterHTML your have a little mistake.
document.getElementById("formdemo").innerHTML = " First name: <input type = "text" name ="firstname">"
and should be like
document.getElementById("formdemo").innerHTML = " First name: <input type='text' name='firstname'>"
You're wrong in String input :
<form id="formdemo">
</form>
<p>Select a new car from the list.</p>
<script>
function myFunction() {
if (document.getElementById("mySelect").value == "1") {
document.getElementById("formdemo").innerHTML =
"First name: <input type=\"text\" name=\"firstname\">";
}
}
</script>
<select id="mySelect" onchange="myFunction()">
<option value="Volvo">33</option>
<option value="1">1</option>
<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Mercedes">Mercedes</option>
<option value="Volvo">Volvo</option>
</select>
the input should be like "First name: <input type=\"text\" name=\"firstname\">";
here is a fiddle :> Fiddle
You can try like this way
var input = document.createElement("textarea");
div.appendChild(input);

Get text from select tag in html

I have two dropdown menus named date and time respectively. I want to get the
text from the option tag when I click a button, but the javascript function does not seem to work. I 've found similar questions (and answers) about this but nothing worked. The code is below:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function collectData() {
var index = document.getElementById("date").selectedIndex;
var date = document.getElementById("date").options[index].text;
window.alert("You selected: " + date);
}
</script>
</head>
<body>
<select name="date">
<option value="1">date 1</option>
.....
</select>
<select name="time">
<option value="1">time 1</option>
.....
</select>
<button type="button" onclick="collectData()">Get data</button>
</body>
</html>
You're selecting the element by id but you didn't assign the id anywhere.
You need to add the correct id to the item:
<select id="date" name="date">
....
<select id="time" name="time">
Or you could select the items by name:
var index = document.getElementsByName("date")[0].selectedIndex;
Note: getElementsByName returns an array, thats why the [0] was added to select the first item that has that name.
Change code to
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function collectData() {
var e = document.getElementById("date");
var strUser = e.options[e.selectedIndex].value;
window.alert("You selected: " + strUser);
}
</script>
</head>
<body>
<select name="date" id="date">
<option value="1">date 1</option>
..
</select>
<select name="time">
..
</select>
<button type="button" onclick="collectData()">Get data</button>
</body>
</html>
Try this:
function collectData() {
var ddl = document.getElementById("dateSelect");
var text = ddl.options[ddl.selectedIndex].text;
window.alert("You selected: " + text);
}
<select id="dateSelect" name="date">
<option value="1">date 1</option>
<option value="2">date 2</option>
<option value="3">date 3</option>
</select>
<button type="button" onclick="collectData()">Get data</button>
Here a CodePen
you are using getElementById('date').so add id attribute to select element.

Adding several input boxes based by a select box value

I have a select box:
<select id="steps_number">
<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>
<option value="9">9</option>
<option value="10">10</option>
</select>
Now, if the user selects "4", then 4 input boxes needed to be added to the page, if he changes his selection to 8, 8 input boxes need to be there, an so on...
And also, the input boxes names are important, I'm gonna send the form values to another page for processing and inserting the data into db, how I could know/get the newly made input boxes names?
Very simple example (also demonstrated here):
// bind to when the drop-down list changes
$('#steps_number').change(function(){
// find out the number to display
var count = $(this).val();
// Try to keep the fields already on the page. Remove anything
// that exceeds the count
$('#steps input:gt('+(count-1)+')').remove();
// But if it doesn't have enough, add more
for (var i = $('#steps input').length; i < count; i++){
$('<input>',{type:'text',id:'step'+(i+1),name='step'+(i+1)}).appendTo('#steps');
}
});
This assumes you want the following structure for your inputs:
<div id="steps">
<input type="text" id="step1" name="step1" />
<input type="text" id="step2" name="step2" />
<input type="text" id="step3" name="step3" />
<!-- .... -->
</div>
And with regards to server-side, you'll now see the inputs using $_REQUEST['step1'], $_REQUEST['step2'], etc. Or, depending on your form method, they'll show up in $_POST or $_GET as well.
I wrote for you some basic functionality. But you need to extend it for your needs:
$('#steps_number')​.change(function(){
for(var i=0; i < parseInt($(this).val()); i++) {
$('body').append('<input type="text" name="someinput' + i + '">');
}
});​
See on jsFiddle
You could do something like this:
<html>
<head>
<title>Test</title>
<script language="javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script language="javascript">
$(document).ready(function(){
alert("ok");
$("#steps_number").change(function() {
var inputNum = $("#steps_number").val();
var inputCode = "";
for(i=0; i<inputNum; i++) {
inputCode += "<p class=\"inputBox\"><input id=\"inputBox_" + i + "\" size=\"20\" type=\"text\"></p>"
}
$("#inputBoxes").html(inputCode);
});
});
</script>
</head>
<body>
<form id="testform">
<select id="steps_number">
<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>
<option value="9">9</option>
<option value="10">10</option>
</select>
<div id="inputBoxes">
</div>
</form>
</body>
</html>
Here is my solution:
<select id="steps_number">
<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>
<option value="9">9</option>
<option value="10">10</option>
</select>
<div id="container"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$("#steps_number").on("change", function() {
var count = $(this).val()
$("#container").html("")
for (i=0;i<count;i++) {
$("<input>").appendTo("#container");
$("<br>").appendTo("#container")
}
})
</script>

Javascript Get Values from Multiple Select Option Box

This one is driving me nuts. It’s got to be something simple and stupid that I am overlooking.
I have a multiple select box in a form. I am just trying to get the values that are selected. In my loop, if I use alert then I have no problem. As soon as try to concatenate the values I get the error ‘SelBranch[...].selected' is null or not an object
<form name="InventoryList" method="post" action="InventoryList.asp">
<select name="SelBranch" class="bnotes" size="5" multiple="multiple">
<option value="All">All</option>
<option value="001 Renton">001 Renton</option>
<option value="002 Spokane">002 Spokane</option>
<option value="003 Missoula">003 Missoula</option>
<option value="004 Chehalis">004 Chehalis</option>
<option value="005 Portland">005 Portland</option>
<option value="006 Anchorage">006 Anchorage</option>
<option value="018 PDC">018 PDC</option>
</select>
<input type="button" name="ViewReport" value="View" class="bnotes" onclick="GetInventory();">
</form>
<script language="JavaScript">
function GetInventory()
{
var InvForm = document.forms.InventoryList;
var SelBranchVal = "";
var x = 0;
for (x=0;x<=InvForm.SelBranch.length;x++)
{
if (InvForm.SelBranch[x].selected)
{
//alert(InvForm.SelBranch[x].value);
SelBranchVal = SelBranchVal + "," + InvForm.SelBranch[x].value;
}
}
alert(SelBranchVal);
}
</script>
The for loop is getting one extra run. Change
for (x=0;x<=InvForm.SelBranch.length;x++)
to
for (x=0; x < InvForm.SelBranch.length; x++)
Here i am posting the answer just for reference which may become useful.
<!DOCTYPE html>
<html>
<head>
<script>
function show()
{
var InvForm = document.forms.form;
var SelBranchVal = "";
var x = 0;
for (x=0;x<InvForm.kb.length;x++)
{
if(InvForm.kb[x].selected)
{
//alert(InvForm.kb[x].value);
SelBranchVal = InvForm.kb[x].value + "," + SelBranchVal ;
}
}
alert(SelBranchVal);
}
</script>
</head>
<body>
<form name="form">
<select name="kb" id="kb" onclick="show();" multiple>
<option value="India">India</option>
<option selected="selected" value="US">US</option>
<option value="UK">UK</option>
<option value="Japan">Japan</option>
</select>
<!--input type="submit" name="cmdShow" value="Customize Fields"
onclick="show();" id="cmdShow" /-->
</form>
</body>
</html>
Take a look at HTMLSelectElement.selectedOptions.
HTML
<select name="north-america" multiple>
<option valud="ca" selected>Canada</a>
<option value="mx" selected>Mexico</a>
<option value="us">USA</a>
</select>
JavaScript
var elem = document.querySelector("select");
console.log(elem.selectedOptions);
//=> HTMLCollection [<option value="ca">Canada</option>, <option value="mx">Mexico</option>]
This would also work on non-multiple <select> elements
Warning: Support for this selectedOptions seems pretty unknown at this point
Also, change this:
SelBranchVal = SelBranchVal + "," + InvForm.SelBranch[x].value;
to
SelBranchVal = SelBranchVal + InvForm.SelBranch[x].value+ "," ;
The reason is that for the first time the variable SelBranchVal will be empty

Categories

Resources