Question

Sorry for grammar mistakes. I have multiple dynamically created text fields (more than 100). how can i get the values of these fields. i don't know the number of fields. Please help me.

Example

<input type="text" name="id_1" />
<input type="text" name="id_2" />
<input type="text" name="id_3" />

................

<input type="text" name="id_100" />
Était-ce utile?

La solution

Use arrays:

<input type="text" name="id[1]" />
<input type="text" name="id[2]" />
<input type="text" name="id[3]" />

Then:

foreach($_POST['id'] as $key => $value) {
    echo "text $key = $value";
}

Autres conseils

If you mean you want to get their values in PHP easily, just name them like "name[]".

<form method="post" action="yourscript.php">
  <input type="text" name="input[]" />
  <input type="text" name="input[]" />
  <input type="text" name="input[]" />
  <input type="text" name="input[]" />
  <input type="text" name="input[]" />

  <input type="submit" value="Submit" />
</form>

This way you'll be able to get the values in yourscript.php. They'll be in $_POST['input']. Just loop over it using foreach to get the values:

foreach($_POST['input'] as $value) {
  // do what you want with the $value
}

Having index numbers in the names like this:

<input type="text" name="input[1]" />
<input type="text" name="input[2]" />

is redundant.

In HTML forms, using jQuery:

$(function() {
$("input[name^='id']").each(function() {
  var name = $(this).attr('name');  
  var inputValue = this.value;
  console.log(name + " : "+ this.value);
  });
});

Hoa about adding a hidden field to pass the number of fields to the processing script?

<input type='hidden' name='num_text_fields' valus='100>

The do a for loop to get the values

$num_text_fields = $_POST['num_text_fields'];

for ($i=1;$i<=$num_text_fields;$i++) 
    {
    $text_field_name = "id_" . $i;

    $value = $_POST[$text_field_name];

    // do something with $valus
    }

I think the best way to do it is to add a class element to your input.

Then you can be easily able to find them regardless of how many you have

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top