1

I have a page that allows the user to add and remove text fields to a form using JavaScript.

Text fields are named field1, field2, field3, etc. and depends on how many fields the user has added

I'm trying to store all the values from my text fields into one Php variable;

I understand that i need to store them into an array first and then use implode(), but how can i specify how many inputs there are within my Php code?

3 Answers 3

2

Usually the best way to approach this is to use array-named input, as shown in the following example in the PHP docs:

<form action="" method="post">
    Nombre:  <input type="text" name="personal[nombre]" /><br />
    Email:   <input type="text" name="personal[email]" /><br />
    Cerveza: <br />
    <select multiple name="cerveza[]">
        <option value="warthog">Warthog</option>
        <option value="guinness">Guinness</option>
        <option value="stuttgarter">Stuttgarter Schwabenbräu</option>
    </select><br />
    <input type="submit" value="submit me!" />
</form>

You could use the very same name for each of the user added fields, as in:

<input type="text" id="field1" name="fields[]" />
<input type="text" id="field2" name="fields[]" />

And then just use implode as required:

$imploded_fields = implode(', ', $_POST['fields']);
Sign up to request clarification or add additional context in comments.

Comments

0

There are many options:

  1. You can use cookies. Use PHP $_COOKIE to get it. For help.
  2. You can use html hidden input fields - <input type="hidden" value=""> and can store actual number of fields in it.

But, Diego Agulló is better one

Comments

0

You can create a hidden field and initialize it with 1 if on option is already open(field1). And increase the the value of counter while increasing the value of fields and vise verse. On submit you will find the total fields added.

Thanks

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.