сохранить входное значение в л oop с javascript - PullRequest
0 голосов
/ 18 февраля 2020

У меня есть поле ввода столбца в <td>, которое находится в l oop, из-за этого каждое Row имеет input поле. Я получил javascript, из которого оно хранит local storage для input поле, но проблема в том, что javascript работает только для одного input Например:

У меня есть пять строк, и из-за l oop input поле, сгенерированное для 5 строк автоматически

То, что я ищу, - это хранить разные значения для каждой строки. Из-за этого сценария он не реализуется для каждой строки отдельно

Код

<input type="text" id="txt_1" onkeyup='saveValue(this);'/> 

Javascript

<script type="text/javascript">
        document.getElementById("txt_1").value = getSavedValue("txt_1");    // set the value to this input
        document.getElementById("txt_2").value = getSavedValue("txt_2");   // set the value to this input
        /* Here you can add more inputs to set value. if it's saved */

        //Save the value function - save it to localStorage as (ID, VALUE)
        function saveValue(e){
            var id = e.id;  // get the sender's id to save it . 
            var val = e.value; // get the value. 
            localStorage.setItem(id, val);// Every time user writing something, the localStorage's value will override . 
        }

        //get the saved value function - return the value of "v" from localStorage. 
        function getSavedValue  (v){
            if (!localStorage.getItem(v)) {
                return "";// You can change this to your defualt value. 
            }
            return localStorage.getItem(v);
        }
</script>

Отображение изображения

enter image description here

КОД

<table class="table table-hover table-striped table-bordered" id="input-group">
<thead ><tr >
 <th class="text-right"><?php echo "Contact No."; ?></th>
  <th><?php echo "Followup 1 Date"; ?>
    </th></tr></thead>
    <tbody>
    <?php
      if (empty($enquiry_list)) {
       ?>
       <?php
        } else {
        foreach ($enquiry_list as $key => $value) {
         $current_date = date("d/m/Y");
         $next_date = $value["next_date"];
         if (empty($next_date)) { $next_date = $value["follow_up_date"];
          }if ($next_date < $current_date) {                                      
          $class = "class='danger'";} else {
           $class = ""; } ?>
           <td class="mailbox-name"><?php echo $value['contact']; ?> </td>
   <td class="mailbox-name" >
    <div  style="width:200px" style="height:200px" >
     <input id="txt_<?= $row[id] ?>" onkeyup='saveValue(this);' 
      autocomplete="off" type="text" class="form-control"   /></div></td>
      </tr> </tr>
      <?php }}?> </tbody> </table>

Ответы [ 3 ]

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

var inputGroup = document.getElementById('input-group');
var inputs = inputGroup.getElementsByTagName('input');

for(i=0;i<inputs.length;i++)
{
	var id = inputs[i].getAttribute('id');
	inputs[i].value = getSavedValue(id);
} 
 
//Save the value function - save it to localStorage as (ID, VALUE)
function saveValue(e){
    var id = e.id;  // get the sender's id to save it . 
    var val = e.value; // get the value. 
    localStorage.setItem(id, val);// Every time user writing something, the localStorage's value will override . 
}

//get the saved value function - return the value of "v" from localStorage. 
function getSavedValue  (v){
    if (!localStorage.getItem(v)) {
        return "";// You can change this to your defualt value. 
    }
    return localStorage.getItem(v);
}
<table id="input-group">
  <tr>
  	<th>Text 1</th>
  	<th><input type="text" id="txt_1" onkeyup='saveValue(this);'/> </th>
  </tr>
  <tr>
  	<th>Text 2</th>
  	<th><input type="text" id="txt_2" onkeyup='saveValue(this);'/> </th>
  </tr>
  <tr>
  	<th>Text 3</th>
  	<th><input type="text" id="txt_3" onkeyup='saveValue(this);'/> </th>
  </tr>
  <tr>
  	<th>Text 4</th>
  	<th><input type="text" id="txt_4" onkeyup='saveValue(this);'/> </th>
  </tr>
  <tr>
  	<th>Text 5</th>
  	<th><input type="text" id="txt_5" onkeyup='saveValue(this);'/> </th>
  </tr>
</table> 
0 голосов
/ 18 февраля 2020

Html не является надежным. Вы можете использовать чистый код javascript для более чистого пути. Вот рабочий образец. Slackblitz https://stackblitz.com/edit/js-xycijp

function saveValue({ target }, index) {
  localStorage.setItem(target.id, target.value); // Every time user writing
  // OR
  localStorage.setItem("target.id"+index, target.value); // Every time user writing something, the localStorage's value will override .
}

//get the saved value function - return the value of "v" from localStorage.
function getSavedValue(v) {
  if (!localStorage.getItem(v)) {
    return ""; // You can change this to your defualt value.
  }
  return localStorage.getItem(v);
}
document.querySelectorAll(".textField").forEach((elm, index) => {
  elm.addEventListener("input", (e) => saveValue(e, index), false);
});

// Can ignore
window.saveValue = saveValue;
window.getSavedValue = getSavedValue;
<input class='textField' type="text" id="txt_1" /> 
<input class='textField' type="text" id="txt_2" /> 
0 голосов
/ 18 февраля 2020

Прежде всего, вам нужно передать прослушиватель событий в функцию, которую вы реализовали, поэтому я решил ее добавить события в файл js. Поэтому вместо этого:

<input type="text" id="txt_1" onkeyup='saveValue(this);'/> 

Вам необходимо добавить событие в js:

<input type="text" id="txt_1"/> 
<input type="text" id="txt_2"/> 

document.getElementById("txt_1").onkeyup = saveValue;
document.getElementById("txt_2").onkeyup = saveValue;

После этого вам необходимо получить доступ к идентификатору и значению из * 1008. * вот так:

function saveValue(e) {
  var id = e.target.id; // get the sender's id to save it .
  var val = e.target.value; // get the value.
  localStorage.setItem(id, val); // Every time user writing something, the localStorage's value will override .
}

Посмотрите на это codesandbox и посмотрите, поможет ли оно вам

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...