如何使用javascript更改表单的方法名称

我是 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");

    }

}

我尝试这样做,但它不起作用。有人可以帮我吗


摇曳的蔷薇
浏览 168回答 2
2回答

茅侃侃

您正在单选按钮上设置属性。而是将其设置在表单上。最小更改解决方案可能看起来像。function updatemethod() {&nbsp; &nbsp; const getBtn = document.getElementById("rdGet");&nbsp; &nbsp; const postBtn = document.getElementById("rdPost");&nbsp; &nbsp; if (getBtn.checked) {&nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("frmid").setAttribute("method", "GET");&nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; else if (postBtn.checked) {&nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("frmid").setAttribute("method", "POST");&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;}如果您在浏览器开发人员工具中检查该元素,您可以在单击单选按钮时看到方法发生了变化。还有另一种更简洁的方法是调用函数并传递this.onchange="updatemethod(this)"这里this指的是单选按钮元素,现在您不需要进行任何 DOM 树搜索。现在的功能是function updatemethod(elem) {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if (elem.checked) {&nbsp; &nbsp; &nbsp; &nbsp; elem.form.setAttribute("method", elem.value);&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;&nbsp;}但是,这取决于您value在 html 中是否具有适当的属性。例如<input type="radio"&nbsp; value="VALID VALUE HERE" ... />

POPMUISE

您可以为此使用 javascript DOM。function updatemethod() {&nbsp; &nbsp; let formfrmId = document.getElementById('frmid');&nbsp; &nbsp; let typeMethod = document.getElementsByName('typeMethod');&nbsp; &nbsp; let numberRadioTypeMethod = typeMethod.length;&nbsp; &nbsp; for (i = 0; i < numberRadioTypeMethod; i++ ) {&nbsp; &nbsp; &nbsp; &nbsp; if (typeMethod[i].checked)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; formfrmId.method = typeMethod[i].value;&nbsp; &nbsp; }}使用浏览器控制台,它将为您提供所有 DOM 属性和功能,供您在 javascript 中使用
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript