I have to get 'n' - total number of names from the user and then create n number of fields for getting all the names. I've currently written this as:
HTML code:
<form action="/flight_ticket/book" name="myform" method="post">
.
.
.
Enter the number of tickets to be booked:
<input name="nooftickets" type="text"><br/><br/>
Enter names
<div id='container'/>
</div>
<br/><br/>
</form>
</body>
JS code:
function addFields(){
var number = parseInt(document.getElementById("nooftickets").value);
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
container.appendChild(document.createTextNode("Name " + (i+1)));
var input = document.createElement("input");
input.type = "text";
input.name = "name" + i;
//input.required= true;
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
But when I run it on browser, after clicking the "Enter names", I don't see any changes in the browser!
What have I got wrong?
What you are doing is trying to fetch the value of the noofticktes which is defined as a name in the HTML but in your code, you are using document.getElementById('noofticktes').value which is throwing an undefined error as there is no id defined as noofticktes.
So, just change your code on from:
var number = document.getElementById("nooftickets").value;
To this:
var number = document.getElementsByName("nooftickets")[0].value;
you will be able to make your code work.
One small update in your code would be if you are trying to clear/remove all the contents of the element container just use the container.innerHTML='' instead of looping and removing each element.
Here is the updated Snippet of your code.
function addFields() {
debugger;
var number = document.getElementsByName("nooftickets")[0].value;
var container = document.getElementById("container");
container.innerHTML = '';
for (i = 0; i < number; i++) {
container.appendChild(document.createTextNode("Name " + (i + 1)));
var input = document.createElement("input");
input.type = "text";
input.name = "name" + i;
//input.required= true;
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
<form action="/flight_ticket/book" name="myform" method="post">
. . . Enter the number of tickets to be booked:
<input name="nooftickets" type="text"><br/><br/>
Enter names
<div id='container' />
</div>
<br/><br/>
</form>
function addFields() {
// body...
var input = '';
var number = document.getElementById('number').value;
for(var i=0;i<number;i++)
{
input +="<input id='number"+i+"' name='number"+i+"'><br>";
}
document.getElementById('container').innerHTML = input;
}
<form action="/flight_ticket/book" name="myform" method="post">
Enter the number of tickets to be booked:
<input name="nooftickets" id="number" type="text"><br/><br/>
Enter names
<div id='container'/>
</div>
<br/><br/>
</form>
Related
when i add new input box with javascript function, previous input boxes become empty. here is the code:
<div id="field">
<input type="text">
</div>
<div id="error"></div>
<button onclick="Add()">add</button>
<script>
let i=0;
const Add=()=>{
i++
if(i<5)
document.getElementById('field').innerHTML+=`<input type="text" id="value${i}">`
else
document.getElementById('error').innerHTML='Error: Field cant be more then 5'
}
</script>
what can I do to NOT change input values of input box on adding new input box with above codes.
You are overwriting the entire HTML content of ID field,
let i = 0;
const Add = () => {
i++
if (i < 5) {
const input = document.createElement('input');
document.getElementById('field').appendChild(input);
} else
document.getElementById('error').innerHTML = 'Error: Field cant be more then 5'
}
<div id="field">
<input type="text">
</div>
<div id="error"></div>
<button onclick="Add()">add</button>
One way of doing it, keeping in mind separation of concerns and avoiding the creation of unnecessary global variables could be:
#error {
display: none;
}
<div id="field">
<input type="text">
</div>
<div id="error"></div>
<button onclick="Add()">add</button>
<script>
const Add = () => {
const inputContainer = document.querySelector('#field'); // this variable is not strictly necessary but I think it makes the code more readable
const inputNotification = document.querySelector('#error'); // this variable is not strictly necessary but I think it makes the code more readable
const inputCount = inputContainer.querySelectorAll('input[type=text]').length // count how many input elements of type text are already inside the `field` div
if (inputCount < 5) {
const txtInput = document.createElement('input');
txtInput.setAttribute('type', 'text');
txtInput.setAttribute('id', `value${inputCount}`);
inputContainer.append(txtInput);
} else {
inputNotification.innerText = 'Error: Field can\'t be more than 5';
inputNotification.style.display = 'block'
event.target.setAttribute('disabled', true); // optionally, you can disable the add button if you reached the maximum number of input fields
}
}
</script>
You could use Document.createElement() and element.appendChild() so that you do not alter the HTML of the div#field :
<div id="field">
<input type="text">
</div>
<div id="error"></div>
<button onclick="Add()">add</button>
<script>
let i=0;
const Add=()=>{
i++
if(i<5) {
let input = document.createElement("input");
input.type = "text";
input.id = "value" + i;
let button = document.createElement("button");
button.innerText = "delete";
button.onclick = function(){
input.remove(); //remove text input
this.remove(); //remove this delete button
i--; //decrement i
};
document.getElementById('field').appendChild(input);
document.getElementById('field').appendChild(button);
} else {
document.getElementById('error').innerHTML='Error: Field cant be more then 5';
}
}
</script>
When I use this code, I am unable to get it to display the data upon clicking the display button. The code is supposed to save the input upon clicking the next button and display the array upon clicking display and clear the array when clicking clear. How do I go about resolving this?
Whenever I click the buttons nothing happens. I want to display the array inside the text area.
<html>
<head>
<script language = "javascript">
var full_name;
var dob;
var gender;
var memberList= new Array();
function saveMember() {
// getElementById may only be used to get one item at a time
// store the .value in the variable
full_name = document.getElementById('full_name').value;
dob = document.getElementById('dob').value;
gender = document.getElementById('gender').value;
// add the values to the array
// (when storing the contents of a variable, use the variable name without quotes)
memberList.push(full_name, dob, gender);
}
function displayMembers() {
var str = " ";
var listLength = memberList.length;
// append all the elements in the array into a single string
for(var i = 0; i < listLength; i+=3) {
str += memberList[i]+", "+memberList[i+1]+", "+memberList[i+2]+"\n";
}
// Replace the contents of the textarea with the value in str
document.getElementById("textBox").value = str;
}
function clearList() {
memberList = [];
}
</script>
<title>INTERNET TECHNOLOGIES CLUB MEMBER LIST </title>
</head>
<body>
<form name = "memberForm">
<h1>
INTERNET TECHNOLOGIES CLUB MEMBER LIST
</h1>
Full Name: <input type = "text" id = "full_name" value = ""/>
Date of Birth: <input type = "text" id ="dob" value = ""/>
<br>
Gender: <input type = "text" id = "gender" value = ""/>
<br>
<textarea id = "textBox" rows = "10" cols = "70">
</textarea>
<br>
<input type = "button" value = "NEXT" onclick ="saveMember()"></button>
<input type = "button" value = "DISPLAY" onclick ="displayMembers()">
</button>
<input type = "button" value = "CLEAR" onclick ="clearList()"></button>
</form>
</body>
</html>
your code is working..remove </button> in your html
I thing you expecting like this: declare the array like var memberList= [];.If you click the clear button Array was empty and textarea also empty.If you need only empty with array.remove document.getElementById("textBox").value=""; in clearlist()
var full_name;
var dob;
var gender;
var full_name;
var memberList= [];
function saveMember() {
// getElementById may only be used to get one item at a time
// store the .value in the variable
full_name = document.getElementById('full_name').value;
dob = document.getElementById('dob').value;
gender = document.getElementById('gender').value;
// add the values to the array
// (when storing the contents of a variable, use the variable name without quotes)
memberList.push(full_name, dob, gender);
}
function displayMembers() {
var str = " ";
var listLength = memberList.length;
// append all the elements in the array into a single string
for(var i = 0; i < listLength; i+=3) {
str += memberList[i]+", "+memberList[i+1]+", "+memberList[i+2]+"\n";
}
document.getElementById("textBox").value = str;
}
function clearList() {
memberList = [];
document.getElementById("textBox").value="";
}
<form name = "memberForm">
<h1>
INTERNET TECHNOLOGIES CLUB MEMBER LIST
</h1>
Full Name: <input type = "text" id = "full_name" value = ""/>
Date of Birth: <input type = "text" id ="dob" value = ""/>
<br>
Gender: <input type = "text" id = "gender" value = ""/>
<br>
<textarea id = "textBox" rows = "10" cols = "70">
</textarea>
<br>
<input type = "button" value = "NEXT" onclick ="saveMember()">
<input type = "button" value = "DISPLAY" onclick ="displayMembers()">
<input type = "button" value = "CLEAR" onclick ="clearList()">
</form>
you have written "</button>" as closing tag, which is incorrect syntax for input tag.
<input type = "button" value = "NEXT" onclick ="saveMember()"></button>
<input type = "button" value = "DISPLAY" onclick ="displayMembers()"></button>
<input type = "button" value = "CLEAR" onclick ="clearList()"></button>
replace this with the following and your code will work fine.
<input type = "button" value = "NEXT" onclick ="saveMember()"/>
<input type = "button" value = "DISPLAY" onclick ="displayMembers()"/>
<input type = "button" value = "CLEAR" onclick ="clearList()"/>
also change these functions for proper functioning
function saveMember() {
full_name = document.getElementById('full_name').value;
dob = document.getElementById('dob').value;
gender = document.getElementById('gender').value;
memberList.push(full_name, dob, gender);
document.getElementById('full_name').value = "";
document.getElementById('dob').value = "";
document.getElementById('gender').value = "";
}
function clearList() {
memberList = [];
document.getElementById("textBox").value = str;
}
I am trying to get a forloop with input elements to run between a form and create a form dynamically with javascript
1: in scenario one , the form in the script is getting closed before the input elements populate.
2: in scenario two , when i put the for loop variable between the form ,the error that comes is undefined .
PLEASE HELP
SCENARIO ONE
<form>
No of Feilds <input type="text" id= "numberoffeilds">
<input type="button" value = "Create Feilds" onclick= "addfeilds1();">
</form>
<div id= "div4" style= "color:gray"></div>
<script>
function addfeilds1()
{
var totalfeilds = document.getElementById("numberoffeilds").value;
var i;
document.getElementById("div4").innerHTML += '<form action= "issue.html" method = "POST">';
for(i=0;i<totalfeilds;i++)
{
document.getElementById("div4").innerHTML += '<input type = "text">';
}
document.getElementById("div4").innerHTML += '<input type = "submit" value="submit" name="submit">';
}
</script>
SCENARIO TWO
<form>
No of Feilds <input type="text" id= "numberoffeilds">
<input type="button" value = "Create Feilds" onclick= "addfeilds2();">
</form>
<div id= "div4" style= "color:gray"></div>
<script>
function addfeilds2()
{
var totalfeilds = document.getElementById("numberoffeilds").value;
var i;
function forloop()
{
for(i=1 ;i<totalfeilds;i++)
{
document.getElementById("div4").innerHTML += '<input type = "text">';
}
}
var loopvar = forloop();
document.getElementById("div4").innerHTML += '<form action= "issue.html" method = "POST">'+
'<input type = "text">'+
loopvar + // it shows the loop as undefined
'<input type = "text">'+
'<input type = "text">'+
'<input type = "submit" value="submit" name="submit">';
}
</script>
You need to build the HTML elements in a string first and add them to the div as a last step.
Fixed scenario 1:
function addfeilds1()
{
var totalfeilds = document.getElementById("numberoffeilds").value;
var i;
var htmlString = "";
htmlString += '<form action= "issue.html" method = "POST">';
for(i=0;i<totalfeilds;i++)
{
htmlString += '<input type = "text">';
}
htmlString += '<input type = "submit" value="submit" name="submit">';
document.getElementById("div4").innerHTML = htmlString;
}
This prevents the form tag from being closed before it's populated with inputs.
Fixing scenario 2:
function forloop()
{
var htmlString = "";
for(i=1 ;i<totalfeilds;i++)
{
htmlString += '<input type = "text">';
}
return htmlString; // now forloop returns a string that can be added to the element. It no longers returns undefined.
}
Actually scenario 2 was fixing scenario 1, but you didn't include a return in your function. If you expect a function to create some text and concat that into a string you need your function to return a string.
Third example (advanced)
function addfeilds1()
{
var totalFields = parseInt(document.getElementById("numberoffeilds").value); //parse integer from value
if (isNaN(totalFields) || totalFields < 1)
{
//check if the input is valid, if not alert.
alert("Value is not a valid number or lower than 1.");
}
var container = document.getElementById("div4");
//create the form
var form = document.createElement("form");
form.setAttribute("action", "issue.html");
form.setAttribute("method", "POST");
for(var i=0; i<totalFields; ++i)
{
var node = document.createElement("input");
node.setAttribute("name", "field[]"); //this sends a array to the request page containing all input field values.
form.appendChild(node); //add the fields to the form.
}
//create the submit button.
var button = document.createElement("input");
button.setAttribute("type", "submit");
button.setAttribute("value", "submit");
button.setAttribute("name", "submit");
form.appendChild(button);
container.appendChild(form); //append the form to the div.
}
Hi I am trying to make five buttons as you can see and I want a function when you push "click me" it will fill up the five button randomly.
It's like a random generator for stats for a game.
I don't know if I'm doing it all wrong but I think I need some other coding for this.
Can anyone that can help me?
This is what I have:
<button onclick='myFunction()'>click me</button>
<div id="demo">
<Input type = radio Name = r1>
<Input type = radio Name = r2>
<Input type = radio Name = r3>
<Input type = radio Name = r4>
<Input type = radio Name = r5>
</div>
<script type="text/javascript">
function myFunction() {
document.getElementById('demo').innerHTML = '';
var num = 3;
var noOfButtons = Math.floor(Math.random() * num);
console.log(noOfButtons);
for (var i = 0; i < noOfButtons; i++) {
var box = document.createElement();
document.getElementById('demo');
}
}
</script>
not exactly sure what your looking for. I threw this JSFiddle together. Take a look and see if its what you're looking for.
<button id='button1'>click me</button>
<div id="demo">
<input type='radio' id='r1'>
<input type='radio' id='r2'>
<input type='radio' id='r3'>
<input type='radio' id='r4'>
<input type='radio' id='r5'>
</div>
.
var button1 = document.getElementById('button1');
button1.onclick = function () {
var noOfButtons = 5;
var pick = Math.floor(Math.random() * noOfButtons) + 1;
var radioBtn = document.getElementById('r' + pick);
radioBtn.checked = true;
}
[edit]
I think what you're trying to do is randomly check a finite number of radios, in which case there's no need to set demo's html to ''. I added the class myRadios to the tags of your radios (just in case there are other radios on the page that you don't want to include in the random checking), and then used the following function:
function myFunction() {
var radios = document.getElementsByClassName('myRadios');
for (var i=0; i<radios.length; i++)
{
radios[i].checked = ( (Math.random()*10) > 5) ? true : false;
}
}
Here is a a working fiddle. Let me know if this is the functionality you were looking for or if you have any questions about how it works :)
I found this fiddle and I am trying to get it to work...I can not figure out why the names are not being added to the list, for some reason Add button is acting like a submit button and I can not tell why...It should add all the numbers to a list so when I click submit, then it should send the numbers in an array..
JavaScript:
function bindName() {
var inputNames = document.getElementById("names").getElementsByTagName("inputNames");
for (i = 0; i < inputNames.length; i++) {
inputNames[i].onkeydown = function() {
if (this.value == "") {
setTimeout(deletename(this), 1000);
}
}
}
}
document.getElementById("addName").onclick = function() {
var num1 = document.getElementById("name");
var myRegEx = /^[0-9]{10}$/;
var myRegEx = /^[0-9]{10}$/;
var itemsToTest = num1.value;
if (myRegEx.test(itemsToTest)) {
var form1 = document.getElementById("names");
var nameOfnames = form1.getElementsByTagName("inputNames").length;
var newGuy1 = document.createElement("inputNames");
newGuy1.setAttribute("id", nameOfnames);
newGuy1.setAttribute("type", "text");
newGuy1.setAttribute("value", num1.value);
form1.appendChild(newGuy1);
num1.value = "";
bindName();
}
else {
alert('error');
}
};
HTML:
<h1>Enter Name</h1>
<div id="mainName">
<h2>name</h2>
<label for="name">Add Names: </label>
<input id="name" type="text">
<button id="addName">Add</button>
<form>
<div id="names">
</div>
<input METHOD="POST" action="text.php" type="submit" value="Submit">
</form>
</div>
I've seen
document.createElement("inputNames");
Shouldn't be
document.createElement("input");
?
Because this /^[0-9]{10}$/; will accept only 10 numbers and only that, try entering 1234567890 and you will see no error.
I'm not sure why your "name" field is restricted to 10 digit numbers, but I've got the thing to work.
http://jsfiddle.net/y8Uju/4/
I think the problem was that you were trying to create an element with the tag name inputNames, but that's not a valid tag. Instead I changed it to create inputs, and set the class to inputNames.