Use Javascript to create multiple input with different ids automatically

Asked

Viewed 167 times

0

I am building a system that receives numbers and then passes them to a form, until then everything is working well, I can generate one or more input with the value I want, my problem is that when I send the form and I receive the data in php page it is only taking the value of 1 input, ignoring others, would have a way to generate these input in javascript add a number in front of id and name?

I’m wearing it like this:

<input type=\'hidden\' name=\'numeros\' id=\'numeros\' value=\''+MeuNumero(value)+'\'>

The php page that receives the data is like this:

if (isset($_POST["action"])){ 

   $nome=$_POST["nome"]; 
   $telefone=$_POST["telefone"]; 
   $numeros=$_POST["numeros"]; 


   echo "<p>Olá, ".$nome."</p>"; echo "<p>Os números escolhidos são: ".$numeros."</p>"; 

   echo "<p>Seu telefone é: ".$telefone."</p>"; 

} 

It creates an input for each selected number, but with the same attribute name and id, like this:

<input type="hidden" name="numeros" id="numeros" value="10">
<input type="hidden" name="numeros" id="numeros" value="11">
<input type="hidden" name="numeros" id="numeros" value="12">

I would like every new input created to put a number in front of the name and id attribute, so:

<input type="hidden" name="numeros1" id="numeros1" value="10">
<input type="hidden" name="numeros2" id="numeros2" value="11">
<input type="hidden" name="numeros3" id="numeros3" value="12">

etc....

And then receive on the php page all the inputs that javascript create, which will be from 1 up to a maximum of 10 inputs. I already have a lock that doesn’t let the person select more than 10 numbers at a time.

This way I did it creates the inputs with the selected value, but when I redeem these inputs in php page it only shows the first result.

I don’t know if I was clear, is that I didn’t find the technical term to use, I know that in programming to do something like: i++ . Well I tried to make it as clear as possible within my ignorance. I thank everyone who can help.

1 answer

1


Is this Marko blz? There is a very simple solution.

  1. Create the Names as an array in html. You rescue in PHP with the variable name $numeros as an array.

  2. If Ids are really needed, you can use the value itself (from the value field) as id.

They’ll stay that way:

<input type="hidden" name="numeros[]" id="num-10" value="10">
<input type="hidden" name="numeros[]" id="num-11" value="11">
<input type="hidden" name="numeros[]" id="num-12" value="12">
//No PHP
$numeros = $_POST['numeros'];

$numeros[0];
$numeros[1];
...

Hugs!

  • Thank you Tiago, it worked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.