javascript - 单选按钮在javascript函数中产生未定义的值

标签 javascript function radio-button

我正在尝试将单选按钮的值发送到 javascript 函数。最终这个函数会做更多的事情,但我的测试已经走到了尽头,因为我一直得到一个未定义的返回值。这是我所拥有的:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
<SCRIPT TYPE="text/javascript">
 <!--
 function jobWindow(){
  var target;
  for( i = 0; i < document.jobView.sales.length; i++ ){
   if( document.jobView.sales[i].checked == true )
   target = document.jobView.sales[i].value;
   break;
  }
  alert( "val = " + target );
  //var load = window.open('target','','scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');  
 }
 // -->
</script>

</head>

<body>

<form name="jobView">
<input name ="sales" value="all" type="radio" />All&nbsp;&nbsp;&nbsp;&nbsp;
<input name="sales" value="darell"  type="radio" />Darell&nbsp;&nbsp;&nbsp;&nbsp;
<input name="sales" value="kevin" type="radio" />Kevin&nbsp;&nbsp;&nbsp;&nbsp;
<input name="sales" value="brad" type="radio" />Brad&nbsp;&nbsp;&nbsp;&nbsp;
<input name="sales" value="chongo" type="radio" />Chongo&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="button" value="View Records" onclick="jobWindow()"/>&nbsp;&nbsp;&nbsp;&nbsp;
<input type="button" value="View Calendar" />
</form>

</body>

</html>

最佳答案

你真正想要的访问路径是:

var el = document.forms["jobView"].elements["sales"];

直点链 (document.jobView.sales) 对“all”集合进行隐式调用,这仅在 IE 中有效。 (是的,我知道 Firefox 在出现问题时会在其错误控制台中返回一个外观相同的字符串,但实际上您不能在自己的代码中使用它。)getELementsByTagName() 和 getElementsByName() 可以正常工作,但随后您需要确保返回的集合中的元素是您真正想要的元素。 (假设有一天你想在页面上创建多个表单,并且字段名称会发生​​冲突。当然,这永远不会发生,除非你一开始就没有做出这个假设,于是另一个开发人员将立即向您刚刚提交的页面添加第二个表单。)

关于javascript - 单选按钮在javascript函数中产生未定义的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3739051/

相关文章:

java - 如何在 GWT 中使用非静态方法@Using window.addEventListener ('message' ~

javascript - 选项卡破坏了我在 Wordpress 主题中的 slider CSS

javascript - TypeScript 类型安全省略函数

python - 是否可以控制函数在 python 中的执行方式?

javascript - 如何将模态对话框确认结果传递回调用函数?

javascript - 找出区间内未知函数的最大值

jquery - 阻止 jQuery Validate 修改单选按钮标记?

php - 在 php 中的 Javascript 函数中获取单选按钮字段值

jQuery 在每个单选按钮或复选框旁边添加空标签

javascript - 按键名过滤 JSON 数据