2017-02-22 6 views
1

Я пытался создать форму, поэтому, когда пользователь заполняет форму, все хранится в хранилище браузера.Хранилище браузеров с помощью javascript

Однако, я в настоящее время интересно, как получить значения из элементов управления на странице и сохранить их в памяти сессии, используя одни и те же имена ключей в файле response.html ..

Выход Я в настоящее время получение не определено для каждого элемента.

"use strict"; 
 
var $ = function(id) { return document.getElementById(id); }; 
 

 
var saveReservation = function() { 
 
    
 
    
 
    // submit form 
 
    $("reservation_form").submit(); 
 
}; 
 

 
window.onload = function() { 
 
    $("submit_request").onclick = saveReservation; 
 
    $("arrival_date").focus(); 
 
};
body { 
 
    font-family: Arial, Helvetica, sans-serif; 
 
    background-color: white; 
 
    margin: 0 auto; 
 
    width: 600px; 
 
    border: 3px solid blue; 
 
    padding: 10px 20px; 
 
} 
 
fieldset { 
 
    margin-top: 1em; 
 
    margin-bottom: 1em; 
 
    padding: .5em; 
 
} 
 
legend { 
 
    color: blue; 
 
    font-weight: bold; 
 
    font-size: 85%; 
 
    margin-bottom: .5em; 
 
} 
 
label { 
 
    float: left; 
 
    width: 90px; 
 
} 
 
input, select { 
 
    margin-left: 1em; 
 
    margin-right: 1em; 
 
    margin-bottom: .5em; 
 
} 
 
input { 
 
    width: 14em; \t 
 
} 
 
input[type="radio"], input[type="checkbox"] { 
 
    width: 1em; 
 
    padding-left: 0; 
 
    margin-right: 0.5em; 
 
}
<!DOCTYPE html> 
 
<html> 
 
<head> 
 
    <title>Reservation request</title> 
 
    <link rel="stylesheet" href="reservation.css"> 
 
    <script src="reservation.js"></script> 
 
</head> 
 
\t 
 
<body> 
 
    <main> 
 
\t <h1>Reservation Request</h1> 
 
\t <form action="response.html" method="get" 
 
    \t name="reservation_form" id="reservation_form"> 
 
      <fieldset> 
 
     \t <legend>General Information</legend> 
 
     \t <label for="arrival_date">Arrival date:</label> 
 
     \t <input type="text" name="arrival_date" id="arrival_date"><br> 
 
     \t <label for="nights">Nights:</label> 
 
     \t <input type="text" name="nights" id="nights"><br> 
 
     \t <label>Adults:</label> 
 
     \t <select name="adults" id="adults"> 
 
        <option value="1">1</option> 
 
        <option value="2">2</option> 
 
        <option value="3">3</option> 
 
        <option value="4">4</option>   \t \t   \t \t   \t \t 
 
     \t </select><br> 
 
     \t <label>Children:</label> 
 
     \t <select name="children" id="children"> 
 
        <option value="0">0</option> 
 
        <option value="1">1</option> 
 
        <option value="2">2</option> 
 
        <option value="3">3</option> 
 
        <option value="4">4</option>   \t \t   \t \t   \t \t 
 
     \t </select><br>   \t 
 
      </fieldset> 
 
      <fieldset> 
 
     \t <legend>Preferences</legend> 
 
     \t <label>Room type:</label> 
 
\t \t <input type="radio" name="room" id="standard" value="standard" checked>Standard \t   \t 
 
\t \t <input type="radio" name="room" id="business" value="business">Business 
 
\t \t <input type="radio" name="room" id="suite" value="suite">Suite<br> 
 
       
 
     \t <label>Bed type:</label> 
 
\t \t <input type="radio" name="bed" id="king" value="king" checked>King 
 
\t \t <input type="radio" name="bed" id="double" value="double">Double Double<br> 
 
\t \t <input type="checkbox" name="smoking" id="smoking" value="smoking">Smoking<br> 
 
      </fieldset> \t \t 
 
      <fieldset> 
 
    \t \t <legend>Contact Information</legend> 
 
    \t \t <label for="name">Name:</label> 
 
\t \t <input type="text" name="name" id="name"><br> 
 
     \t <label for="email">Email:</label> 
 
     \t <input type="text" name="email" id="email"><br> 
 
\t \t <label for="phone">Phone:</label> 
 
