Forum Moderators: open

Message Too Old, No Replies

Add form fields dynamically in javascript

         

chulo

8:02 pm on Jan 22, 2008 (gmt 0)

10+ Year Member



Hi, I would like to change this PHP add form field into javascript. I want to add a field without refresh the browser. I am using a select to show/hidden a DIV and when i click to add form field it refresh the browser and have to select the DIV again.

//this part to Javascript:
if (isset($_POST['addoption'])) {

$poll_title = $_POST['poll_title'];
foreach($_POST['poll_option'] as $key => $value) {
$poll_option[$key] = $_POST['poll_option'][$key];
}
$opt_count = ($_POST['opt_count']!= 10? count($poll_option) + 1 : $_POST['opt_count']);
}
$i = 0; $opt = 1;
$poll_title = isset($poll_title)? $poll_title : "";
$opt_count = isset($opt_count)? $opt_count : 2;
// end of code that want to change to Javascript

if (isset($poll_id)) $poll_ended = isset($poll_ended)? $poll_ended : 0;

echo "<form name='pollform' method='post' action='addfield.php'>
<table align='center' cellpadding='0' cellspacing='0' width='280'>
<tr>
<td width='80' class='tbl'>title</td>
<td class='tbl'><input type='text' name='poll_title' value='$poll_title' class='textbox' style='width:200px'></td>
</tr>\n";
while ($i!= $opt_count) {
$poll_opt = isset($poll_option[$i])? $poll_option[$i] : "";
echo "<tr>\n<td width='80' class='tbl'>Option $opt</td>\n";
echo "<td class='tbl'><input type='text' name='poll_option[$i]' value='$poll_opt' class='textbox' style='width:200px'></td>\n</tr>\n";
$i++; $opt++;
}
echo "</table>
<table align='center' cellpadding='0' cellspacing='0' width='280'>
<tr>
<td align='center' class='tbl'><br>\n";

echo "<input type='hidden' name='opt_count' value='$opt_count'>
<input type='submit' name='addoption' value='addoption' class='button'>
<input type='submit' name='save' value='submit' class='button'>\n";

echo "</td>\n</tr>\n</table>\n</form>\n";

vincevincevince

12:22 pm on Jan 23, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Your idea is slightly misaligned. With javascript, you need to create things as an object - create the 'div' object, then use appendChild method to attach it where you need it. Then, add an EventListener to your <select> box - that can call a function which looks up the value of the selected entry and deal with it as required.

chulo

7:18 pm on Jan 23, 2008 (gmt 0)

10+ Year Member



thank for your reply, can you gave me a code example or a link were i can see how is done.

[edited by: jatar_k at 12:29 am (utc) on Jan. 24, 2008]
[edit reason] no urls thanks [/edit]

mehh

8:35 pm on Jan 23, 2008 (gmt 0)

10+ Year Member



I didn't look at your code in detail so sorry if this isn't quite what you need.
function addField(form,json){
var inp=document.createElement("input");
for(var i in json){
inp[i]=json[i];
}
form.appendChild(inp);
}
addField(document.forms[0],{
type :"button",
name :"foo",
value:"bar"
});