I am trying to make a button to add another input box every time it is clicked but I also want it to add an increasing number the end of the input name. I have this code to add more inputs.
<script type="text/javascript">
function addInput()
{
var x = document.getElementById("inputs");
x.innerHTML += "<input type=\"file\" name=\"photo\" />";
}
</script>
What can I do to make it so that every time a new form is added it will add a higher number to the end of name="photo" so that I can process images with my php script correctly?
default the form is:
<input type="file" name="photo">
but I would like to add a number to the end of photo every time a new input is made to have an output like this.
<input type="file" name="photo">
<input type="file" name="photo2">
<input type="file" name="photo3">
<input type="file" name="photo4">
etc
You can use [] in your form name, then your php script will automatically convert those inputs into an array, that way you don't even have to worry about appending numbers anymore.
<input type="file" name="photo[]">
If you want to do it using javascript, easiest way is to have a variable that keeps track of the number of inputs
var inputNumber = 0;
function addInput()
{
var x = document.getElementById("inputs");
x.innerHTML += "<input type=\"file\" name=\"photo\"" + inputNumber + " />";
inputNumber++;
}
Declare a count and initialize it to 0, then increase it in every call.
<script type="text/javascript">
var count=0;
function addInput()
{
var x = document.getElementById("inputs");
x.innerHTML += '<input type=\"file\" name=\"photo\"'+count+' />;
count++;
}
</script>
andeas's answer is probably best for this specific situation. But in general if you want a counter that will increase every time a function is called, try:
(function {
var counter = 0;
window.myfunction = function() {
// do stuff, use counter if needed
counter++;
}
})();
counter can be treated as if it were a static variable in this context.
Related
I have a basic js function that connects to my html file. I want the user to input a number and then the function will count up to that number. As it counts it will display a circle with each number. So, input 3 and you'll see three circles counting 1, 2, 3 horizontally on the page.
When I call the function and hard code an input like:
display(9)
it works fine.
I console log my user input, I console log as I loop through and it's counting just fine, but for some reason,
const button = document.getElementById("button");
const main = document.querySelector("main");
let number = "";
function display(num) {
for (let i = 1; i <= num; i++) {
console.log("in the loop " + i);
number += `<div>${i}</div>`;
}
}
button.addEventListener('click', () => {
let input = parseInt(document.getElementById("input").value);
console.log(input);
display(input);
});
document.getElementById("display").innerHTML = number;
<h1 class="h1">Test Form</h1>
<input class="input" id="input" type="text" />
<input type="button" id="button" value="Enter" />
<p class="display" id="display"></p>
it won't display anything using user input.
My code is below. Thoughts? And thank you for the help!
You just add the following statements to the end of display function to make it work.
let displayDiv=document.getElementByI("display");
displayDiv.innerHTML=number;
first of all i'm not a programmer of any kind, so i please need you to fix my issue.
I have a contact form which have inside a place where i can add more input fields till a maximum of 10.
Each field i add it has inside the code a class that i called "pers", and i want that this class pers has an incremental number near to it, as pers1, 2, 3 and so go on.
Getting the incremental value was easy but the problem is that the class "pers" wont update the variable keeping the first number on document load.
Here is the code
<script type="text/javascript">
window.s = 1;
</script>
<script type="text/javascript">
$(document).ready(function() {
var addButton = $('.add_button');
var wrapper = $('.field_wrapper');
var maxField = 10;
var fieldHTML = '<div style="margin-top:5px;"><input type="text3" name="pers' + window.s + '" placeholder="Nome e Cognome"/><input type="time" style=margin-left:3.5px; autocomplete="off"><input type="time" style=margin-left:3.5px; autocomplete="off"><img src="IMG/less_icon.png"></div>';
$(addButton).click(function() {
if (window.s < maxField) {
window.s++; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
}
});
$(wrapper).on('click', '.remove_button', function(e) {
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
s--; //Decrement field counter
});
});
</script>
There is a global variable "window.s" because it was my last try to get the var updated.
The fields adds correctly till 10 as it should be, but the "window.s" or when it was only "s" still keeps his first value of 1, and so "pers" is always "pers1". I thought that exposing a global variable i would have fix the problem, but nothing.
What am i doing wrong?
Thank you very much for your help guys.
The problem with your code is because you only set fieldHTML once, when the page loads. At this point window.s is 1, so this is the value that's used every time you reference fieldHTML. The quick fix to this would be to put the fieldHTML definition inside the click() event handler.
However the better approach it to entirely remove the need for the incremental variable at all. Use the same name on all the fields you dynamically generate. This way you don't need to maintain the count (eg. if there have been 5 added and someone deletes the 3rd one, you'll currently end up with 2 per5 elements). Because of this it also simplifies the JS logic. In addition you should put the HTML to clone in a <template> element, not the JS, so that there's no cross-contamination of the codebase.
Here's a working example of the changes I mention:
jQuery($ => {
var $addButton = $('.add_button');
var $wrapper = $('.field_wrapper');
var maxFields = 10;
var fieldHTML = $('#field_template').html();
$addButton.click(() => {
if ($('.field_wrapper > div').length < maxFields) {
$wrapper.append(fieldHTML);
}
});
$wrapper.on('click', '.remove_button', e => {
e.preventDefault();
$(e.target).closest('div').remove();
});
});
.field_wrapper>div {
margin-top: 5px;
}
.field_wrapper input.time {
margin-left: 3.5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<button class="add_button">Add</button>
<div class="field_wrapper"></div>
<template id="field_template">
<div>
<input type="text3" name="pers[]" placeholder="Nome e Cognome" />
<input type="time" name="time1[]" class="time" autocomplete="off" />
<input type="time" name="time2[]" class="time" autocomplete="off" />
<a href="#" class="remove_button" title="Rimuovi">
<img src="IMG/less_icon.png">
</a>
</div>
</template>
You can then receive all the input values as an array in your PHP code, like this.
It's because you have not used the updated value there.
First, you assign a value to window.s, and then you create a variable that uses the value of window.s from the initial state, and on each addition, it just appends the same fieldHtml. So, you are getting the same value.
Here is the answer, you are looking:
<div><button class="add_button">click me</button></div>
<div class="field_wrapper"></div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script type="text/javascript">
window.s = 1;
</script>
<script type="text/javascript">
$(document).ready(function() {
var addButton = $('.add_button');
var wrapper = $('.field_wrapper');
var maxField = 10;
$(addButton).click(function() {
if (window.s < maxField) {
window.s++; //Increment field counter
let fieldHTML = generateLine(window.s);
$(wrapper).append(fieldHTML); //Add field html
}
});
$(wrapper).on('click', '.remove_button', function(e) {
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
s--; //Decrement field counter
});
});
function generateLine(lineNumber){
return '<div style="margin-top:5px;"><input type="text3" name="pers' + lineNumber + '" placeholder="Nome e Cognome"/><input type="time" style=margin-left:3.5px; autocomplete="off"><input type="time" style=margin-left:3.5px; autocomplete="off"><img src="IMG/less_icon.png"></div>';
}
</script>
I basically have an input of type number
<input type="number" id="no_pi" name="" onkeyup="des()">
<div id="extract"></div>
and function
function des() {
var ext = document.getElementById('extract');
var va = Number(document.getElementById('no_pi').value);
for (var i = 0; i = va; i++) {
ext.innerHTML = "<input type='number' name='' class='form-control'><div class='input-group-text'>cm</div>";
}
}
I just want to instantly generate x number of inputs in div based on user input.
When the user input any number, the page just crashes down. I think the page is going in infinite loop, but I think it is not the case.
Any idea how to achieve this
There's several errors :
In your loop : i = va (this is why it crashes)
You erase the content of the div ext each time you iterate, instead of adding content
By listening on keyup event, you add some content on each key hit. Finally if the user submit 12, it will generate 1 + 12 elements. You should pass the value using a form (by doing this you can also add easily the value control in the input element).
As perfectly mentionned by #Andy in the comments, innerHTML += is a very bad idea. You should generate your elements using document.createElement or insertAdjacentHTML.
Some advices :
Use an event listener instead of the onkeyup attribute
Avoid this kind of variable names, be more explicit
Use const and let instead of var
Here's a version which fixes all that issues :
document.getElementById('elementsNumberForm').addEventListener('submit', event => {
event.preventDefault();
const targetElement = document.getElementById('extract');
const inputValue = document.getElementById('no_pi').value;
for (let i = 0; i < inputValue; i++) {
targetElement.insertAdjacentHTML('beforeEnd', '<input type="number" name="" class="form-control" /><div class="input-group-text">cm</div>');
}
});
<form id="elementsNumberForm">
<input type="number" id="no_pi" min="1" />
<input type="submit" />
</form>
<div id="extract"></div>
Your key issue is how you're using your loop. i = va isn't going to accomplish what you want. It should be a check that the index in the iteration is less than the number represented by the value in your input. It should be i < va.
The other issue is that you're not adding to the HTML, just ensuring that the HTML is just one input.
I've adjusted the code in your question to remove the inline JS and use addEventListener instead, and also to use an array to store the HTML built from the loop which can then be applied to the extract element.
// Cache the elements outside of the loop
// and attach a change listener to the noPi element
const extract = document.getElementById('extract');
const noPi = document.getElementById('no_pi');
noPi.addEventListener('change', des, false);
function des() {
const limit = noPi.value;
// Check that we haven't gone into
// negative numbers
if (limit >= 0) {
// Create an array
const html = [];
// Loop, pushing HTML into the array, until
// we've reached the limit set by the value in noPi
for (let i = 0; i < limit; i++) {
html.push('<input type="number" class="form-control"><div class="input-group-text">cm</div>');
}
// `join` up the array, and add the HTML
// string to the extract element
extract.innerHTML = html.join('');
}
}
<input type="number" id="no_pi" />
<div id="extract"></div>
Additional information
join
I see that you want to use an input field to insert the number of inputs to create.
I see a better way to start learning insert the number of inputs with a prompt, and then scale the project.
You can start like this: (hope it make sense to you)
<div style="height: 300px; background-color: #ccc;" class="container"></div>
we have this div that is going to be filled with the inputs
Then we have the script:
const container = document.querySelector('.container');
const runTimes = prompt("How many inputs wnat to create?");
for(let i = 0; i < runTimes; i++){
let newInput = document.createElement('input');
newInput.innerHTML = "<input type='number' name='' class='form-control'>";
container.appendChild(newInput);
}
In the for loop, we create the element input, then with the .innerHTML we add the HTML we want. to end the loop, we need to append the created input element to the div we have.
hope it makes sense to you, :)
when you get the idea with the prompt , I´ve done this project more pro jaja.
<div style="height: 300px; background-color: #ccc;" class="container"></div>
<input type="text" class="numberTimes" onkeyup="getValue()">
we add an event listener to the input with the function getValuue, and the script like this:
const container = document.querySelector('.container');
function getValue(){
let runTimes = document.querySelector('.numberTimes').value;
document.querySelector('.numberTimes').value= "";
for(let i = 0; i < runTimes; i++){
let newInput = document.createElement('input');
newInput.innerHTML = "<input type='number' name='' class='form-control'>";
container.appendChild(newInput);
}
}
This line document.querySelector('.numberTimes').value= ""; is to reset the input field.
So whenever insert a value on the input it creates that number of inputs in the container and cleans the input field :)
I am trying to create an add more button which will create a new input field. However, I would like to have an unique name set for it.
I tried to search up for an answer, but this does not answer my question.
So, basically what I tried to make my namefield unique is to use the php method rand(). The concept is that - when the add more button is clicked, it will have a name attached to the number given to me by rand().
However, what happens is that it takes the value generated by rand() and applies it to all the names of all the inputs generated.
This is my code and what I tried:
HTML:
<div class="field_wrapper">
<div>
<input type="text" name="field_name[<?php echo rand(); ?>]" value=""/>
Add More
</div>
</div>
JQUERY / JAVASCRIPT:
<script type="text/javascript">
$(document).ready(function(){
var maxField = 100; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div><input type="text" name="field_name[<?php echo rand(); ?>]" value=""/>Remove</div>'; //New input field html
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxField){
x++; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
</script>
As you can see, the first field generates the number as intended. If you click on the add more, the second field does create an unique number. However, if you click add more once again, the third field copies the same name as the 2nd field.
How do I go about achieving what I want and why is rand() not generating a new code?
Also, does rand() guarantee me that it will be an unique ID or is there a chance for it to repeat the same number?
If it does repeat, then what would be the best approach to take to make it as unique as possible?
If you generate random name with PHP it is done once on the server. Your JS code then copies the same element. What you need is to generate unique names with js.
Avoid random if you can, theoretically, you can hit the same number and run into mysterious bugs.
var generateField = function(name)
{
return '<div><input type="text" name="'+name+'" value=""/>Remove</div>'; //New input field html
}
//Once add button is clicked
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxField){
x++; //Increment field counter
$(wrapper).append(generateField('field_name['+x+']' ) ); //Add field html
}
});
Random does not necessarily mean unique, even if collisions would be extremely rare. This solution simply increments a totalFieldsCreated variable to get the next unique number (up to the maximum value JavaScript can provide.)
The new fields are created dynamically instead of using a fixed string of HTML. (This technique is more flexible.)
$(document).ready(function() {
// Defines global identifiers
let
currentFieldCount = 1,
totalFieldsCreated = 1;
const
maxFieldCount = 100,
addButton = $('.add_button'),
wrapper = $('.field_wrapper');
// Calls `addField` when addButton is clicked
$(addButton).click(addField);
// Executes anonymous function when `Remove` is clicked, which removes
// the parent div, and decrements (and logs) `currentFieldCount`
$(wrapper).on('click', '.remove_button', function(e) {
e.preventDefault();
$(this).parent('div').remove();
currentFieldCount--;
console.log(`currentFieldCount: ${currentFieldCount}`);
});
// Defines the `addField` function
function addField(){
// Makes sure that `currentFieldCount` and `totalFieldsCreated`
// are not at maximum before proceeding
if(
currentFieldCount < maxFieldCount &&
totalFieldsCreated < Number.MAX_VALUE
){
// Creates an input element, increments `totalFieldsCreated`,
// and uses the incremented value in the input's `name` attribute
const input = document.createElement("input");
input.type = "text";
input.name = "field" + ++totalFieldsCreated;
input.value = "";
// Creates an anchor element with the `remove_button` class
const a = document.createElement("a");
a.href = "javascript:void(0);";
a.classList.add("remove_button");
a.title = "remove";
a.innerHTML = "Remove";
// Adds the new elements to the DOM, and increments `currentFieldCount`
const div = document.createElement("div");
div.appendChild(input);
div.appendChild(a);
$(wrapper).append(div);
currentFieldCount++;
// Logs the new values of both variables
console.log(
`currentFieldCount: ${currentFieldCount},`,
`totalFieldsCreated ${totalFieldsCreated}`
);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="field_wrapper">
<div>
<input type="text" name="field1" value="" />
Add More
</div>
</div>
Try Math.random() in js rather than rand() in php ,Math.floor(Math.random()*90000) + 10000 will generate a five digit random number , Hope this helps
$('.rand').attr('name',"fields["+Math.floor(Math.random()*90000) + 10000+"]")
$('.add_button').click(function(e){
$('.field_wrapper').append('<div><input type="text" name=fields['+Math.floor(Math.random()*90000) + 10000+'] value=""/>Remove</div>')
})
$(document).on('click','.remove_button',function(e){
$(this).parent().remove()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="field_wrapper">
<div>
<input type="text" class="rand" value=""/>
Add More
</div>
</div>
I am trying to use JavaScript in an online examination assignment in HTML. As a requirement of the project, we have to use text input forms as well as radio buttons and the like. I have dealt with the part of radio buttons but for some reason my text input forms do not work. My problem will be clearly stated using this code snippet from the main project:
<html>
<head>
<title></title>
<script type="text/javascript">
var test, name, matr, myname, count = 0;
function form(){
test = document.getElementById("test");
test.innerHTML = "Count = "+count;
test.innerHTML += "<form> \
First name:<br> \
<input type='text' name='name'><br>\
<button onclick='check()'>Submit Answer</button>";
}
function check(){
myname = document.getElementsByName("name");
if (myname[1].value == "myname")
{
count++;
}
form();
}
window.addEventListener("load", form, false);
</script>
</head>
<body>
<div id = "test"></div>
</body>
</html>
What this code aims to do is that when the user inputs "myname" into the form called 'First name' and clicks 'Submit', the counter on the top should increment.
Can someone please shed some light on what I am doing wrong and how it may be resolved.
As Pluto mentioned, arrays in javascript start at 0. You can also look at tinkering with the form element. It is not closed nor is the type, get or post specified. I got it working in the example below by removing the form completely. This is because the button press was trying to submit the form and therefore load a new page.
https://jsfiddle.net/jpm68eub/
var test, name, matr, myname, count = 0;
function form() {
test = document.getElementById("test");
test.innerHTML = "Count = " + count;
test.innerHTML += "</br> First name:<br> \
<input type='text' name='name'><br>\
<button onclick='check()'>Submit Answer</button>";
}
function check() {
myname = document.getElementsByName("name");
if (myname[0].value == "myname") {
count++;
}
form();
}
form();
you need to prevent the default action of the onclick event. To do this, try something like this:
function check(e){
e.preventDefault();
myname = document.getElementsByName("name");
if (myname[0].value == "myname")
{
count++;
}
form();
}
the above user was also correct about where javascript arrays start (they start at 0)