I google'd myself silly, I can't find tutorials for this. I hope someone could lend me a hand.

I'll try to make this simple. I have a PHP & MySQL driven site. I have a form for adding new content.

The form has a set of check box options that are pulled from MySQL.

At the bottom of the check boxes there is an "Add New" input field which I want to be used to add new check box options right above it.

database

table options
id int 255 auto increment primary key
name varchar 255

index.php

<form action="saveinfo.php" method="post">
<?php

$gf = mysql_query("SELECT * FROM options");
while($agf = mysql_fetch_array($gf)){

$id = $agf['id'];
$option_name = $agf['name'];
echo "<input type=\"checkbox\" name=\"option[$id]\" value=\"true\" />$option_name<br />";

}
?>
<div id="newoptions">[...New options here...]</div>

<input type="text" name="addnew" value="" placeholder="Add New" />

[...the rest of the form...]

<input type="submit" name="submit" value="Save Information"/>

</form>

So as I understand how this should work, when I click in the 'add new' text field, type something in, then press enter - the value of the add new field should be sent to a php script, addnew_backend.php. The form itself should not submit it's data. The PHP script will add the new value to the mysql table of options, and if successful, returns the newley generated checkbox which should fade in right above the add new text field into div#newoptions.


addnew_backend.php

<?php

//connect to mysql
include("config.php");

$name = mysql_real_escape_string(trim($_POST['addnew']));

$ins = mysql_query("INSERT INTO options (id,name) VALUES (id,'$name')");

//success
if($ins){
$insertid = mysql_insert_id();
echo "<input type=\"checkbox\" name=\"option[$insertid]\" value=\"true\" checked=\"checked\" />";
}else{
//fail
echo mysql_error();
}

?>

So I think I understand what needs to happen, could someone help me with the actual code?

Thank you!

Recommended Answers

All 13 Replies

Not a single reply ....darn. Any ideas at all?

I can help, give me a few minutes though.

of course, this is just for an idea of how you can do this. the code mostly works as expected. I did not make a remove_option.php script. you should better understand how this works now. a few things of note, you can do this in a POST but just to get the idea across I changed the calling method to a GET. I like POST much better but was just trying to get you something before I went home for the night.
that said, test drive this code around for a while and see what you think. let me know if you have more questions. read the comments.

<script type="text/javascript">
	var http = false;
	var optionCount = 0;
	if(navigator.appName == "Microsoft Internet Explorer") {
		http = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		http = new XMLHttpRequest();
	} 	
	// always run the code above this line.  http and optionCount need to be set.
	
	// your 'original' function, changed from POST to GET, consult code below, pretty straight forward.
	// I use optionCount to keep track of how many options have been added it is also used on the removal code (which is all a bonus).
	function add_option() {
		//alert('add_option called with ');
		// lets find the value of addnew text field
		var addnew = document.myform.addnew.value;
        // make sure it is not blank as you are posting directly to your db.
		if (addnew != '') {
//		function replace() {
			// I made it a GET call just so I could get you code, this is how you do it, now you have an idea... you can use either GET or POST
			http.open("GET", "addnew_backend.php?addnew="+addnew, true);
			http.onreadystatechange=function() {
				if(http.readyState == 4) {
					//document.getElementById('foo').innerHTML = http.responseText;					
					//document.getElementById("newoptions").innerHTML=http.responseText;
					// well, we've added an option, so increment the count and set hidden variable on our form.
					optionCount++;
					document.myform.optionCount.value = optionCount;
					//alert('call addOption');
					// could have done it all here, but I didn't.  calling new function with the response text.
					addOption(http.responseText); 					
				}
			}
			http.send(null);
		}					
	}

	// Actually builds 2 divs and attaches them underneath 'newoptions'
	function addOption(text) {
	    var id = document.myform.optionCount.value;
		var div = jQuery(document.createElement('div')).attr('id',id);
		div.html(text + '&nbsp;&nbsp;&nbsp;');
		var rem = jQuery(document.createElement('a')).attr('id','option_div_'+id).attr('alt',id).attr('class',id).attr('name',id).attr('href','javascript:;').text("Remove").click(removeUpload);      
		rem.appendTo(div);  					
		div.appendTo("#newoptions");				

		// this call is not working, it should make the value of your addnew textbox blank (so they can fill it in again)
		// left it here because I find it useful, 
		jQuery("#addnew").removeAttr('value');  	
		// you may want to see why it isn't working or just do this:
		//document.myform.addnew.value = '';
		// which should leave the addnew value to be blank so they can add a new option.
		// always nice to trace our progress, so I just commented my alerts out.
		//alert('end addOption');
	}
	
	function removeUpload(e){   
		//alert('removeUpload called!');
		// this is actually looking at the alt attribute set on the rem div above.  you can pick out any values by changing 'alt' to lets say 'id' 
		var removeId = jQuery(e.target).attr('alt');
		//alert('calling remove on #'+removeId);
		jQuery('#'+removeId).remove();
		if(optionCount>0) {
			optionCount--;   
		}
		document.myform.optionCount.value = optionCount;
		alert('item removed');
		// if you need to delete the option from the database, you can do that here.
		//jQuery.post("remove_option.php", { js: removeName});
	}	
	</script>
	<!--  I gave your form a name, to reference document.myform.someitem.value -->
	    <form name="myform" action="saveinfo.php" method="post">
    <?php
     
    $gf = mysql_query("SELECT * FROM options");
    while($agf = mysql_fetch_array($gf)){
     
    $id = $agf['id'];
    $option_name = $agf['name'];
    echo "<input type=\"checkbox\" name=\"option[$id]\" value=\"true\" />$option_name<br />";
     
    }
    ?>
    <div id="newoptions">[...New options here...]</div>
	
	<input type="hidden" name="optionCount" value="">
     <!-- I added a 'Add' button, it's easier that way -->
    <input type="text" name="addnew" value="Add New" /><input type="button" value="Add" onclick="add_option();"><br/><br />
     
    [...the rest of the form...]
     
    <input type="submit" name="submit" value="Save Information"/>
     
    </form>

