Как проверить переключатель перед отправкой формы с помощью кнопки? - PullRequest
0 голосов
/ 12 февраля 2020

У меня есть форма с таблицей, и каждая строка этой таблицы представляет собой отдельное предложение. Итак, у меня также есть несколько кнопок в каждой строке, чтобы загрузить документацию предложения или удалить предложение. Эти кнопки отправляют форму и они go в другой файл php, который выполняет желаемое действие.

Моя проблема в том, что перед тем как я отправлю форму, необходимо проверить переключатель нужной строки. Есть ли способ с javascript, когда вы нажимаете одну из этих двух кнопок, сначала она автоматически выбирает переключатель этой строки, а затем отправляет форму?

<form class="filterSelection" action="../php/editOffer/getInfo.php" method="POST">
    <table class="accountsTable">
        <thead>
            <tr>
                <th>Selected</th>
                <th>Project ID</th>
                <th>Revision</th>
                <th>Project Description</th>
                <th>Customer</th>
                <th>Date</th>
                <th>Creator</th>
                <th>Documentation</th>
                <th>Delete</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td><input type="radio" name="selectedOffer" id="selectedOffer" required="" value="1-1"></td>
                <td>1</td>
                <td>1</td>
                <td>Test</td>
                <td>Info</td>
                <td>2020-02-10</td>
                <td>Name</td>
                <td>
                    <button type="submit" class="download" name="action" value="Download"><i class="fa fa-download" aria-hidden="true"></i></button>
                </td>
                <td>
                    <button type="submit" class="delete" name="action" value="Delete" onclick="return confirm('Do you want to delete the selected offer? This action can´t be undone')">
                        <i class="far fa-trash-alt"></i>
                    </button>
                </td>
            </tr>
        </tbody>
    </table>
    <br>
    <button name="action" class="nextButton" type="submit" value="Next"><i class="fas fa-arrow-alt-circle-right fa-2x"></i></button>
</form>

Ответы [ 4 ]

1 голос
/ 12 февраля 2020

Вы можете выбрать ближайший tr, чтобы найти указатель c. Затем установите атрибут checked , используя setAttribute().

. Вы можете попробовать следующий способ:

var buttons = document.querySelectorAll('button[type=submit');
buttons.forEach(function(btn){
  btn.addEventListener('click', function(el, e){
    this.closest('tr').querySelector('[type=radio]').setAttribute('checked', 'checked');
    alert(this.closest('tr').querySelector('[type=radio]').getAttribute('checked'));
  });
})
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<form class = "filterSelection" action = "../php/editOffer/getInfo.php" method = "POST">
  <table class = "accountsTable">
      <thead>
          <tr>
              <th>Selected</th>
              <th>Project ID</th>
              <th>Revision</th>
              <th>Project Description</th>
              <th>Customer</th>
              <th>Date</th>
              <th>Creator</th>
              <th>Documentation</th>
              <th>Delete</th>
          </tr>
      </thead>
      <tbody>
         <tr>
            <td><input type="radio" name="selectedOffer" id="selectedOffer" value="1-1">
            </td>
             <td>1</td>
             <td>1</td>
             <td>Test</td>
             <td>Info</td>
             <td>2020-02-10</td>
             <td>Name</td>
             <td><button type="submit" class="download" name="action" value="Download"><i class="fa fa-download" aria-hidden="true"></i></button>
              </td>
             <td><button type="submit" class="delete" name="action" value="Delete" onclick="return confirm('Do you want to delete the selected offer? This action can´t be undone')"><i class="fa fa-trash"></i></button></td>
        </tr>
        
        <tr>
            <td><input type="radio" name="selectedOffer" id="selectedOffer" value="1-1">
            </td>
             <td>1</td>
             <td>1</td>
             <td>Test</td>
             <td>Info</td>
             <td>2020-02-10</td>
             <td>Name</td>
             <td><button type="submit" class="download" name="action" value="Download"><i class="fa fa-download" aria-hidden="true"></i></button>
              </td>
             <td><button type="submit" class="delete" name="action" value="Delete" onclick="return confirm('Do you want to delete the selected offer? This action can´t be undone')"><i class="fa fa-trash"></i></button></td>
        </tr>
    </tbody>
  </table><br>
  <button name="action" class="nextButton" type="submit" value="Next"><i class="fa fa-arrow-alt-circle-right fa-2x"></i>    </button>
</form>
0 голосов
/ 14 февраля 2020

Наконец я решил добавить скрытый ввод и удалить переключатели. Я также изменил структуру форм. Вот мой код, который работает:

<table class = "accountsTable">
            <thead>
                <tr>
                    <th>Project ID</th>
                    <th>Revision</th>
                    <th>Project Description</th>
                    <th>Customer</th>
                    <th>Date</th>
                    <th>Creator</th>
                    <th>Download</th>
                    <th>Delete</th>
                    <th>Edit</th>
                </tr>
            </thead>
            <tbody>
              <tr>
                    <form class="filterSelection" action="../php/editOffer/getInfo.php" method="POST">
                        <td>1</td>
                        <td>1</td>
                        <td>Test</td>
                        <td>Info</td>
                        <td>2020-02-10</td>
                        <td>Name</td>
                        <td><button type="submit" class="download" name="action" value="Download"><i class="fa fa-download" aria-hidden="true"></i></button>
                            </td>
                        <td><button type="submit" class="delete" name="action" value="Delete" 
                                    onclick="return confirm('Do you want to delete the selected offer? This action can´t be undone')">
                                <i class="far fa-trash-alt"></i></button></td>
                        <td><button name="action" class="edit" type="submit" value="Next"><i class="fas fa-edit"></i></button></td>
                        <input type="hidden" name="selectedOffer" value="1-1"/>
                    </form>
                </tr>
                                        <tr>
                    <form class="filterSelection" action="../php/editOffer/getInfo.php" method="POST">
                        <td>1</td>
                        <td>2</td>
                        <td>Demo</td>
                        <td>Info1</td>
                        <td>2020-02-13</td>
                        <td>Name1</td>
                        <td></td>
                        <td><button type="submit" class="delete" name="action" value="Delete" 
                                    onclick="return confirm('Do you want to delete the selected offer? This action can´t be undone')">
                                <i class="far fa-trash-alt"></i></button></td>
                        <td><button name="action" class="edit" type="submit" value="Next"><i class="fas fa-edit"></i></button></td>
                        <input type="hidden" name="selectedOffer" value="1-2"/>
                    </form>
                </tr>
0 голосов
/ 12 февраля 2020

Вам необходимо внести небольшие изменения в форму, как показано ниже:

<form class="filterSelection" id="filter-form" action="../php/editOffer/getInfo.php" method="POST">
    <table class="accountsTable">
        <thead>
            <tr>
                <th>Selected</th>
                <th>Project ID</th>
                <th>Revision</th>
                <th>Project Description</th>
                <th>Customer</th>
                <th>Date</th>
                <th>Creator</th>
                <th>Documentation</th>
                <th>Delete</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td><input type="radio" name="selectedOffer" id="selectedOffer-1" value="1-1"></td>
                <td>1</td>
                <td>1</td>
                <td>Test</td>
                <td>Info</td>
                <td>2020-02-10</td>
                <td>Name</td>
                <td><button type="button" name="action" data-row="1" onclick="btnAction(this)" value="Download"><i
                            class="fa fa-download" data-row="1" aria-hidden="true"></i> Download</button>
                </td>
                <td><button type="button" name="action" onclick="btnAction(this)" value="Delete">
                        <i class="far fa-trash-alt"></i> Delete</button></td>
            </tr>
        </tbody>
    </table><br>
    <button name="submit" class="nextButton" type="button" value="Next"><i
            class="fas fa-arrow-alt-circle-right fa-2x"></i> Next</button>
</form>

Теперь вот код javascript, чтобы проверить некоторую проверку:

<script>
    function btnAction(btn) {
        var row = btn.dataset.row;
        var radio = document.getElementById("selectedOffer-"+row);
        radio.checked = true;
        document.getElementById("filter-form").submit();
    }
</script>

Надеюсь, что это произойдет работа для вас решение

0 голосов
/ 12 февраля 2020

добавить событие нажатия на кнопку

<td>
    <button type="button" class="delete" name="action" value="Delete" onclick="someAction(this);">
        <i class="far fa-trash-alt"></i>
    </button>
</td>

Jquery Код

Добавить Jquery библиотеку на страницу

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

Использовать скрипт ниже

function someAction(ds) {

   if(!$(ds).closest('tr').find('input[type="radio"]').is(':checked')){         

     $(ds).closest('tr').find('input[type="radio"]').prop('checked',true);
     if(confirm('Do you want to delete the selected offer? This action can´t be undone')){
          $(ds).parents('form').submit();
     }
  }               
}
...