yesod表单使用jquery

时间:2015-12-04 01:05:58

标签: yesod yesod-forms

我暂时使用 Monadic Form of Yesod 来创建表单,但我很难用jquery在其上设置值。由于 Monadic Form 为您生成表单,因此它有自己的方式在select / multi-select字段上设置值

例如:

sampleForm :: Html -> MForm Handler (FormResult (Maybe [Text]), Widget)
sampleForm = renderBootstrap bConfig $ (,)
    <$> aopt (multiSelectFieldList $ colors) "Color" Nothing
  where
    colors :: [(Text, Color)]
    colors = [("Red", Red), ("Blue", Blue), ("Gray", Gray), ("Black", Black)]

输出:

   <select multiselect>
       <option value="1">Red</option>
       <option value="2">Blue</option>
       <option value="3">Gray</option>
      <option value="4">Black</option>
   </select>

我想要的是这样:

<select id="colors" multiselect>
     <option value="Red">Red</option>
     <option value="Blue">Blue</option>
     <option value="Gray">Gray</option>
     <option value="Black">Black</option>
</select>

这样在我的jquery代码中:

var selectedValues = "Red,Black,Gary";
$.each(selectedValues.split(","), function(i,e){
  $("#colors option[value='" + e.replace(/\s/g, '') + "']").prop("selected", true);
});

希望你能帮助我,提前谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容替换您的jQuery代码。

var selectedValues = ["Red", "Black", "Gray"];
$("option").removeAttr('selected');
$.each(selectedValues, function (idx, val) {
    $("option").filter(":contains(" + val + ")").attr('selected', true);
});