【问题标题】:Return element class post form submission返回元素类 post 表单提交
【发布时间】:2018-05-29 23:13:36
【问题描述】:

我正在尝试使用按钮创建可自定义的复选框。我能够区分选择了哪个按钮类,但我无法跟踪表单提交后的按钮类。理想情况下,我可以保留最初提供的任何输入,而不是在加载或提交页面时将按钮重置为默认值。我尝试过使用 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>

【问题讨论】:

    标签: javascript php jquery html


    【解决方案1】:

    如何删除表单标签并向提交按钮添加“点击”事件侦听器?如下所示的代码插入附加到文件末尾:

    <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>
    

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

    【讨论】:

    • 这应该可以解决我遇到的其他一些问题。我会试一试并更新。在我现有的代码中级联更改需要一段时间。
    • 我认为这会奏效。我目前有一个需要重新加载表单的 php sql 查询,但我应该能够切换到 AJAX 方法。
    猜你喜欢
    • 1970-01-01
    • 2021-03-30
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多