如何通过传递表单作为参考来获取复选框的值?

时间:2015-04-13 18:37:19

标签: javascript

我是一个javascript noob。我目前正在学习如何检查是否选中了复选框。这是代码:

    <!doctype>

<html>
<head>
<title>Javascript form - input text Field</title>
<script>
var outputt = "";
var i = 0;
function output(frm){
for(i = 0; i < frm.fruits.length; i++){
    if(frm.fruits[i].checked){
        outputt =+ fruits[i].text;
        }
    }
alert(outputt);
}

</script>
</head>
<body>

<form>
<p>Click on your favourite fruits</p>
<input type="checkbox" name="fruits" value="strawberry">Strawberry</input>
<input type="checkbox" name="fruits" value="banana">banana</input>
<input type="checkbox" name="fruits" value="apple">apple</input>
<input type="checkbox" name="fruits" value="kiwi">kiwi</input>

<input type="button" name="validate" value="validate" onClick="output(this.form)">
<input type="reset">
</form>


</body>
</html>

我想要做的是当用户点击“验证”按钮时,调用输出函数,该函数将表单作为参考传递。在函数中,它将复选框作为数组,然后遍历每个复选框,检查它们是否被勾选。如果勾选了任何框,则该值将连同到输出字符串。

编辑:虽然我不太了解解决方案,但我设法解决了这个问题。所以在下面的代码中,函数ouput()接受checkBoxArray的参数,这个引用来自按钮'validate'。如果我的表单中有2个复选框输入怎么办(即一个用于喜欢的饮料,一个用于喜欢的水果)。浏览器如何知道要检查哪个复选框?

<!doctype>

<html>
<head>
<title>Javascript form - input text Field</title>
<script>
var outputt = "";
var i = 0;
function output(checkBoxArray){
for(i = 0; i < checkBoxArray.length; i++){
    if(checkBoxArray[i].checked){
        outputt += checkBoxArray[i].value;
        }
    }
alert(outputt);
}

</script>
</head>
<body>

<form>
<p>Click on your favourite fruits</p>
<input type="checkbox" name="fruits" value="strawberry">Strawberry</input>
<input type="checkbox" name="fruits" value="banana">banana</input>
<input type="checkbox" name="fruits" value="apple">apple</input>
<input type="checkbox" name="fruits" value="kiwi">kiwi</input>

<input type="button" name="validate" value="validate" onClick="output(this.form)">
<input type="reset">
</form>


</body>
</html>

2 个答案:

答案 0 :(得分:1)

  

我要做的是当用户点击“验证”时。按钮,调用输出函数,将表单作为引用传递。 [在]函数中,它将复选框作为数组...

不,它没有;它访问HTMLInputElement个节点 - 碰巧是复选框 - 并使用循环遍历它们。这并不能使它们成为一个阵列,它们甚至不是NodeList,它只是浏览器使用i变量的增量来检索,并在循环内依次访问每个<input />元素。

  

...然后遍历每个复选框,检查它们是否被勾选 [选中]。如果勾选了任何框,则该值将连接到outputt字符串。

首先,我会整理您发布的代码并解释原因(在评论中,在代码中):

// this is a matter of taste, but I've changed the variable's name from
// 'frm' to 'form' to be more clear of its contents:
function output(form) {
  // this isn't used outside the function, and global variables
  // can lead to (unanticipated) mistakes; here we initialise the
  // variable within the function in which it's used:
  var outputt = '';

  // initialising the 'i' variable within the loop itself (since
  // that's where it's being used), and caching the number of
  // elements returned by 'form.fruits.length' (to avoid having
  // to re-check it on every iteration):
  for (var i = 0, len = form.fruits.length; i < len; i++) {
    if (form.fruits[i].checked) {
      // your updated excerpt showed that you'd realised the
      // concatenation operator should be '+=' and not '=+',
      // but obviously I corrected that here; also your code had
      // 'fruits[i].value' omitting the 'form', so you were
      // trying to access an element from an
      // uninitialised/undeclared variable:
      outputt += form.fruits[i].value;
    }
  }
  // a matter of taste (again), but using 'console.log()' in place
  // of Window.alert() reduces interruptions/work-flow:
  console.log(outputt);
}

