返回元素类后表单提交

时间:2018-05-29 23:13:37

标签: javascript php jquery html

我正在尝试使用按钮创建可自定义的复选框。我能够区分选择了哪个按钮类,但是我无法跟踪按钮类的表单提交。理想情况下,我可以保留最初提供的任何输入,而不是在加载或提交页面时将按钮重置为默认值。我已经尝试过使用isset()php函数,但我认为在这种情况下它不是一个有效的解决方案。还有其他选择吗?在下面找到我的代码:

<form id="my-form" method="post">
<html>
<body >

 <style>    
  .button {
    color: white;
    padding: 10px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 12px;
    margin: 4px 2px;
    cursor: pointer;
  }

  .button1 {
    border-radius: 100%;
    background-color: green;
    border: none;
  }

  .button2 {
    border-radius: 100%;
    background-color: red;
    border: none;
  } 
</style>

<div id="test1"></div>
<div id="test2"></div>

<!-- invalid code?
<?php
echo isset($_POST["t1test"]);
echo isset($_POST["t2test"]);
echo $_POST["t1test"];
echo $_POST["t2test"];
?>
-->

<script type="text/javascript">

  function makeButton(div, val) {
    var element = document.getElementById(val);
    var button = document.createElement("button");
    var span = document.createElement("span");
    // change to account for submitted settings
    if (element == null) {
      button.setAttribute("class", "button button1"); }
    else {
      var cL1 = element.classList.contains("button1");
      var cL2 = element.classList.contains("button2");
      element.parentNode.removeChild(element);
      if (cL2 == true) { button.setAttribute("class", "button button1"); }
      if (cL1 == true) { button.setAttribute("class", "button button2"); }
    }
    button.setAttribute("type", "button");
    button.setAttribute("id", val);
    button.setAttribute("name", val);
    var testDiv = document.getElementById(div);
    testDiv.appendChild(button);
    button.addEventListener ("click", function() { makeButton(div, val); }) 
  }

  window.onload = function() {
    makeButton("test1", "t1test"); 
    makeButton("test2", "t2test"); }

</script>

</body>
</html>

<button id="submit">Submit</button>
</form>

1 个答案:

答案 0 :(得分:1)

如何删除表单标记并添加&#34;点击&#34;事件监听器提交按钮?下面显示的代码附加到文件的末尾:

<script>
document.getElementById("submit").addEventListener("click", function(){
  var elements = ["t1test", "t2test"];
  for(var i = 0; i < elements.length; i++) {
    var element = document.getElementById(elements[i]);
    console.log(element.classList.contains("button1"));
    console.log(element.classList.contains("button2"));
  }
});
</script>

这样,按下按钮时不会重新加载页面,从而保留按钮选择。