【问题标题】:How to change the method name of a form using javascript如何使用javascript更改表单的方法名称
【发布时间】:2019-10-01 02:25:25
【问题描述】:

我是 JavaScript 新手。我有这样的表格

<form id="frmid" action="index.php" method="get">    
    <label>Method</label>
    <input type="radio" name="typeMethod" value="POST" id="rdPost" checked="checked"  onchange="updatemethod()"/>
    <label for="rdPost">POST</label>
    <input type="radio" name="typeMethod" value="GET" id="rdGET" onchange="updatemethod()" />
    <label for="rdGET">GET</label>    
    <input type="text" name="firstName" value="" id="txtFirst" />    
    <input type="text" name="middleName" value="" id="txtMiddle" />
    <input type="text" name="lastName" value="" id="txtLast" />    
    <input type="submit" name="submit" id="txtSubmit" value="Send Information" />       
</form>

我有一个带有单选按钮的 html 表单。我正在尝试编写一个javascript函数updatemethod(),当我选择一个单选按钮时,它会根据单选按钮进行更改。 我已经这样做了

function updatemethod() {
    get = document.getElementById("rdGet");
    post = document.getElementById("rdPost");

    if (get.isChecked) {
        get.setAttribute("method", "GET");
    } else {
        post.setAttribute("method", "POST");
    }
}

我尝试这样做,但它不起作用。 谁能帮帮我

【问题讨论】:

  • 请向我们展示您在 javascript 上的 updatemethod 函数和控制台日志 javascript 错误。那里可能有更多线索。
  • 正如保罗所说,你把一些东西弄混了,你把它设置为你的无线电输入

标签: javascript forms radio-button


【解决方案1】:

您正在设置单选按钮的属性。而是将其设置在表单上。

最小更改解决方案可能看起来像。

function updatemethod() {
    const getBtn = document.getElementById("rdGet");
    const postBtn = document.getElementById("rdPost");

    if (getBtn.checked) {
        document.getElementById("frmid").setAttribute("method", "GET");
    } 
    else if (postBtn.checked) {
        document.getElementById("frmid").setAttribute("method", "POST");
    }            
}

如果您在浏览器开发人员工具中检查元素,您可以在单击单选按钮时看到方法发生变化。

通过调用函数并传递this,还有另一种更简洁的方法。

onchange="updatemethod(this)"

这里的this 指的是单选按钮元素,现在您不需要进行任何 DOM 树搜索。

功能现在

function updatemethod(elem) {    
    if (elem.checked) {
        elem.form.setAttribute("method", elem.value);
    }      
}

然而,这取决于您的 html 中是否有适当的 value 属性。

例如

<input type="radio"  value="VALID VALUE HERE" ... />

【讨论】:

    【解决方案2】:

    您可以为此使用 javascript DOM。

    function updatemethod() {
    
        let formfrmId = document.getElementById('frmid');
        let typeMethod = document.getElementsByName('typeMethod');
        let numberRadioTypeMethod = typeMethod.length;
    
        for (i = 0; i < numberRadioTypeMethod; i++ ) {
            if (typeMethod[i].checked) 
                formfrmId.method = typeMethod[i].value;
        }
    }
    

    使用浏览器控制台,它将为您提供所有 DOM 属性和功能,供您在 javascript 中使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-17
      • 2012-12-18
      • 2019-04-18
      • 1970-01-01
      相关资源
      最近更新 更多