Back

RDCUBE

Home

Add New Row with Jquery and Coldfusion

I want to keep this very brief and only provide the code I use every time I need to add new rows to tables.

After you include your Jquery js file, this is the function I call with the data I need to have available every time someone clicks the 'add row' button/link:


<script>
var current = 1
function addRow() {
current++; 
var strToAdd = '
<input id="txtCount" name="txtCount" type="hidden" value="'+current+'" /> Enter Your Name:<input id="FullName'+current+'" name="FullName'+current+'" size="6" type="text" />Which State you're From: <select id="State'+current+'" name="State'+current+'">
<cfoutput query="qStates"><option value="#state_name#">#state_name#</option></cfoutput></select>'
$("#datable").append(strToAdd)
}
</script>

What I've done is populate a simple html tr/td table with an input and select menu and every time a user calls the 'addRow()' function, it will increment 'current' variable which I'm storing on 'txtCount'.

As you can see, since I didn't wanted to bother with entering all "US States" manually, I'm looping the tag with a cfoutput query inside JS (this might not be the best way to do it, but hey, it works ;)

My form will already have a table with the same tr/td fields to start off and it will be the last row in my table.
so the only thing left to do, is just add the button/link to call the function:

<a class="AddNewLink" href="javascript:void(0);" onclick="addRow();">Add New Row</a>

Now that this is working, how about processing what is submitted; since I don't know how many rows were added, I'm just going to loop from 1 to the last 'txtCount' field added.

<cfloop from="1" index="i" to="#listlast(form.txtCount)#">
<!--- Since my original SQL insert only calls for 'FullName' and 'State', I'm setting the variable to match --->
<cfset form.FullName = #form["FullName"&i]# />
<cfset form.State = #form["State"&i]# />
<!--- this passes the values to a cfc that process the form --->
<cfset addrecord="fnAddNewFriend(form)">
</cfloop>

And that's it!

Full Version