2011-07-10 61 views
-1

我有以下的HTML表单:用JQuery更新这些表单域的最简单方法是什么?

<form> 
<input type="checkbox" name="fruits[]" value="apples" /><input type="text" value="false" /><br/> 
<input type="checkbox" name="fruits[]" value="oranges" /><input type="text" value="false" /><br/> 
<input type="checkbox" name="fruits[]" value="grapes" /><input type="text" value="false" /><br/> 
<input type="checkbox" name="fruits[]" value="bananas" /><input type="text" value="false" /><br/> 
</form> 

现在我想写一些JavaScript/JQuery的,这样当我选中或取消选中复选框,对应的文本框中显示“真”或“假”。在不改变javascript的情况下添加更多水果应该很容易。

以优雅的方式做到这一点的最佳方式是什么?

+1

你真的需要展示一些像尝试。现在它更像是一个帮助的命令。相反,你是什么谷歌,你为什么不是你的方式是优雅的东西。我有客户使用你的语言,“应该很容易......”我们不在这里为你写代码。 – austinbv

回答

1

这很容易在纯JavaScript中,你并不需要jQuery。只需为每个复选框的onchange事件分配一个可更新文本字段的函数,复选框和文本字段之间就必须有关系。该功能可能类似于:

// assign to onchange like: onchange="updateTextField(this)" 
function updateTextField(cb) { 
    // this assumes that the corresponding text field has id with the same name as the 
    // checkbox value 
    var tf = document.getElementById(cb.value); 
    tf.value = cb.checked.toString(); 
} 
1

您需要在复选框和文本字段之间存在某种关系。像这样的东西可以使用jQuery,并且是非常可扩展的。

<form> 
    <input type="checkbox" value="apples" /><input type="text" value="false" for="apples"/><br/> 
    <input type="checkbox" value="oranges" /><input type="text" value="false" for="oranges" /><br/> 
    <input type="checkbox" value="grapes" /><input type="text" value="false" for="grapes" /><br/> 
    <input type="checkbox" value="bananas" /><input type="text" value="false" for="bananas"/><br/> 
</form> 

<script> 
$(function() { 
    $(":checkbox").click(function() { 
     if ($(this).attr('checked')) { 
      $('input[for$="' + $(this).val() + '"]').val("true"); 
     } else { 
      $('input[for$="' + $(this).val() + '"]').val("false"); 
     } 
    }) 
}) 
</script> 
相关问题