2012-11-17 67 views
3

我在這裏我的Javascript代碼添加了動態文本框(行)我的問題是如何將動態文本框的值保存到使用PHP腳本的數據庫中?希望你能幫助我的傢伙..謝謝!如何使用PHP添加動態文本框(行)並保存到數據庫

<script type="text/JavaScript"> 
    function addRow(r){ 
    var root = r.parentNode;//the root 
    var allRows = root.getElementsByTagName('tr');//the rows' collection 
    var cRow = allRows[0].cloneNode(true)//the clone of the 1st row 
    var cInp = cRow.getElementsByTagName('input');//the inputs' collection of the 1st row 
    for(var i=0;i<cInp.length;i++){//changes the inputs' names (indexes the names) 
    cInp[i].setAttribute('name',cInp[i].getAttribute('name')+'_'+(allRows.length+1)) 
    } 
    root.appendChild(cRow); 
    } 
    function shownames(){ 
    var allInp=document.getElementsByTagName('input'); 
    for(var i=0;i<allInp.length;i++){ 
    alert(allInp[i].name) 
    } 
    } 
    </script> 

我的HTML代碼:

<form method="POST" action="#"> <table width="1024" border="0" cellspacing="6" cellpadding="0"> <tr> 
     <td width="195"><div class="user"><input type="text" name="user_a" id="user" tabindex="6"/></div></td> 
    <td width="410"><div class="reported"><input type="text" name="user_b" id="reported" tabindex="7"/></div></td> 
    <td width="399"><div class="reported"><input type="text" name="user_c" id="reported" tabindex="8"/></div></td> 
    <td width="10"><input name="button" type="button" value="+" onclick="addRow(this.parentNode.parentNode)"></td> </tr> </table> </form> 

回答

0
<html> 
<head> 
<title>Dynamic Form</title> 
<script language="javascript"> 
<?php $i = 1; ?> 
function changeIt() 
{ 
    //alert(i); 
    //var i = 1; 

my_div.innerHTML = my_div.innerHTML +"<br><input type='text' name='mytext[<?php echo $i;?>]'><input type='text' name='mytext[<?php echo $i+1;?>]'><input type='text' name='mytext[<?php echo $i+2;?>]'><br>"; 
<?php $i = $i+3; ?> 
} 
</script> 
</head> 
<body> 

<form name="form" action="http://localhost/try.php" method="post"> 
<!--<input type="text" name=t1>--> 
<input type="button" value="test" onClick="changeIt()"> 
<div id="my_div"></div> 
<p class="submit"><button type="submit">Register</button></p>  
</body> 

try.php(這是在那裏你會被抓住的值,然後插入SQL 文件)

<?php 
    $var = $_POST['mytext']; 
    echo $var[1].$var[2]; 
    ?> 
+0

感謝您的答覆。在你的代碼中,我只能添加一個文本框。但我需要在一行中添加三個文本框。我將如何做到這一點?請幫助我。謝謝! – user1831375

+0

不應該是'我'是一個全局變量(用在'function changeIt()') –

+0

是的我的不好,它需要是全局的。 @ user1831375,我編輯了代碼,嘗試使用已編輯的代碼,它將一次添加3個文本框! –

1

你必須只使用這是由動態添加文本框的名稱。

$('form').submit(function() { 
var data=($(this).serialize()); 
return false; 
}); 

此功能讓所有的元素值,並創建一個字符串,它是在數據存儲,數據現在將通過在Ajax調用。

$('form').submit(function() { 
var data=($(this).serialize()); 
     $.ajax({ 
     type: "POST", 
     url: "your_some.php", 
     data: data, 
     }).done(function(msg) { 
     alert("Data Saved: " + msg); 
    }); 
}); 
相關問題