Jump to content

Dynamically add form fields (from a select box)


tHud
Go to solution Solved by Psycho,

Recommended Posts

Hello :)

I'm using a small script (that I found online) to dynamically add fields to an order form.

It works well with normal text fields but I would like to use it with a select box fields (as it draws data from MySQL).

 

My problem is, that when the field is 'cloned' it contains the product id and not the product name - which is what the user needs to see.


<?php
echo '<form method="post" name="orderform">';

// lots of form fields...

echo '<div id="itemRows">';
echo 'Item quantity: <input type="text" name="add_qty" size="4" />';


$prod = "SELECT prod_id, product FROM products ORDER BY product ASC";
$prodRes = $mysqli->query($prod);

echo 'Item name : <select name="add_name">';

	while ($p = $prodRes->fetch_assoc()) {
		echo'<option value="'.$p['prod_id'].'">'.$p['product'].'</option>';
	}

echo '</select>';

echo '<input onclick="addRow(this.form);" type="button" value="Add row" /> (Won't be saved until you click on "Add row")';



if(isset($product['qty']) && isset($product['name'])) {
?>

<p id="oldRow<?=$product['id']?>">
Item quantity: <input type="text" name="qty<?=$product['id']?>" size="4" value="<?=$product['qty']?>" />
Item name: <input type="text" name="name<?=$product['id']?>" value="<?=$product['add_name']?>" />
<input type="checkbox" name="delete_ids[]" value="<?=$product['id']?>"> Mark to delete
</p>
</div>
<?php 
}
?>
	
</div>

<input type="submit" value="Submit new order" name="addOrder">
</fieldset>
</div>
</form>




<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
	rowNum ++;
	var row = '<p id="rowNum'+rowNum+'">Item quantity: <input type="text" name="qty[]" size="4" value="'+frm.add_qty.value+'"> Item name: <input type="text" name="name[]" value="'+frm.add_name.value+'"> <input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
	jQuery('#itemRows').append(row);
	frm.add_qty.value = '';
	frm.add_name.value = '';
}

function removeRow(rnum) {
	jQuery('#rowNum'+rnum).remove();
}
</script>







I know I could use the $p['product'] value in the select box field, but when it is submiitted - it loses its  $p['prod_id'] value which I need to input back into the MySQL database.

 

 

I did try

       echo'<option value="'.$p['prod_id'].':'.$p['product'].'">'.$p['product'].'</option>';

and then explode...

    foreach($_POST['name'] as $key => $value) {

        $items[] = current(explode(":", $value));

    }

...but clearly, that is a dreradful solution and looks awful to the user.

 

Any thoughts, please?

 

Thank you. :)

Edited by tHud
Link to comment
Share on other sites

  • Solution

I don't see anything in your code that is trying to clone the select list.

 

You should NOT hard-code the fields to be copied/cloned into the JavaScript code. Instead you should put the 'group' of fields to be copied into a DIV or other container and then dynamically copy the fields in that container. That way, when you make changes to the fields in the future, you only have to change the fields in the initial form (i.e. PHP) and you don't have to change the JavaScript.

 

Here is a very "rough" example: http://jsfiddle.net/sEtmN/3/

Edited by Psycho
Link to comment
Share on other sites

Hi Psycho,

Thanks so much for this answer.

(Sorry abbout the use of the word 'clone' - whilst researching the answer I read about clone and used the word instead of append.)

 

Your code seems to do exactly what I need (thanks again!).

 

Just one thing though... How can I stop the form from submitting when using the button...

<button onclick="addRow()">Add Row</button>

(As opposed to when I use the main form submit button when all the other fields have been filled in.)

 

Thank you again :)

 

Link to comment
Share on other sites

Hi,

I really don't know why it is submitting.

I've been staring at the code since you last posted but I guess my knowledge does not go deep enough.

 

This is the whole script (very much in prototype).

<?php

	if ( isset($_POST['client_id']) && ($_POST['client_id'] == "addClient"))	{
		header("Location: clients.php?addClient" );
		exit;
	}   

include("includes/connect.php");
include("includes/header.txt");


if (isset($_POST['addOrder'])) {

	foreach($_POST['select'] as $key => $value) {
		$items[] = current(explode(":", $value));
}


$stmt = $mysqli->prepare("INSERT INTO orders (client_id, o_date, o_number, o_notes ) VALUES (?, ?, ?, ?)");
$stmt->bind_param('isss', $_POST['client_id'], userToMysql($_POST['o_date']), $_POST['o_number'], $_POST['o_notes']);
$stmt->execute();
$newOrderId =$mysqli->insert_id; 
$stmt->close();


if(!empty($_POST['qty'])) {

	foreach($_POST['qty'] as $cnt => $qty) {
		$stmt = $mysqli->prepare("INSERT INTO order_details (o_id, prod_id, qty) VALUES (?, ?, ?);");
		$stmt->bind_param('iii', $newOrderId, $items[$cnt], $qty);
		$stmt->execute();
		$stmt->close();
	}

}

include("includes/footer.txt");
}


$query = "SELECT client_id, client FROM clients ORDER BY client ASC";
$result = $mysqli->query($query);

echo '<form method="post">';

echo '<label>Client</label>';
echo '<select name="client_id">';
echo '<option value="addClient">Add New Client</option>';

while ($row = $result->fetch_assoc()) {
		echo'<option value="'.$row['client_id'].'">'.$row['client'].'</option>';
}
echo '</select><br>';


?>

<label>Date</label><input type="text" name="o_date" size="10">
<script language="JavaScript">
new tcal ({
	'formname': 'orderform',
	'controlname': 'o_date'
});
</script>

<label>Order No.</label><input type="text" name="o_number" size="25"><br><br>
<label>Notes</label><textarea name="o_notes" cols="65" rows="3"></textarea><br><br>


<div id='container'>
<div id='rowNum1'>
	qty: <input type="qty" name="qty{}"><br>

	<?php
	$prod = "SELECT prod_id, product FROM products ORDER BY product ASC";
	$prodRes = $mysqli->query($prod);

	echo '	Select: <select name="select{}">';
		
		while ($p = $prodRes->fetch_assoc()) {
			echo'<option value="'.$p['prod_id'].':'.$p['product'].'">'.$p['product'].'</option>';
		}
	echo '</select>';
	?>
</div>
</div>

<button onclick="addRow()">Add Row</button>

<input type="submit" value="Submit new order" name="addOrder">

</form>





<script type="text/javascript">
function addRow()
{
	var container = document.getElementById('container');
	var rowNum = container.children.length + 1;
	var rowSetHTML = container.children[0].innerHTML;
	var rowHTML = '<p id="rowNum'+rowNum+'">'+rowSetHTML+'</p>';
    $( "#container" ).append(rowHTML);
}
</script>


<?php

include("includes/footer.txt");





?>


Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.