\t \t <input type="text" name="phone" id="phone"><br> 
 
      </fieldset> 
 

 
      <input type="button" id="submit_request" value="Submit Reservation"><br> 
 
\t </form> 
 
    </main> 
 
</body> 
 
</html>

<!DOCTYPE html> 
 
<!--response--> 
 
<html> 
 
<head> 
 
    <title>Reservation Request</title> \t 
 
    <link rel="stylesheet" href="reservation.css"> 
 
</head> 
 

 
<body> 
 
    <main> 
 
     <script> 
 
      document.write("<h3>The following reservation has been submitted</h3>"); 
 
      document.write("Name: ", sessionStorage.name, "<br>"); 
 
      document.write("Phone: ", sessionStorage.phone, "<br>"); 
 
      document.write("Email: ", sessionStorage.email, "<br>"); 
 
      document.write("Arrival Date: ", sessionStorage.arrivalDate, "<br>"); 
 
      document.write("Nights: ", sessionStorage.nights, "<br>"); 
 
      document.write("Adults: ", sessionStorage.adults, "<br>"); 
 
      document.write("Children: ", sessionStorage.children, "<br>"); 
 
      document.write("Room Type: ", sessionStorage.roomType, "<br>"); 
 
      document.write("Bed Type: ", sessionStorage.bedType, "<br>"); 
 
      document.write("Smoking: ", sessionStorage.smoking, "<br><br>"); 
 
     </script> 
 
    </main> 
 
</body> 
 
</html>

+0

Где находится 'sessionStorage'? – guest271314

+0

@ guest271314 Что вы имеете в виду? – steven

+0

Где вы изначально устанавливали 'sessionStorage' на' javascript'? – guest271314

ответ

0

Синтаксис кажется неправильным. Попробуйте это вместо

Для сохранения данных/инициализации sessionStorage:

// Save data to sessionStorage 
sessionStorage.setItem('key', 'value'); 

Для извлечения сохраненного значения из sessionStorage

// Get saved data from sessionStorage 
sessionStorage.getItem('key'); 
+0

Примечание. Точечная нотация может получить набор свойств 'sessionStorage'. – guest271314

+0

это инициализирует хранение сессии? @ guest271314 – steven

+0

@steven Да. Вам нужно установить элементы в 'sessionStorage', если вы хотите получать элементы из' sessionStorage'. – guest271314

0

По моим сведениям, что вы ищете, чтобы принять пользователь данных и отобразить их в другом HTML

Вы можете сделать это, создав JSON с данными формы и сохраните его в локальном хранилище. Вы можете вернуть эту форму и заполнить ее на другой странице. Вы можете использовать атрибуты readonly, если хотите запретить редактирование. (Или просто сделать поля отображаются в этикеточной/SPAN/пункт и т.д ..)

код выглядит следующим образом:

registration.html

HTML

<body> 
    <main> 
    <h1>Reservation Request</h1> 
    <form action="response.html" method="post" 
     name="form" id="form"> 
      <fieldset> 
      <legend>General Information</legend> 
      <label for="arrival_date">Arrival date:</label> 
      <input type="text" name="arrival_date" id="arrival_date"><br> 
      <label for="nights">Nights:</label> 
      <input type="text" name="nights" id="nights"><br> 
      <label>Adults:</label> 
      <select name="adults" id="adults"> 
        <option value="1">1</option> 
        <option value="2">2</option> 
        <option value="3">3</option> 
        <option value="4">4</option>             
      </select><br> 
      <label>Children:</label> 
      <select name="children" id="children"> 
        <option value="0">0</option> 
        <option value="1">1</option> 
        <option value="2">2</option> 
        <option value="3">3</option> 
        <option value="4">4</option>             
      </select><br>   
      </fieldset> 
      <fieldset> 
      <legend>Preferences</legend> 
      <label>Room type:</label> 
     <input type="radio" name="room" id="standard" value="standard" checked>Standard    
     <input type="radio" name="room" id="business" value="business">Business 
     <input type="radio" name="room" id="suite" value="suite">Suite<br> 

      <label>Bed type:</label> 
     <input type="radio" name="bed" id="king" value="king" checked>King 
     <input type="radio" name="bed" id="double" value="double">Double Double<br> 
     <input type="checkbox" name="smoking" id="smoking" value="smoking">Smoking<br> 
      </fieldset>  
      <fieldset> 
      <legend>Contact Information</legend> 
      <label for="name">Name:</label> 
     <input type="text" name="name" id="name"><br> 
      <label for="email">Email:</label> 
      <input type="text" name="email" id="email"><br> 
     <label for="phone">Phone:</label> 
     <input type="text" name="phone" id="phone"><br> 
      </fieldset> 

      <input type="submit" value="SubmitReservation"><br> 
    </form> 
    </main> 
