如何使用jQuery在ColdFusion脚本中选择POST后的下拉值?

时间:2017-01-26 04:03:07

标签: javascript jquery coldfusion

我写了一个带有onload函数的简单表单,它总是预先填充市场价值。但是当我从下拉列表中选择一个市场价值并在提交表单后,该值应该在下拉列表中保持选中状态。这是相关的代码:

<html>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
  <cfif isdefined("form.submit")>
    form submitted
    <cfdump var="#form#">
  </cfif>

  <body onload="myFunction()">
    <h1>Hello World!</h1>
    <cfform action="dropdowntest.cfm" method="post">
      <cfselect name="market1" id="market1"></cfselect>
      <br> <br>
      <button id="addTypes1" >add types</button><br> <br>
      <CFINPUT class="but" TYPE="submit" NAME="SUBMIT" VALUE="SEARCH">
    </cfform>

    <script>
    function myFunction() {
      //var selectedVal = $("#market1").val();
      var kinds = ["A", "B", "C"];
      $.each(kinds, function(index, value) {         
        $("#market1").append("<option value='"+value+"'>" +value+ "</option>");
        //$("#market1").val('selectedVal')
      });
    }
    </script>
  </body>
</html>

POST后如何再次选择值?

2 个答案:

答案 0 :(得分:0)

下拉列表将失去其值,因为您正在发布表单。因此,您需要保留它并将其设置为负载。一种方法是使用cookie

$('select[name=market1]').on('change', function() {
  $.cookie("marketVal", this.value );
});

现在在onload函数中,您可以检查此cookie值是否存在,并从中设置所选市场价值。

function myFunction() {
  var selectedVal = $.cookie("marketVal" );
  var kinds = ["A", "B", "C"];
  $.each(kinds, function(index, value) {         
    $("#market1").append("<option value='"+value+"'>" +value+ "</option>");
  });
  if(selectedVal) {
    $("#market1").val(selectedVal);
  }
}

答案 1 :(得分:-1)

不是通过jQuery编写选项,而是直接在ColdFusion中编写它们:

<cfselect name="market1" id="market1">
  <cfloop array="#['A', 'B', 'C']#" item="val">
    <option value="#val#"
        #structKeyExists(FORM, "market1") and FORM.market1 eq val ?
        " selected" : ""#>#val#</option>
  </cfloop>
</cfselect>

只有在异步加载数据时,才需要填充jQuery中的下拉列表,如下所示:

<script>
function myFunction() {
  var kinds = ["A", "B", "C"];
  $.each(kinds, function(index, value){
    $("##market1").append("<option value='"+value+"'>" +value+ "</option>");
  });
  <cfif structKeyExists(FORM, "market1")>
    $("##market1 > option[value=#FORM.market1#]").prop("selected", true);
  </cfif>
}
</script>