&#13;
&#13;
function output(form) {
  var outputt = '';
  for (var i = 0, len = form.fruits.length; i < len; i++) {
    if (form.fruits[i].checked) {
      outputt += form.fruits[i].value;
    }
  }
  console.log(outputt);
}
&#13;
<form action="#" method="post">
  <p>Click on your favourite fruits</p>
  <input type="checkbox" name="fruits" value="strawberry" />Strawberry
  <input type="checkbox" name="fruits" value="banana" />banana
  <input type="checkbox" name="fruits" value="apple" />apple
  <input type="checkbox" name="fruits" value="kiwi" />kiwi

  <input type="button" name="validate" value="validate" onClick="output(this.form)" />
  <input type="reset" />
</form>
&#13;
&#13;
&#13;

现在,您会注意到字符串在没有空格的情况下连接在一起,有几种方法可以避免这种情况。第一个使用条件(&#39;三元&#39;)运算符来评估outputt字符串的长度是真实的(非零)还是假的(0):

outputt += (outputt.length > 0 ? ' ' : '') + form.fruits[i].value;

&#13;
&#13;
function output(form) {
  var outputt = '';
  for (var i = 0, len = form.fruits.length; i < len; i++) {
    if (form.fruits[i].checked) {
      outputt += (outputt.length > 0 ? ' ' : '') + form.fruits[i].value;
    }
  }
  console.log(outputt);
}
&#13;
<form action="#" method="post">
  <p>Click on your favourite fruits</p>
  <input type="checkbox" name="fruits" value="strawberry" />Strawberry
  <input type="checkbox" name="fruits" value="banana" />banana
  <input type="checkbox" name="fruits" value="apple" />apple
  <input type="checkbox" name="fruits" value="kiwi" />kiwi

  <input type="button" name="validate" value="validate" onClick="output(this.form)" />
  <input type="reset" />
</form>
&#13;
&#13;
&#13;

另一种方法是使用数组来记录已选中复选框的值:

function output(form) {
  // initialising an empty array, using an array
  // literal (the '[]' part):
  var outputt = [];
  for (var i = 0, len = form.fruits.length; i < len; i++) {
    if (form.fruits[i].checked) {
      // adding each of the checked-<input> element's
      // value to that array:
      outputt.push(form.fruits[i].value);
    }
  }
  // Using Array.prototype.join() to join the array-elements
  // together, with the specified character, to form a string:
  console.log(outputt.join(' '));
}

&#13;
&#13;
function output(form) {
  var outputt = [];
  for (var i = 0, len = form.fruits.length; i < len; i++) {
    if (form.fruits[i].checked) {
      outputt.push(form.fruits[i].value);
    }
  }
  console.log(outputt.join(' '));
}
&#13;
<form action="#" method="post">
  <p>Click on your favourite fruits</p>
  <input type="checkbox" name="fruits" value="strawberry" />Strawberry
  <input type="checkbox" name="fruits" value="banana" />banana
  <input type="checkbox" name="fruits" value="apple" />apple
  <input type="checkbox" name="fruits" value="kiwi" />kiwi

  <input type="button" name="validate" value="validate" onClick="output(this.form)" />
  <input type="reset" />
</form>
&#13;
&#13;
&#13;

此外,我建议从HTML中删除内联事件处理程序 - 将onClick属性从HTML中取出,并将其替换为添加了JavaScript的事件处理程序:

function output() {
  // 'this' is passed in automagically from the
  // addEventListener() method, the form-node is
  // found exactly the same way as in your own code:
  var form = this.form,
    outputt = [];

  for (var i = 0, len = form.fruits.length; i < len; i++) {
    if (form.fruits[i].checked) {
      outputt.push(form.fruits[i].value);
    }
  }
  console.log(outputt.join(' '));
}

// finding all elements whose 'name' property is 'validate':
var validator = document.getElementsByName('validate');

validator[0].addEventListener('click', output);

&#13;
&#13;
function output() {
  var form = this.form,
    outputt = [];

  for (var i = 0, len = form.fruits.length; i < len; i++) {
    if (form.fruits[i].checked) {
      outputt.push(form.fruits[i].value);
    }
  }
  console.log(outputt.join(' '));
}

var validator = document.getElementsByName('validate');

validator[0].addEventListener('click', output);
&#13;
<form action="#" method="post">
  <p>Click on your favourite fruits</p>
  <input type="checkbox" name="fruits" value="strawberry" />Strawberry
  <input type="checkbox" name="fruits" value="banana" />banana
  <input type="checkbox" name="fruits" value="apple" />apple
  <input type="checkbox" name="fruits" value="kiwi" />kiwi

  <input type="button" name="validate" value="validate" />
  <input type="reset" />
</form>
&#13;
&#13;
&#13;

现在,我已经整理了一下,我想更进一步,实际创建和使用数组来解决这个问题,并使用一些更新的方法来找到相关的元素: / p>

function output() {
  // using Array.prototype.map(), in conjunction with
  // Function.prototype.call(), to apply an array-method to
  // the array-like nodeList (this.form.fruits):
  var outputt = Array.prototype.map.call(this.form.fruits, function(fruit) {
    // the first argument to the callback function (here 'fruit') is
    // the element of the array (here it's an <input /> element),

    // if it's checked:
    if (fruit.checked) {
      // we store the value ('apple', 'banana' etc) in
      // the array:
      return fruit.value;
    }
  });

  console.log(outputt.join(' '));
}

// using document.querySelector() to retrieve the first (if any)
// element in the document that matches the given CSS selector,
// here we're looking for an input element whose type is equal to 'button'
// and whose name is equal to 'validate':
var validator = document.querySelector('input[type=button][name=validate]');

validator.addEventListener('click', output);

&#13;
&#13;
function output() {

  var outputt = Array.prototype.map.call(this.form.fruits, function(fruit) {
    if (fruit.checked) {
      return fruit.value;
    }
  });

  console.log(outputt.join(' '));
}

var validator = document.querySelector('input[type=button][name=validate]');

validator.addEventListener('click', output);
&#13;
<form action="#" method="post">
  <p>Click on your favourite fruits</p>
  <input type="checkbox" name="fruits" value="strawberry" />Strawberry
  <input type="checkbox" name="fruits" value="banana" />banana
  <input type="checkbox" name="fruits" value="apple" />apple
  <input type="checkbox" name="fruits" value="kiwi" />kiwi

  <input type="button" name="validate" value="validate" />
  <input type="reset" />
</form>
&#13;
&#13;
&#13;

此外,有必要避免在循环内部检查<input>元素是checked是否为checked,只选择那些 { {1}}:

function output() {

  // here we're using the querySelectorAll() method to retrieve
  // only those <input> elements within the form that are checked:
  var outputt = Array.prototype.map.call(this.form.querySelectorAll('input:checked'), function(fruit) {
    return fruit.value;
  });

  console.log(outputt.join(' '));
}

&#13;
&#13;
function output() {

  var outputt = Array.prototype.map.call(this.form.querySelectorAll('input:checked'), function(fruit) {
    return fruit.value;
  });

  console.log(outputt.join(' '));
}

var validator = document.querySelector('input[type=button][name=validate]');

validator.addEventListener('click', output);
&#13;
<form action="#" method="post">
  <p>Click on your favourite fruits</p>
  <input type="checkbox" name="fruits" value="strawberry" />Strawberry
  <input type="checkbox" name="fruits" value="banana" />banana
  <input type="checkbox" name="fruits" value="apple" />apple
  <input type="checkbox" name="fruits" value="kiwi" />kiwi

  <input type="button" name="validate" value="validate" />
  <input type="reset" />
</form>
&#13;
&#13;
&#13;

参考文献:

答案 1 :(得分:0)

由于您不熟悉JavaScript,我建议您熟悉使用浏览器附带的开发人员工具(使用Chrome和IE中的F12访问),尤其是调试器。在那里,您可以设置断点并查看可以访问的值。

另外,正如Morten建议的那样,我会研究jQuery(一个流行的免费JavaScript库);它让事情变得更容易。

以下帖子可能会回答您的问题:

How to set up groups of checkboxes which affect each other

我认为第一步是熟悉调试器,因为代码中存在语法错误。