How to insert value of dynamically created input b

2019-09-08 15:34发布

问题:

This question is an exact duplicate of:

  • how to post value of 3 input fields into database

hello developers i am creating 2 text boxes and 1 select box dynamically using java script function... now i want to post the value of (n) fields created into database (relevant table) as i am using codeigniter so m posting the script and code

this is the simple java script that i am using

<script>
  var counter=1;
  function generateRow() {
    var count="<font color='red'>"+counter+"</font>";
    var temp ="<p>&nbsp;&nbsp;&nbsp;&nbsp;<div class='_25'><input type='textbox' id='textbox' name='stop"+counter+"' placeholder='Stop Name'></input></div>&nbsp;&nbsp;&nbsp;<div class='_25'><input type='textbox' id='textbox' name='timing"+counter+"' placeholder='Timing'></input></div>&nbsp;<div class='_25'><select id='ampm"+counter+"' name='ampm"+counter+"'><option>a.m</option><option>p.m</option></select>  </div>";

    var newdiv = document.createElement('div');
    newdiv.innerHTML = temp + count;

    var yourDiv = document.getElementById('div');
    yourDiv.appendChild(newdiv);
    counter++;
  }
</script>

and this is my division on php file

 <div id="div">
 </div>

 <p>&nbsp;</p>
 <div class="_25">
    <p>
      <input type="button" name="button" class="button red" id="button" value="Add"  onclick="generateRow() "/></a>
    </p>
 </div>
 <input type='button' value='Remove Button' id='removeButton'>

and this is my related table fields

route_number    stop_name   am_pm   timing

回答1:

My favorite way to do this is to use the DOM as much as possible. Don't use counters unless you absolutely have to (they're just a source of bugs). Here's a quick example:

Html/JS/jQuery (can vary, I crafted this to make it easy to follow):

<form method="POST" id="theForm">
    <div id="fields">
        <input type="text" name="fields[]"/>
    </div>
    <input type="button" id="addField" value="Add Field"/>
</form>
<script type="text/javascript">
    $(document).ready(function() {
        $('#addField').click(function() {
            $('#fields').append(
                $('<input type="text" name="fields[]"/>')
            );
        })
    });
</script>

Note how I don't need to use any sort of counting variable. Just like PHP, you can create an array of POST variables without specifying indexes by using [] and the server (or browser? I'm not sure) will build the array for you. The order in which the <input /> fields are rendered on the page will be the order they are provided to your PHP via $_POST. This code...

foreach ($_POST['fields'] as $fieldIndex => $fieldValue) {
    doStuff($fieldValue);
}

... will process each field in the order they were added. You can even use JavaScript to re-order or remove the inputs and that will be reflected in $_POST. This method, coupled with JSON encoding, makes for a fast and easy way to handle multi-input, free-form fields.

Update:

Applying the above code to your use-case requires a small addition that may not be obvious. You'll need to create an array for each of the three inputs (stop, timing, and ampm) like so:

<form method="POST" id="theForm">
    <div id="fields">
        <input type="text" name="fields[stop][]"/>
        <input type="text" name="fields[timing][]"/>
        <select name="fields[ampm][]">
            <option value="am">AM</option>
            <option value="pm">PM</option>
        </select>
        <br/>
    </div>
    <input type="button" id="addField" value="Add Field"/>
</form>
<script type="text/javascript">
    $(document).ready(function() {
        $('#addField').click(function() {
            $('#fields').append(
                $('<input type="text" name="fields[stop][]"/>'),
                $('<input type="text" name="fields[timing][]"/>'),
                $('<select name="fields[ampm][]"><option value="am">AM</option><option value="pm">PM</option></select>'),
                $('<br/>')
            );
        })
    });
</script>

Filling out this form with some test data yields the following array:

[fields] => Array
(
    [stop] => Array
        (
            [0] => aaa
            [1] => bbb
        )

    [timing] => Array
        (
            [0] => 1111
            [1] => 2222
        )

    [ampm] => Array
        (
            [0] => am
            [1] => pm
        )

)

And to process that in PHP requires a simple old-school loop:

$numFields = count($_POST['fields']['stop']);

for ($i = 0; $i < $numFields; $i++) {

    // Pack the field up in an array for ease-of-use.
    $field = array(
        'stop' => $_POST['fields']['stop'][$i],
        'timing' => $_POST['fields']['timing'][$i],
        'ampm' => $_POST['fields']['ampm'][$i]
    );

    saveToDatabase($field);
}

Unfortunately I don't have time right now to make sure all that is correct. It should be, and if its not it may still help :). I'll check back in a few hours.



回答2:

name your dynamic input box "stop["+counter+"]" (using braces as part of the name) instead of adding a counter to the end of the name. Then in your post data, $_POST['stop'] will be an array of values that you can just foreach loop over with the counter as the key in the sub-array. And $_POST['stop'][1] will correspond to $_POST['timing'][1]...etc.



回答3:

You can construct the following HTML input fields:

<input type="text" name="data[]" />
<input type="text" name="data[]" />
<input type="text" name="data[]" />
// ...

Which will lead to an array keyed data inside $_REQUEST super global, when you var_dump($_REQUEST['data']). Try it out. You don't even need to index the data[] array, since PHP will do it for you.

You might want to process your $_REQUEST['data'] or $_POST['data'] array with a foreach loop construct:

foreach($_REQUEST['data'] as $data){
  // $data is the corresponding input field's value
}