Как правильно заполнить форму с помощью JS без потери данных?

223
14 июня 2018, 17:30

Как правильно заполнить форму при помощи JS и залить форму с данными в БД? Надо при соответствующим выборе выпадающего списка автоматически заполнить одно из текстовых полей. Сделал это так:

var select, value, text;
function change() {
    select = document.getElementById("MySelect");
    value = select.options[select.selectedIndex].value;
    console.log(value);
    if(value == "Existing Business"){
        document.getElementById("name").setAttribute('disabled', 'disabled');
        document.getElementById("name").value = "C1";
        document.getElementById("name").text = "C1";
        console.log(document.getElementById("name").text);
    }else if(value == "New Business"){
        document.getElementById("name").setAttribute('disabled', 'disabled');
        document.getElementById("name").value = "H1";
        document.getElementById("name").text = "Н1";
    }else{
        document.getElementById("name").removeAttribute('disabled');
        document.getElementById("name").value = "";
    }
}

На странице все отображается, но в БД ничего не попадает. Как сделать, что бы работало? Заранее спасибо.

Answer 1

Клиентская часть, может выглядеть так:

var select, value, text; 
 
function change() { 
  select = document.getElementById("MySelect"); 
  value = select.options[select.selectedIndex].value; 
  console.log(value); 
  if (value == "Existing Business") { 
    document.getElementById("name").setAttribute('disabled', 'disabled'); 
    document.getElementById("name").value = "C1"; 
    document.getElementById("name").text = "C1"; 
    console.log(document.getElementById("name").text); 
  } else if (value == "New Business") { 
    document.getElementById("name").setAttribute('disabled', 'disabled'); 
    document.getElementById("name").value = "H1"; 
    document.getElementById("name").text = "Н1"; 
  } else { 
    document.getElementById("name").removeAttribute('disabled'); 
    document.getElementById("name").value = ""; 
  } 
} 
 
function send(e) { 
  e.preventDefault(); 
  var form = document.getElementById('mainForm').elements; 
  //---------------------------------------------------------------- 
  // Form serialization by NAME --> element must have a name attribute 
  var data = Object.values(form).reduce((obj, field) => { 
    // Will not send undefined or empty name attribute 
    if (!(typeof field.name === "undefined" || typeof field.value === "undefined" || field.name.length === 0)) 
      obj[field.name] = field.value; 
    return obj 
  }, {}); 
  //---------------------------------------------------------------- 
 
  //---------------------------------------------------------------- 
  // Send data to Server  
  const url = 'https://jsonplaceholder.typicode.com/posts'; // Replace this with your URL 
  //---------------------------------------------------------------- 
  // jQuery version 
  $.ajax({ 
      method: "POST", 
      url: url, 
      data: { 
        data: JSON.stringify(data) 
      } 
    }) 
    .done(function(msg) { 
      console.log("Data Saved: ", msg); 
    }); 
 
  //---------------------------------------------------------------- 
  // No jQuery ----------------------------------------------------- 
  //---------------------------------------------------------------- 
  /** 
    dbParam = JSON.stringify(data); 
    xmlhttp = new XMLHttpRequest(); 
    xmlhttp.onreadystatechange = function() { 
      if (this.readyState == 4 && this.status == 200) { 
        var txt = ''; 
        myObj = JSON.parse(this.responseText); 
        for (x in myObj) { 
          txt += myObj[x].id + "<br>"; 
        } 
         document.getElementById("demo").innerHTML = txt; 
      } 
    }; 
    xmlhttp.open("POST", url, true); 
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    xmlhttp.send("data=" + dbParam); 
    **/ 
  //---------------------------------------------------------------- 
 
  return false; 
}
<!-------- Libraries --------> 
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" /> 
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<!-------- Libraries --------> 
<form onsubmit="return send(event); " id="mainForm"> 
 
  <div class="form-group"> 
 
    <label for="sel1">Select list (select one):</label> 
    <select name="code" class="form-control" id="MySelect" onchange="change()"> 
      <option value="Other">Other</option> 
      <option value="Existing Business">Existing Business</option> 
      <option value="New Business">New Business</option> 
    </select> 
  </div> 
 
  <div class="form-group"> 
    <label for="name">Name:</label> 
    <input type="text" name="data" class="form-control" id="name" /> 
  </div> 
 
  <button class="btn btn-default">Submit</button> 
 
</form> 
<div id="demo"></div>

P.S. Открывать на весь экран.

Серверная часть принимает JSON и вносит в БД.

// Подключение к БД до этих команд
// Выбор таблиц и т.д.
$data = json_decode($_POST['data'], true);
$statement->execute($data);

Пример серверной части

READ ALSO
Передача данных в post-запросе средствами cURL

Передача данных в post-запросе средствами cURL

Есть скрипт, который получает определенный файл и сохраняет его на диск с помощью связки file_put_contents и file_get_contentsЗатем запускается второй скрипт,...

197
создание галереи php/js

создание галереи php/js

Доброго всем времени сутокВопрос: мне нужно научиться создавать галереи картинок, т

193
CRON не может записать данные в БД

CRON не может записать данные в БД

Переношу парсер с одного VDS на другой и столкнулся с проблемойНа прошлом ресурсе все работало как часы, а сейчас есть проблема с записью полей...

209