Home > Enterprise >  html show search result below search bar dynamically and capture the result in variable
html show search result below search bar dynamically and capture the result in variable

Time:07-12

I am new to HTML and css and this is my first html code after a decade, I am trying to create a simple form with 2 basic requirement. I have a search field which runs a script which does a rest call with the value inserted in text box and return list of values(1 - 10). I want to show those values under my search box and also assign it to a variable and fetch it when submit is hit so that I can pass it to another rest call. For the below code, I commended out the rest call in script and added and dummy value. My end objective is to get all the values in the form, including the one returned from search and make a http call on submit button. How can I achieve this? I never did a frontend/html development so any references would be helpful.

<!DOCTYPE html>
<html style="font-size: 16px;" lang="en"><head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta charset="utf-8">
    <meta name="keywords" content="​ Simplified UI">
    <meta name="description" content="">
    <title>Home</title>
    <link rel="stylesheet" href="nicepage.css" media="screen">
    <link rel="stylesheet" href="Home.css" media="screen">
    <script  type="text/javascript" src="jquery.js" defer=""></script>
    <script  type="text/javascript" src="nicepage.js" defer=""></script>
    <meta name="generator" content="Nicepage 4.13.4, nicepage.com">
    <link id="u-theme-google-font" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:100,100i,300,300i,400,400i,500,500i,700,700i,900,900i|Open Sans:300,300i,400,400i,500,500i,600,600i,700,700i,800,800i">

    <script>
        // define the callAPI function that takes a first name and last name as parameters
        var callAPI = (title_name)=>{
            // instantiate a headers object
            var myHeaders = new Headers();
            // add content type header to object
            myHeaders.append("Content-Type", "application/json");
            // using built in JSON utility package turn object to string and store in a variable
            var raw = JSON.stringify({"title_name":title_name});
            // create a JSON object with parameters for API call and store in a variable
            var requestOptions = {
                method: 'POST',
                headers: myHeaders,
                body: raw,
                redirect: 'follow'
            };
            // make API call with parameters and use promises to get response
<!--            fetch("API-INVOKE-URL", requestOptions)-->
<!--            .then(response => response.text())-->
<!--            .then(result => alert(JSON.parse(result).body))-->
<!--            .catch(error => console.log('error', error));-->
           {"123456", "bob"}
        }
    </script>
    <meta name="theme-color" content="#478ac9">
    <meta property="og:title" content="Home">
    <meta property="og:type" content="website">
</head>
<body data-home-page="Home.html" data-home-page-title="Home" ><header  id="sec-70ca"><div >
    <div  data-animation-name="" data-animation-duration="0" data-animation-delay="0" data-animation-direction="">
        <div >
            <h2 >Simplified UI</h2>
            <div >
                <form action="#" method="POST"  name="form" style="padding: 23px;">
                    <div >
                        <label for="name-4c18" >name</label>
                        <input type="text" placeholder="ML Audience name" id="name-4c18" name="Name"  required="">
                    </div>
                    <div >
                        <label for="email-4c18" >Id</label>
                        <input type="text" placeholder="Enter email id" id="email-4c18" name="emailId"  required="required">
                    </div>
                    <div >
                        <label for="select-dc18" >Country</label>
                        <div >
                            <select id="select-dc18" name="Country"  required="required">
                                <option value="US">US</option>
                                <option value="PL">PL</option>
                                <option value="IN">IN</option>
                                <option value="KOR">KOR</option>
                                <option value="CH">CH</option>
                            </select>
                            <svg xmlns="http://www.w3.org/2000/svg" width="14" height="12" version="1" ><path fill="currentColor" d="M4 8L0 4h8z"></path></svg>
                        </div>
                    </div>
                    <div >
                        <label for="select-c14d" >Are you a first time visitor</label>
                        <div >
                            <select id="select-c14d" name="NewShowOrNot"  required="required">
                                <option value="Yes">Yes</option>
                                <option value="No">No</option>
                            </select>
                            <svg xmlns="http://www.w3.org/2000/svg" width="14" height="12" version="1" ><path fill="currentColor" d="M4 8L0 4h8z"></path></svg>
                        </div>
                    </div>
                    <div >
                        <label for="text-049f" > Title</label>
                        <input type="text" id="text-049f" name="ProgramTitle" >
                        <button type="button" onclick="callAPI(document.getElementsByName('ProgramTitle')[0].value)">search</button>
                    </div>
                    <div >
                        <a href="#" >Submit your request</a>
                        <input type="submit" value="submit" >
                    </div>
                    <div > Thank you! Your request has been sent. </div>
                    <div > Unable to send your request. Please fix errors then try again. </div>
                </form>
            </div>
        </div>
    </div>
    <div >
        <div ></div>

    </div>
</div></header>

<footer  id="sec-0cc5"><div >
    <p >Sample text. Click to select the Text Element.</p>
</div></footer>

</body></html>

enter image description here

CodePudding user response:

The question wasn't perfectly clear in some details..

Anyway I simplified your html a bit to make the solution more clear.

Then I focused on your logic to fetch results from your api on the click event of the search button, so that after the call returns, its result gets echoed in a dedicated html target (whose id is api_results located right under the search button).

I was confused on how that array was supposed to be, because in your question you say values from 1-10, while in your code you put a dummy array like ["123456", "bob"]. Since it was not relevant to the focus of the question, I left it as written on your code.

Such results array gets also saved as a JSON string in a dedicated new hidden input field (id: apiresults) that will be sent with the rest of the data when the form is submitted.

Plus, there's a listener for the submit event of the form that will be called on submit (if input data passed validation) and will fetch that array from the hidden field so that if you want to call a further api, you have that data.

This is the demo:

//on document ready
document.addEventListener('DOMContentLoaded',()=>{

  //add click event listener to search button
  document.getElementById('search').addEventListener('click', (event)=>{
    //fetch the title_name
    const title_name = document.getElementsByName('ProgramTitle')[0].value;
    //call the api
    const results = callAPI(title_name);
    //get the html element to show output
    const outputTarget = document.querySelector('.api_results');
    //reset its inner content
    outputTarget.innerHTML = "";
    //loop through each result item
    results.forEach((o,i)=>{
      //create a list item element and append it to the output
      const p = document.createElement('li');
      p.textContent = o;
      outputTarget.appendChild(p);
    });    
    //saves the api results as a json string in the hidden input field (id=apiresults)
    document.getElementById('apiresults').value = JSON.stringify(results);
  });

  //add submit event listener to form
  document.getElementById('form').addEventListener('submit', (event)=>{       
  
    //here you have the array returned from the search api call
    const encoded = document.getElementById('apiresults').value;
    const decoded = JSON.parse( encoded );    
    
    //here you are supposed to call your next api with that data?
  
    //this preventDefault is meant to stop the real submit because here it would break
    //just uncomment this in your real production code
    event.preventDefault();
    
    console.log(`form submitted - array data from api was (as json): ${encoded}`);
  });
});

// define the callAPI function that takes a first name and last name as parameters
const callAPI = (title_name)=>{            
    // instantiate a headers object
    const myHeaders = new Headers();
    // add content type header to object
    myHeaders.append("Content-Type", "application/json");
    // using built in JSON utility package turn object to string and store in a variable
    const raw = JSON.stringify({"title_name":title_name});
    // create a JSON object with parameters for API call and store in a variable
    const requestOptions = {
        method: 'POST',
        headers: myHeaders,
        body: raw,
        redirect: 'follow'
    };
    // make API call with parameters and use promises to get response
    /*
    fetch("API-INVOKE-URL", requestOptions)
      .then(response => response.text())
      .then(result => alert(JSON.parse(result).body))
      .catch(error => console.log('error', error));
    */
       
   return ["123456", "bob"];
}
html{
  font-size: 16px;
}

form{
  padding: 23px;
}

.formgroup{
  display: flex;
  margin-bottom: 1rem;
}

.formgroup label{
  width: 20%;
}

.api_results{
  border: dashed 3px gray;
  margin: 1rem 0 1rem 0;  
  padding: 1rem;
}

button, input[type=submit]{
  padding: 0.25rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1>Simplified Form</h1>

<form action="#" method="POST" name="form" id="form">

  <div >
    <label for="name-4c18">name</label>
    <input
      id="name-4c18" name="Name"
      type="text"
      placeholder="ML Audience name"                                
      required="">
  </div>

  <div >
    <label for="email-4c18">Id</label>
    <input
      id="email-4c18" name="emailId"
      type="text"
      placeholder="Enter email id"
      required="required">
  </div>

  <div >
    <label for="select-dc18">Country</label>
    <div>
        <select
          id="select-dc18" name="Country"
          required="required">
            <option value="US">US</option>
            <option value="PL">PL</option>
            <option value="IN">IN</option>
            <option value="KOR">KOR</option>
            <option value="CH">CH</option>
        </select>
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="14" height="12" version="1">
            <path fill="currentColor" d="M4 8L0 4h8z"></path>
        </svg>
    </div>
  </div>

  <div >
    <label for="select-c14d">Are you a first time visitor</label>
    <div>
        <select
          id="select-c14d" name="NewShowOrNot"
          required="required">
            <option value="Yes">Yes</option>
            <option value="No">No</option>
        </select>
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="14" height="12" version="1">
            <path fill="currentColor" d="M4 8L0 4h8z"></path>
        </svg>
    </div>
  </div>

  <div >
    <label for="text-049f">Title</label>
    <input id="text-049f" name="ProgramTitle" type="text">
    <button
      id="search"
      type="button"
      onclick="callAPI()">
      search
    </button>
  </div>

  <div >
  </div>
  <input type="hidden" id="apiresults" name="apiresults" value="">

  <div >    
    <input type="submit" value="submit">
  </div>

</form>

  • Related