将表单输入值与所选选项合并



我想通过使用jQuery实时组合选项和输入字段中的值。

<input name="recipe" id="recipe" value="tablespoons" />
<select id="spoon_value" name="spoon_value">
<option value="1" selected="">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

也许这样的事情会起作用,但我遇到了错误。

Uncaught SyntaxError: Unexpected identifier

$('select#spoon_value').each(function(i) {
$(select[name=spoon_value] option[value=" + this.data.spoon_value + "]").html() + this.data.recipe);

我想要的输出是 2 汤匙或 3 汤匙等等。

<!doctype>
<html>
<head>
    <script>
        function _(x){
            return document.getElementById(x);
        }
        function update() {
            var tbsVal = _("spoon_value").value;
            var output = tbsVal + " tablespoons";
            _("realtimeTbsVal").innerHTML = output;
        }
    </script>
</head>
<body>
    <form action="yourFileName" method="post">
        <select id="spoon_value" name="spoon_value" onblur="update()">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
        </select>
        <input type="submit" value="Submit">
    </form>
    <div id="realtimeTbsVal">yo</div>
</body>
</html>

你在each函数中的选择器周围缺少引号——你还有一个针对 ID 的each函数,这很糟糕,因为它很可能意味着你在重复 ID。下面是代码的语法正确版本:

$('select#spoon_value').each(function(i) {
    var someData = $("select[name=spoon_value] option[value=" + this.data.spoon_value + "]").html() + this.data.recipe;
});

最新更新