Home > Back-end >  XMLHttpRequest, AJAX, JSP, Load data into form
XMLHttpRequest, AJAX, JSP, Load data into form

Time:08-19

If the object contains more fields than what are referenced in the form, then it breaks, how can I prevent this (https://jsfiddle.net/a4v7p2xg/2/) the snippet below works.

var data = {
  "firstname": "David",
  "lastname": "Garcia"
};

$( document ).ready(function() {
Object.keys(data).forEach(key => document.querySelector(`input[data-name="${key}"]`).value = data[key]);
});
<!doctype html>
<html lang="en">

  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <!-- JS -->

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg OMhuP IlRH9sENBO0LRn5q 8nbTov4 1p" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj 3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <title></title>
    <style type="text/css">
      body {
        font-family: 'Open Sans', Arial, helvetica, sans-serif;
        color: #333333
      }

    </style>
  </head>


  <body style="" >
    <div >
      <div >
        <div >First Name</div>
        <div ><input name="firstname" data-name="firstname"  id="firstname" type="text" /></div>
      </div>
      <div >
        <div >Last Name</div>
        <div ><input name="lastname" data-name="lastname"  id="lastname" type="text" /></div>
      </div>
    </div>
  </body>

</html>

CodePudding user response:

  • First off, instead of using XMLHTTPRequest, you should be using the fetch api, built-in to JS. See this answer.
  • Secondly, you can set the value of the inputs after adding data-name attributes to each input which corresponds to the key of the value of the object you want to set its value to . Here's how I would do that:
function addToForm(data){
    Object.keys(data).forEach(key => document.querySelector(`[data-name="${key}"]`) == null ? 0 : document.querySelector(`[data-name="${key}"]`).value = data[key])
}
  • Related