Javascript / JQuery получает значение из полей ввода таблицы - PullRequest
0 голосов
/ 30 августа 2018

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

Я создал похожую, но гораздо более простую таблицу HTML, с которой я могу поиграть. Я еще не смог добраться до части переключателя, потому что я все еще пытаюсь решить часть окна ввода, но мне нужно будет получить оба из них. В идеале я бы возвращал каждую строку в массив JSON.

JQuery, который я включил, возвращает «Не удается прочитать свойство« GetElementsByTagName »с неопределенным значением», но это только один из многих примеров, которые я пробовал без какого-либо успеха. Я тестировал варианты с .value, .text, .innerHTML, но я просто не могу получить то, что находится внутри коробки (или значение переключателя в этом отношении).

Любая помощь для начинающего JS?

//$('.tableRow').each(function() {
//  favoriteBeer = document.getElementsByClassName('favoriteBeer').document.GetElementsByTagName('input');
//  console.log(favoriteBeer);
//});
table {
  border-collapse: collapse;
}

table,
th,
td {
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
  <thead>
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th>Favorite Food</th>
      <th>Favorite Beer</th>
    </tr>
  </thead>
  <tbody>
    <tr class='tableRow'>
      <td>John</td>
      <td>30</td>
      <td><label><input type="radio" name="favoriteFood1" value="Pizza"/>Pizza</label><label><input type="radio" name="favoriteFood1" value="Tacos" />Tacos</label>
        <td><input type="text" class="favoriteBeer"></td>
    </tr>
    <tr class='tableRow'>
      <td>Joe</td>
      <td>25</td>
      <td><label><input type="radio" name="favoriteFood2" value="Pizza"/>Pizza</label><label><input type="radio" name="favoriteFood2" value="Tacos"/>Tacos</label>
        <td><input type="text" class="favoriteBeer"></td>
    </tr>
    <tr class='tableRow'>
      <td>Sam</td>
      <td>50</td>
      <td><label><input type="radio" name="favoriteFood3" value="Pizza"/>Pizza</label><label><input type="radio" name="favoriteFood3" value="Tacos"/>Tacos</label>
        <td><input type="text" class="favoriteBeer"></td>
    </tr>
  </tbody>
</table>

Ответы [ 3 ]

0 голосов
/ 30 августа 2018

Вы не можете запустить эту строку:

favoriteBeer = document.getElementsByClassName('favoriteBeer').document.GetElementsByTagName('input');

Поскольку document элемента .favoriteBeer не определено.

Кроме того, когда запускается $('.tableRow').each(function(), поле ввода остается пустым, поскольку оно запускается при загрузке страницы. Вместо этого вы можете прослушивать событие keyup и проверять текущее значение ввода каждый раз, когда пользователь что-то вводит.

Вроде так:

$('.favoriteBeer').keyup(function() {
  console.log($(this).val());
});
table {
  border-collapse: collapse;
}

table,
th,
td {
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
  <thead>
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th>Favorite Food</th>
      <th>Favorite Beer</th>
    </tr>
  </thead>
  <tbody>
    <tr class='tableRow'>
      <td>John</td>
      <td>30</td>
      <td><label><input type="radio" name="favoriteFood1"/>Pizza</label><label><input type="radio" name="favoriteFood1" />Tacos</label>
        <td><input type="text" class="favoriteBeer"></td>
    </tr>
    <tr class='tableRow'>
      <td>Joe</td>
      <td>25</td>
      <td><label><input type="radio" name="favoriteFood2"/>Pizza</label><label><input type="radio" name="favoriteFood2" />Tacos</label>
        <td><input type="text" class="favoriteBeer"></td>
    </tr>
    <tr class='tableRow'>
      <td>Sam</td>
      <td>50</td>
      <td><label><input type="radio" name="favoriteFood3"/>Pizza</label><label><input type="radio" name="favoriteFood3" />Tacos</label>
        <td><input type="text" class="favoriteBeer"></td>
    </tr>
  </tbody>
</table>
0 голосов
/ 30 августа 2018

Используйте цикл for с помощью $(this), чтобы получить соответствующие значения каждой строки, и выберите выбранные переключатели, используя input:radio:checked в качестве селектора, например:

$('button').click(function() {
  $('.tableRow').each(function() {
    var favoriteBeer = $(this).find('.favoriteBeer').val();
    var favoriteFood = $(this).find('input:radio:checked').val();

    var dataObj = {
      favoriteBeer: favoriteBeer,
      favoriteFood: favoriteFood
    };

    console.log(dataObj);
  });
})
table {
  border-collapse: collapse;
}

table,
th,
td {
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
  <thead>
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th>Favorite Food</th>
      <th>Favorite Beer</th>
    </tr>
  </thead>
  <tbody>
    <tr class='tableRow'>
      <td>John</td>
      <td>30</td>
      <td><label><input type="radio" name="favoriteFood1" value="Pizza"/>Pizza</label><label><input type="radio" name="favoriteFood1" value="Tacos" />Tacos</label>
        <td><input type="text" class="favoriteBeer"></td>
    </tr>
    <tr class='tableRow'>
      <td>Joe</td>
      <td>25</td>
      <td><label><input type="radio" name="favoriteFood2" value="Pizza"/>Pizza</label><label><input type="radio" name="favoriteFood2" value="Tacos"/>Tacos</label>
        <td><input type="text" class="favoriteBeer"></td>
    </tr>
    <tr class='tableRow'>
      <td>Sam</td>
      <td>50</td>
      <td><label><input type="radio" name="favoriteFood3" value="Pizza"/>Pizza</label><label><input type="radio" name="favoriteFood3" value="Tacos"/>Tacos</label>
        <td><input type="text" class="favoriteBeer"></td>
    </tr>
  </tbody>
</table>
<button type="button">Retrieve Data</button>
0 голосов
/ 30 августа 2018

Вы не можете вызвать document.getElementsByTagName() по результатам .getElementsByClassName(), потому что .getElementsByClassName() возвращает «список узлов», а список узлов не имеет свойства document. Но вы могли бы сделать это:

favoriteBeer = document.getElementsByClassName('favoriteBeer').getElementsByTagName('input');

Поскольку большинство методов запроса DOM можно вызывать на document, узле или списке узлов.

Тем не менее, .getElementsByClassName() и .getElementsByTagName() оба возвращают "живые" списки узлов, что означает, что каждый раз, когда вы ссылаетесь на переменную, которой вы присвоили результаты, весь документ необходимо повторно сканировать, чтобы убедиться, что вы получите самые актуальные результаты. Это полезно только тогда, когда у вас есть элементы, которые создаются / уничтожаются динамически. Если вы не работаете с таким кодом, использование этих методов не рекомендуется, поскольку они очень расточительны с точки зрения производительности.


Теперь, так как вы используете JQuery, вы должны использовать его последовательно. Просто передайте действительный селектор CSS в объект JQuery для сканирования DOM на предмет соответствия элементов.

Итак, вы можете просто передать имя класса в JQuery, чтобы получить набор ссылок на ваши DOM-объекты, а затем получить свойство value этих input элементов. Но вам нужно подождать, чтобы запустить этот код, пока пользователь не сможет ввести некоторые данные. Я добавил в ваш код элемент button, который вы можете щелкнуть, когда будете готовы увидеть входные значения.

$("button").on("click", function(){
  // Just passing a valid CSS selector to the JQuery object will
  // return a JQuery "wrapped set" of all matching elements.
  
  // Then, the .each() method takes a function that will automatically
  // be passed the index of the current element being iterated, a DOM reference
  // to the element itself, and a reference to the wrapped set (not used here).
  $('.favoriteBeer').each(function(index, element) {
   // You can use the element argument inside of the .each() loop
   // or you can use the "this" keyword to get the same DOM reference
   console.log(element.value, this.value);
  });
});
table {
  border-collapse: collapse;
}

table,
th,
td {
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
  <thead>
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th>Favorite Food</th>
      <th>Favorite Beer</th>
    </tr>
  </thead>
  <tbody>
    <tr class='tableRow'>
      <td>John</td>
      <td>30</td>
      <td><label><input type="radio" name="favoriteFood1"/>Pizza</label><label><input type="radio" name="favoriteFood1" />Tacos</label>
        <td><input type="text" class="favoriteBeer"></td>
    </tr>
    <tr class='tableRow'>
      <td>Joe</td>
      <td>25</td>
      <td><label><input type="radio" name="favoriteFood2"/>Pizza</label><label><input type="radio" name="favoriteFood2" />Tacos</label>
        <td><input type="text" class="favoriteBeer"></td>
    </tr>
    <tr class='tableRow'>
      <td>Sam</td>
      <td>50</td>
      <td><label><input type="radio" name="favoriteFood3"/>Pizza</label><label><input type="radio" name="favoriteFood3" />Tacos</label>
        <td><input type="text" class="favoriteBeer"></td>
    </tr>
  </tbody>
</table>
<button type="button">Get Data</button>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...