javascript 使用javascript获取输入框“名称”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12833110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:13:38  来源:igfitidea点击:

get the input box 'name' using javascript

phpjavascriptcodeigniter

提问by Parth Sarthi Gour

I am making form in PHP and submitting using javascript. I want to get the name of input box, As normal coding gives the value of the input box, but i need to get name of input box. Without onclick functionality on it. Can it possible that retrieving the name of input box in other javascript function on click a button. for example

我正在用 PHP 制作表单并使用 javascript 提交。我想获取输入框的名称,因为正常编码给出了输入框的值,但我需要获取输入框的名称。没有 onclick 功能就可以了。是否有可能在单击按钮时在其他 javascript 函数中检索输入框的名称。例如

<input type="radio" name="text_name" value="4" id="d">

Now onclick a other button I am calling test(), In test()how can I get the name of the input box.

现在点击我正在调用的另一个按钮test()test()如何获取输入框的名称。

采纳答案by Priyank Patel

var txtbox = document.getElementById("d");
var txtboxname = txtbox.name;

回答by bipen

u can do that by using attr function...

你可以通过使用 attr 函数来做到这一点......

in yout test function add this...

在你的测试功能中添加这个...

$('#d').attr('name');  // this will return text_name in your case (if you are using jquery)

OR

或者

var inputname=document.getElementById("d").name  //javascript

回答by polin

put this on your javascript function

把它放在你的 javascript 函数上

var name=document.getElementById("d").name;

回答by Merlin

function test() {
return document.getElementById("d").name; }

function test() {
return document.getElementById("d").name; }

回答by RobG

Not really sure what you are trying to do, but if your script is called from a listener on a button in the form, you can do:

不太确定您要做什么,但是如果您的脚本是从表单中按钮上的侦听器调用的,您可以执行以下操作:

<input type="button" value="Send form" onclick="doSubmit(this)">

Then the doSubmit function is something like:

然后 doSubmit 函数类似于:

function doSubmit(el) {
  var form = el.form;
  var control, controls = form.elements;

  for (var i=0, iLen=controls.length; i<iLen; i++) {
    control = controls[i];

    /*  
        Do stuff with control.
        Control name is control.name, control value is control.value
    */
  }
}

I would strongly recommend that your form has a standard submit button and works without any scripting, then you can add your scripted submission to the form's submit handler. It can cancel the standard submit and do its own thing.

我强烈建议您的表单有一个标准的提交按钮并且无需任何脚本即可工作,然后您可以将您的脚本提交添加到表单的提交处理程序中。它可以取消标准提交并做自己的事情。

That way if script is disabled, not available or fails for some reason, the user can still submit the form.

这样,如果脚本被禁用、不可用或由于某种原因失败,用户仍然可以提交表单。