Reputation: 69
I have a form with a multiple select option in it. I wanted to make it so that when the user hits submit, it will populate my DB with all the relevant fields, then go through some sort of loop for the multiple select portion.
https://jsfiddle.net/vtyofmza/1/
Example would be someone highlights 3 fields in the multiple select and puts in their name. When they hit submit, the database would populate
John Doe - Breakfast
John Doe - Snacks
John Doe - Dessert
I was thinking something like this might work, but it just resets the form all over again
iSelect = $('#meal').val();
iLength = $('#meal option:selected').length;
for (i = 0; i < iLength; i++){
$('#meal').val(iSelect[i])
document.form.submit();
}
But when it submits the information, it goes back and resets the page all over again.
The submit.cfm looks like this
<cfquery name="Add" datasource="food">
INSERT INTO Log (Meal, Name)
VALUES (#Form.Neal#, #Form.Name#)
</cfquery>
<cflocation url="... loops back to original page">
Upvotes: 1
Views: 206
Reputation: 28873
As @Kevin B said above, this is not a job for javascript. Any extra handling or looping should be done in ColdFusion.
Basic Loop:
Multiple selections will be submitted as a csv list ie form.Meal = "Breakfast,Snacks,Dessert"
. Simply loop through that list and execute an insert for each meal + name. There are ways to improve this kind of looping, but below is the basic idea (no validation):
<!--- ensure field always exists --->
<cfparam name="form.Meal" default="">
<!--- loop through the meal list and insert each one individually --->
<cfloop list="#form.Meal#" index="currMealName">
<cfquery name="Add" datasource="food">
INSERT INTO Log (Meal, Name)
VALUES (
<cfqueryparam value="#currMealName#" cfsqltype="cf_sql_varchar">
, <cfqueryparam value="#Form.Name#" cfsqltype="cf_sql_varchar">
)
</cfquery>
</cfloop>
NB: A few important notes
Better Option
If the source of the select list values is another database table, another approach is to use a SELECT
statement to insert the values. This has the advantage of built in validation and it also inserts all of the values in a single query. Personally, I prefer that approach rather than looping. For demo purposes, the example uses type=cf_sql_varchar. Obviously update the types as needed to match your actual columns.
INSERT INTO Log (Meal, Name)
SELECT Meal
, <cfqueryparam value="#form.name#" cfsqltype="cf_sql_varchar">
FROM YourMealTable
WHERE Meal IN
(
<cfqueryparam value="#form.meal#" list="true" cfsqltype="cf_sql_varchar">
)
Upvotes: 11