首页 > 解决方案 > 如何在onclick事件完成后将“按钮”按钮更改为“提交”按钮onclick而不提交?

问题描述

我有一个按钮,单击该按钮时,会通过onclickJavaScript 函数动态提示用户提供更多信息:

<button type="button" id="create" onclick="addFields()">create?</button>

将新信息加载到页面后,我希望按钮提交表单:

// .js file
function addFields(){
    var container = document.getElementById("initialinfo");
    var newInfo = document.createElement('div');
    newInfo.setAttribute("id", "createDetails");
    newInfo.innerHTML += "divs and checkboxes and radios"
    container.appendChild(newInfo);

    document.getElementById("create").removeAttribute("onclick");
    document.getElementById("create").setAttribute('type', 'submit');

}

不幸的是,当我这样做时,表单不会在下次点击时提交。相反,在onclick事件之后,按钮(现在是 type submit)提交表单。如何防止这种行为?

标签: javascripthtml

解决方案


您可以在第二次单击按钮时以编程方式触发表单

<form id="myForm" action="..." >
    <button type="button" onclick="addFields(event)">continue?</button>
</form>

function addFields({target}){
    var container = document.getElementById("initialinfo");
    var newInfo = document.createElement('div');
    newInfo.setAttribute("id", "createDetails");
    newInfo.innerHTML += "divs and checkboxes and radios"
    container.appendChild(newInfo);

   // here we change the onclick event handler
   target.onclick = () => {
     const form = document.getElementById('myForm')
     form.reportValidity() && form.submit()     
   }
}

推荐阅读