如何将多个动态生成的文本框值显示到数组中

时间:2017-08-24 08:47:18

标签: php jquery html css

我有多个动态生成的文本框。这里当我单击文本框行中的添加按钮时,它将动态生成文本框行并从文本框中获取值。在这里我如何使用PHP从这些行或文本框数组中获取值。

$(document).ready(function(){
	var maxField = 10; //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_name2[]" value=""/><input type="text" name="field_name2[]" value=""/><input type="text" name="field_name3[]" value=""/><input type="text" name="field_name4[]" value=""/><a href="javascript:void(0);" class="remove_button" title="Remove field"><img src="https://cdn0.iconfinder.com/data/icons/round-ui-icons/512/close_red.png" width="30" height="30"/></a></div>'; //New input field html 
	var x = 1; //Initial field counter is 1
	$(addButton).click(function(){ //Once add button is clicked
		if(x < maxField){ //Check maximum number of input fields
			x++; //Increment field counter
			$(wrapper).append(fieldHTML); // Add field html
		}
	});
	$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
		e.preventDefault();
		$(this).parent('div').remove(); //Remove field html
		x--; //Decrement field counter
	});
});
input[type="text"]{height:20px; vertical-align:top;}
.field_wrapper div{ margin-bottom:10px;}
.add_button{ margin-top:10px; margin-left:10px;vertical-align: text-bottom;}
.remove_button{ margin-top:10px; margin-left:10px;vertical-align: text-bottom;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form" action="" method="post">
<div class="field_wrapper">
	<div>
    	  <input type="text" name="field_name1[]" value=""/>
        <input type="text" name="field_name2[]" value=""/>
        <input type="text" name="field_name3[]" value=""/>
        <input type="text" name="field_name4[]" value=""/>
        <a href="javascript:void(0);" class="add_button" title="Add field"><img src="https://cdn0.iconfinder.com/data/icons/small-n-flat/24/678092-sign-add-128.png" width="30" height="30"/></a>
    </div>
</div>
<input type="submit" name="submit" value="SUBMIT"/>
</form>

这里我使用php获取值,但它只显示单个文本框值。

<?php
if(isset($_REQUEST['submit'])){
    $field_values_array = $_REQUEST['field_name'];

    print '<pre>';
    print_r($field_values_array);
    print '</pre>';

    foreach($field_values_array as $value){
        //your database query goes here
    }
}
?>

1 个答案:

答案 0 :(得分:0)

试试这个。您必须遍历已发布的字段

if(isset($_REQUEST['submit']))
{

    for($i=1; $i<=4; $i++) //changes number of count as per fields in form
    {

        $field_values_array = $_REQUEST['field_name'.$i];

        print '<pre>';
        print_r($field_values_array);
        print '</pre>';

        foreach($field_values_array as $value){
            //your database query goes here
        }

    }            
}