And last thing of note, since I change the calling from POST to GET you need to update your addnew_backend.php page.

$name = mysql_real_escape_string(trim($_GET['addnew']));
// and you might want to mysql_real_escape_string() that variable, keep that database safe.

Wow, you are amazing. Thank you so much. Give me some time to dig in.

hey, how did that work for you. do you see the logic? do you need more help? if you are happy please close ticket or reply with questions. the POST logic is there at the end of the remove script, we could change everything and call post if you wish... and beware of $id's on remove script, those are the id's of the div and not the ids of the 'options' you are setting. that's a whole lot more code. anyway, just asking if everything is ok now.

Hey man,

Thanks again for all your work. I've spent a lot of time reading, understanding and toying with the code to get my mind wrapped around it all.

The code works perfectly, though I have developed a few questions - it's all a bit complicated so ill try my best.

I actually have a single form that has multiple options for "add new". I had difficulty duplicating some of the code to make it work, so I was thinking, could I pass a parameter to the add_option() function? If I understand this properly, you can pass it when you declare a function, just like in PHP. But after that, how might I use it with the functionality that also updates the html form with the newly added option?

I'll clarify: I believe I'd need to pass a parameter to the Jquery / JS 'add option' function, this parameter would do 2 things - it would allow me to specify the section of the form I am adding a new option to, and second, it would allow my back end PHP script to determine what section I am adding options to.

