Keeping the values of form on page

帅比萌擦擦* 提交于 2020-01-25 00:12:22

问题


I want to keep the values chosen by the user on the form once they submit the form.

This is what I tried:

<cfset tx_name = "">
<cfset id_age1 = "">

<cfif isDefined("form.tx_name")>
    <cfset tx_name = form.tx_name>

    <cfif isDefined("a1")>
        <cfset id_age1 = form.a1>
    </cfif>
</cfif>

<cfoutput>

<input type="text" name="tx_name" value="#tx_name#">

<select name="id_age1">
    <cfloop from="1" to="20" index="a1">
        <option value="#a1#">#a1#</option>
    </cfloop>
</select>

</cfoutput>

I am getting the expected result for tx_name, however, the id_age1 is not displaying the correct result. It just resets back to 1. What am I doing wrong?


回答1:


Most of that code unnecessary. To define default values for variables that do not exist (different than being empty), simply use cfparam. Be sure to specify the variable scope to avoid unexpected results due to scope conflicts:

    <cfparam name="form.tx_name" default="">
    <cfparam name="form.id_age1" default="">

To pre-select an item within the <select> list, you must apply the selected attribute to the appropriate <option>:

<select name="id_age1">
   <cfloop ...> 
      <option value="#a1#" <cfif a1 eq form.id_age1>selected</cfif>>
         #a1#
      </option>
   </cfloop>
</select>

Also, not sure if it was omitted deliberately, but .. the two form fields should be nested inside a <form> tags.




回答2:


I know this is more of a comment, but it is easier to read as an answer.

The code on the input is not safe. It is subject to HTML Injection. See: html-injections

<cfparam name="form.tx_name" default="">
...
<input type="text" name="tx_name" value="#EncodeForHTMLAttribute(tx_name)#" />

ColdFusion has a series of functions to address this. See: http://blogs.adobe.com/security/2014/05/coldfusion-11-enhances-the-security-foundation-of-coldfusion-10.html



来源:https://stackoverflow.com/questions/42406754/keeping-the-values-of-form-on-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!