如何避免即使提交后仍保留表单元素?

时间:2019-06-14 08:18:38

标签: javascript html asp.net-mvc-4

我必须通过匹配条件来创建元素。但是当我执行另一个条件时,先前创建的元素就在那里。如何使用Java脚本避免这种重复?this is what i am getting 我有这样的Javascript函数:

 function maketext(p) {

        var f = document.createElement('form');
        f.setAttribute('method', "post");
        f.setAttribute('id', "update");
        f.setAttribute('action', "updateprod");

        if (p == "Code") {

            var inp = document.createElement('input');
            inp.setAttribute("placeholder", "Type Here");
            inp.setAttribute("class", "form-control");
            inp.setAttribute("id", "mcode");
            inp.setAttribute("name", "mcode");
            var sub = document.createElement("input");
            sub.setAttribute("type", "submit");
            sub.setAttribute("value", "submit");
            sub.setAttribute("class", "btn btn-primary");

            f.appendChild(inp);
            f.appendChild(sub);
            document.getElementById("mys").appendChild(f);

        }
        if (p == "Name") {
            var inp = document.createElement('input');
            inp.setAttribute("placeholder", "Type Here");
            inp.setAttribute("class", "form-control");
            inp.setAttribute("id", "mname");
            inp.setAttribute("name", "mname");
            var sub = document.createElement("input");
            sub.setAttribute("type", "submit");
            sub.setAttribute("value", "submit");
            sub.setAttribute("class", "btn btn-primary");

            f.appendChild(inp);
            f.appendChild(sub);
            document.getElementById("mys").appendChild(f);
        }
}

HTML

    <a href="#" onclick="maketext('Code')" data-toggle="modal" data-target="#myModal"  class="btn btn-info btn-lg">Edit</a>

<a href="#" onclick="maketext('Name')" data-toggle="modal" data-target="#myModal"  class="btn btn-info btn-lg">Edit</a> 

1 个答案:

答案 0 :(得分:1)

在创建元素之前,请从div

中删除所有先前的元素

function maketext(p) {
  document.getElementById("mys").innerHTML = ''
  // rest of the code
}