//pass a parameter like this, right?
function add_option(parameter1) {

Here is part of my form, shortened for simplicity, to illustrate my thoughts:

<?php
function add_new_plant_form(){
global $settings,$form;
/*
p_id p_articlename p_permalink p_botanicalname p_author p_publishdate p_active

p_cg p_gfsi p_gfso p_tepo p_osst p_ogst p_ost p_omc p_onc p_oac p_op p_od p_ow
p_ose p_odt p_odh p_ont p_onh p_pr p_oi
*/
?>

<form action="<?php echo $settings['site']['url']; ?>actions/process-add-new-plant-form" method="post">

<div id="form">

<section class="sub-sub-section">
<div id="form">
<ul>

<li>
<label>Grow From Seed: Start Indoors</label>
<span class="note"></span>
<?php get_plant_options("gfsi",""); ?>
</li>

<li>
<label>Grow From Seed: Start Outdoors</label>
<span class="note"></span>
<?php get_plant_options("gfso",""); ?>
</li>
</ul>
</div>
<br class="clear" />
</section>

<ul>
<li>
<label>Submit</label>
<span class="note"></span>
<input type="submit" name="submit" value="Save" />
</li>
</ul>


</form>
</div>
<?php
}

?>

Notice the lines:

<?php get_plant_options("gfsi",""); ?>
<?php get_plant_options("gfso",""); ?>

This function pulls out the <select> tags, the <option>'s that exist in the database, and the 'add new' input tag. The first parameter specifies the identifier, this is a unique string that is used to identify what options to pull out. The second parameter is an array used to check off options (For edit for or similar). See the function below:

<?php

function get_plant_options($section,$checked = array()){
$sql = "SELECT * FROM plant_options WHERE po_section='$section' ORDER BY po_order ASC, po_name ASC";
$go = mysql_query($sql);
$cgo = mysql_num_rows($go);
if($cgo > 0){
while($ago = mysql_fetch_array($go)){
extract($ago);
/*po_id 	po_name 	po_section 	po_order 	po_note*/
echo "<input type=\"checkbox\" name=\"form[checkboxes][$section]"."[$po_id]\" value=\"true\" ";
if(in_array($po_id, $checked)){echo "checked=\"checked\" ";}
echo"/>$po_name<br />";
}
}
echo "<div id=\"newoptions-$section\"></div>";
echo "<input type=\"text\" class=\"addnew\" name=\"form[addnew][$section]\" value=\"\" placeholder=\"Add New\" />";
}

?>

So <?php get_plant_options("cg",""); ?> produces something like:

<input type="checkbox" value="true" name="form[checkboxes][cg][4]">Fruits<br />
<input type="checkbox" value="true" name="form[checkboxes][cg][3]">Nuts<br />
<input type="checkbox" value="true" name="form[checkboxes][cg][2]">Roots &amp; Tubers<br />
<input type="checkbox" value="true" name="form[checkboxes][cg][5]">Vegetables<br />
<input type="checkbox" value="true" name="form[checkboxes][cg][1]">Greens<br />
<div id="newoptions-cg"></div>
<input type="text" placeholder="Add New" value="" name="form[addnew][cg]" class="addnew"></li>
</ul>
</div>
<br class="clear">
</section>

I apologize this is so much code, and such a confusing issue (at least to me).

So I think it's just a matter of tweaking the JS so I can pass it a parameter. I totally dig dynamic code that doesn't need to be edited in the event that I add an option to the database - just pass a parameter to determine how it needs to be handled, etc.

Thanks again for your help.

certainly, you can pass a value to your javascript function just like php.
I'm just going to post a short answer for you to try something add the event to the button you are creating

// line 17 get_plant_options function:
echo "<input type=\"text\" class=\"addnew\" name=\"form[addnew][$section]\" value=\"\" placeholder=\"Add New\" />";
echo "<input type=\"text\" class=\"addnew\" name=\"form[addnew][$section]\" value=\"\" placeholder=\"Add New\" onmouseout=\"javascript:add_option();\"/>";
// I would still add an 'add button' instead of relying on onmouseout so alter your get_plant... function to return this 
echo "<input type=\"text\" class=\"addnew\" name=\"form[addnew][$section]\" value=\"\" placeholder=\"Add New\" />";
echo "<input type=\"button\" value=\"Add\" onclick=\"add_option('$section');\"/>";
// untested code, I enclosed $section with ' ' because I assume you are wanting to pass a string back into your js function 
// just so you know that when that button is pressed that it is expected to fire your add_option code (as opposed to onmouseout). on your function add_option(), add a parameter 
// this is javascript
function add_option(sec) {
    alert('updating section ' + sec);
    // rest of your update code, now with sec (name of section) available to you.
}

it works just like php as far as passing parameters and using them inside your functions.

Right on man, thank you, I'll see what I can do with this.

Alright, I think I have everything ready except one thing.

function add_option(section) {

var addnew = document.myform.'addnew-'+section.value;

Let's say that the input field to add new options for a section is addnew-section_name.

<input type="text" name="addnew-1" value="" />

How do I make that line of JS refer to it dynamically. ie

var addnew = document.myform.'addnew-'+section.value;

or

var addnew = document.myform.addnew-+'section'.value;

Two questions:
1) How would I go about that?

And 2) If I were to search Google for the answer to this, how would I phrase it? My biggest problem with JS is that when I come to a problem, I don't know how to ask it.