</body> 

jQuery (3.1.1)

Вы можете использовать это в теге сценария в вашем HTML

$.fn.serializeObject = function() 
{ 
    var jsonObj = {}; 
    var jsonArr = this.serializeArray(); 
    $.each(jsonArr, function() { 
     if (jsonObj[this.name] !== undefined) { 
      if (!jsonObj[this.name].push) { 
       jsonObj[this.name] = [jsonObj[this.name]]; 
      } 
      jsonObj[this.name].push(this.value || "NA"); 
     } else { 
      jsonObj[this.name] = this.value || "NA"; 
     } 
    }); 
    return jsonObj; 
} 
$(function() { 
    $('form').submit(function() { 
    console.log(jsonData); 
    var jsonData=$('form').serializeObject(); 
// Put the object into storage 
localStorage.setItem('jsonData', JSON.stringify(jsonData)); 
existingEntries.push(jsonData); 
     return false; 
    }); 
    }); 

response.html

HTML

<body> 
    <main> 
    <h1>Reservation Request</h1> 
    <form action="response.html" method="post" 
     name="form" id="form"> 
      <fieldset> 
      <legend>General Information</legend> 
      <label for="arrival_date">Arrival date:</label> 
      <input type="text" name="arrival_date" id="arrival_date"><br> 
      <label for="nights">Nights:</label> 
      <input type="text" name="nights" id="nights"><br> 
      <label>Adults:</label> 
      <select name="adults" id="adults"> 
        <option value="1">1</option> 
        <option value="2">2</option> 
        <option value="3">3</option> 
        <option value="4">4</option>             
      </select><br> 
      <label>Children:</label> 
      <select name="children" id="children"> 
        <option value="0">0</option> 
        <option value="1">1</option> 
        <option value="2">2</option> 
        <option value="3">3</option> 
        <option value="4">4</option>             
      </select><br>   
      </fieldset> 
      <fieldset> 
      <legend>Preferences</legend> 
      <label>Room type:</label> 
     <input type="radio" name="room" id="standard" value="standard" checked>Standard    
     <input type="radio" name="room" id="business" value="business">Business 
     <input type="radio" name="room" id="suite" value="suite">Suite<br> 

      <label>Bed type:</label> 
     <input type="radio" name="bed" id="king" value="king" checked>King 
     <input type="radio" name="bed" id="double" value="double">Double Double<br> 
     <input type="checkbox" name="smoking" id="smoking" value="smoking">Smoking<br> 
      </fieldset>  
      <fieldset> 
      <legend>Contact Information</legend> 
      <label for="name">Name:</label> 
     <input type="text" name="name" id="name"><br> 
      <label for="email">Email:</label> 
      <input type="text" name="email" id="email"><br> 
     <label for="phone">Phone:</label> 
     <input type="text" name="phone" id="phone"><br> 
      </fieldset> 

      <input type="submit" value="SubmitReservation"><br> 
    </form> 
    </main> 
</body> 

JQuery (3.1.1)

Вы можете использовать это в теге сценария в вашем HTML

$(function() { 
var jsonString = JSON.parse(localStorage.getItem("jsonData")); 
$.each(jsonString, function(key, value) { 
     var ctrl = $('[name='+key+']'); 
     switch(ctrl.prop("type")) { 
      case "radio": case "checkbox": 
       ctrl.each(function() { 
        if($(this).prop('value') == value) $(this).prop("checked",value); 
       }); 
       break; 
       case "text": 
       ctrl.val(value); 

       break; 
      default: 
       ctrl.val(value); 
     } 
    }); 
}); 

ПРИМЕЧАНИЕ: CSS остается такой же, как у вас обоих файлов (предварительный заказ.CSS)

Вы можете посмотреть на следующем jsFiddle выполнить вышеуказанные коды:

CLICK HERE FOR registration page

CLICK HERE FOR response page

Вы можете проверить содержимое локального хранилища в Google chrome путем нажатия F12 -> Application tab -> local storage on the left side navBar

Смежные вопросы