Thank you.

The first way. assuming that 1 is what is coming over in your 'section' variable.

var addnew = document.myform.'addnew-'+section.value;

google:
google javascript syntax to do x.
javascript example of finding the value of a input field
javascript syntax find hidden input value
keywords would be syntax and examples you do have to know what you are looking for though.

Alright,

I have one more question ddymacek.

I have multiple "add new" options in the same form. I need a way to reference the "addnew" input field that I can pass to the add_option function. Everything I've tried has failed. See code below and let me know if you know what to do? Thanks.

<?php
include("config.php"); // database
?>
<script type="text/javascript">
var http = false;
var optionCount = 0;
if(navigator.appName == "Microsoft Internet Explorer"){
  http = new ActiveXObject("Microsoft.XMLHTTP");
}else{
  http = new XMLHttpRequest();
}


	
function add_option(section) {
var addnew = document.myform.addnew+"-"+section.value;

if (addnew != '') {
	http.open("GET", "addnew_backend.php?addnew="+addnew+"-"+section+"&section="+section, true);
	http.onreadystatechange=function() {
	if(http.readyState == 4) {
document.getElementById(section).innerHTML = document.getElementById(section).innerHTML + http.responseText;
optionCount++;
document.myform.optionCount.value = optionCount;
					addOption(http.responseText); 					
	}
}

		http.send(null);

	}					
}


function addOption(text) {
var id = document.myform.optionCount.value;
var div = jQuery(document.createElement('div')).attr('id',id);
div.html(text + '&nbsp;&nbsp;&nbsp;');
var rem = jQuery(document.createElement('a')).attr('id','option_div_'+id).attr('alt',id).attr('class',id).attr('name',id).attr('href','javascript<b></b>:;').text("Remove").click(removeUpload);
rem.appendTo(div);
div.appendTo("#"+section);				
jQuery("#addnew").removeAttr('value');  
}


<?php /*Disable enter key submit*/ ?>

function disableEnterKey(e,section)
{
     var key;

     if(window.event)
          key = window.event.keyCode;     //IE
     else
          key = e.which;     //firefox

     if(key == 13){
      add_option(section);
      return false;
     }

}

</script>

<form name="myform" action="saveinfo.php" method="post">

<?php

$gf = mysql_query("SELECT * FROM options WHERE section='cg'");
while($agf = mysql_fetch_array($gf)){
     
$id = $agf['id'];
$option_name = $agf['name'];
echo "<input type=\"checkbox\" name=\"option[$id]\" value=\"true\" />$option_name<br />";
     
}

?>

<div id="cg"></div>
<input type="hidden" name="optionCount" value="">

<input type="text" name="addnew-cg" value="" placeholder="Add New Option" onKeyPress="return disableEnterKey(event,"cg");" /><input type="button" value="Add" onclick="add_option("cg");"><br />



<?php
$gf = mysql_query("SELECT * FROM options WHERE section='other'");
while($agf = mysql_fetch_array($gf)){
$id = $agf['id'];
$option_name = $agf['name'];
echo "<input type=\"checkbox\" name=\"option[$id]\" value=\"true\" />$option_name<br />";
}
?>

<div id="other"></div>
<input type="hidden" name="optionCount" value="">
<input type="text" name="addnew-other" value="" placeholder="Add New Option" onKeyPress="return disableEnterKey(event,"other");" /><input type="button" value="Add" onclick="add_option("other");"><br />

    <input type="submit" name="submit" value="Save Information"/>
     
</form>

So when either the enter key is pressed, or the add new button is pressed, I think I need to pass a variable that I can then use to reference the "addnew-section_name" input field.

Is this the right way to do it? Is there a better way? If I'm on the right path, can you show me what is wrong with my code, if you see any syntax problems?

I just can't seam to figure this one thing out.

Thank you for your help!

~John

I think I've got it! I did it like this:

function add_option(section){
var sec = section.id; // get the section value
var formname = "addnew-"+sec; // name of the input field to grab
var addnew = document.myform[formname].value; // grab the value of the form
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.