1

I am trying to save some html structure with the values selected and all.

<select id="select-options-beneficiaries" aria-describedby="selector2">
    <option selected value="Jhon Doe">Jhon Doe</option>
    <option value="Jane Doe">Jane Doe</option>
    <option value="New Beneficiary">New Beneficiary</option>
</select>

I am saving this piece of block like this:

var htmlBeneficiariesData = document.getElementById('select-options-beneficiaries').innerHTML;
sessionStorage.setItem('htmlBeneficiariesData', htmlBeneficiariesData);

Now when I try to retrieve the information and prepend it, it doesn't save up the selected value or the values saved in the input.

var sessionBeneficiariesData = sessionStorage.getItem('htmlBeneficiariesData');
$('#plan-beneficiaries-container').prepend(sessionBeneficiariesData);

Is there a way to save the HTML structure including selected values and inputs?

Why do I need to do this? Well, for instance the html is created using JS, so when a button is clicked it creates new HTML like the one above.

So every time you click on the button, a new select and input will be generated. After you finish filling out all the information from the fields that were generated by JS, you go to the next page, and then when you try to go back, the information (HTML and values) are lost (because it was generated by clicking the button) and why this was done this way? Why I cannot change it? because the UX team design it like this.

Monica
  • 1,524
  • 4
  • 27
  • 44
  • 1
    The `value`, `checked`, and `select` *properties* are what hold the actual value of an input/select. They are **not** reflected in the HTML *attributes*. Consider checking out: [What is the difference between properties and attributes in HTML?](https://stackoverflow.com/questions/6003819/what-is-the-difference-between-properties-and-attributes-in-html). I realize this doesn't answer your question, however it does highlight a major caveat of your approach. An alternative would be to loop through all your inputs and selects and update the attributes before saving the HTML. – Tyler Roper Oct 11 '19 at 18:06
  • 3
    Why do you need to save the whole HTML, and not just the selected value? Isn't your HTML known anyway (where did it initially come from?) – trincot Oct 11 '19 at 18:10
  • I think @trincot is right. You might want to change your approach a bit and just store the current selected value, whether it's in your app cache or session storage. – Jay Kariesch Oct 11 '19 at 18:21
  • @trincot Well I think the backend is in .NET and I am just the frontend developer offshore helping, When the user go back from the next page to this one, the information should be persistent to what was before. And since all of the information (HTML) was generated by js (because that was how the UX team wanted it), when they go back, the page is empty, so I am trying to save everything in a session, when they go back, they can retrieve the same information – Monica Oct 11 '19 at 18:23
  • 2
    That really feels wrong. So you are planning to inject your own JS, sitting next to some other disfunctional JS (because apparently it doesn't run when the user goes back), to reproduce what the other JS already is capable of (except for the input values)? Unless you have more detailed information that proves otherwise, this looks like a very bad design choice. – trincot Oct 11 '19 at 18:36
  • 1
    I read how the content is generated by a click on a button. You can analyse what that click actually does. Does it perform an Ajax call to retrieve the HTML from the server application? If so, you should do the same (Ajax call to retrieve the HTML), ... – trincot Oct 11 '19 at 18:39
  • @trincot unfortunately, there is no ajax call, HTML is generated through JS. I know doesn't sound great. But am I going to fight with the backend team? am I going to fight with the UX team for coming up with this? NO, I can't I am just here to solve this problem, and as ugly as it looks I have to find a way to fix it. I DID NOT design the UX. In a perfect world this would not be handle this way, I know. – Monica Oct 11 '19 at 18:43
  • 1
    But.... the Javascript code is there. You should use it. Call the functions it calls to build the HTML, ... If that code is not clear, you are entitled to ask for its documentation. That is not fighting, that is collaborating. – trincot Oct 11 '19 at 18:49
  • @trincot I guess I'll create 2 sessions one that saves the HTML structure and another that saves the data. then when going back load the html from the session Storage and then right after load the data from the other sessionStorage. I cannot see it any other way. I thought that maybe there was something out there that I could use to save the data and the html structure all together. But if not, then I'll proceed this way. Thanks! – Monica Oct 11 '19 at 19:06
  • @Monica have you see my answer? – A. Meshu Oct 11 '19 at 22:42

2 Answers2

1

I do not know what you have for problems ;) For sure that can be done ! It is JAVASCRIPT !!! Everything is possible - even maybe not sense full all the time. This here will do the trick. But for sure that is not elegant nor advised. just for the fun.

            <!DOCTYPE HTML>
            <html>
                <head>
                    <title>Untitled</title>
                </head>
                <body>
                    <select id="select-options-beneficiaries" aria-describedby="selector2"  onchange="silly();">
                        <option selected value="Jhon Doe">Jhon Doe</option>
                        <option value="Jane Doe">Jane Doe</option>
                        <option value="New Beneficiary">New Beneficiary</option>
                    </select>
                   <br><br>
                    <textarea id="x" style="width:800px; height:200px;"></textarea>

                    <script>
                        function silly() {
                            value = document.getElementById("select-options-beneficiaries").value;
                            console.log(value);
                            options = document.getElementById("select-options-beneficiaries").childNodes;
                            var HTML = '<select id="select-options-beneficiaries" aria-describedby="selector2">\n';

                            for (i = 0; i < options.length; i++) {
                                var o = options[i].outerHTML;
                                if (o) {
                                    var test = 'value="' + value + '"';
                                    var x = o.indexOf(test);
                                    o = o.replace(' selected=""', '');
                                    if (o.indexOf(test) > -1) {

                                        o = o.replace('value="', 'selected ' + 'value="');
                                    }

                                    HTML = HTML + o + "\n"
                                }

                            }
                            HTML = HTML + "</select>"
                            sessionStorage.setItem('htmlBeneficiariesData', HTML);
                             document.getElementById("x").value=sessionStorage.getItem('htmlBeneficiariesData');

                        }
                    silly();  
                    </script>

                </body>
            </html>

if you want to use your code this here might work also after your html add apiece script first before you save get the selection

 value = document.getElementById("select-options-beneficiaries").value;

now add as string to your innerHTML this

 '<script>document.getElementById("select-options-beneficiaries").value="'+value+'";</script>\n" 

You first will pump now the html with the wrong settings first and correct it afterwards by this piece of code.

The normal way would just store all the form values and recreate all the form values by the saved datas. Usually stored as json object and later on applied by javascript.

This here will put your whole form into a URL Object for example. I use it for POST requests to transmit form datas. With decodeURIComponent you will get the values back and can apply all of them to your form. Or change the decodeURIComponent part to your needs.

function serialize(form) {
                if (!form || form.nodeName !== "FORM") {
                    return;
                }
                var i, j, q = [];
                for (i = form.elements.length - 1; i >= 0; i = i - 1) {
                    if (form.elements[i].name === "") {
                        continue;
                    }
                    switch (form.elements[i].nodeName) {
                    case 'INPUT':
                        switch (form.elements[i].type) {
                        case 'text':
                        case 'tel':
                        case 'email':
                        case 'hidden':
                        case 'password':
                        case 'button':
                        case 'reset':
                        case 'submit':
                            q.push(form.elements[i].name + "=" + 
     encodeURIComponent(form.elements[i].value));
                            break;
                        case 'checkbox':
                        case 'radio':
                            if (form.elements[i].checked) {
                                q.push(form.elements[i].name + "=" + 
   encodeURIComponent(form.elements[i].value));
                            }
                            break;
                        }
                        break;
                    case 'file':
                        break;
                    case 'TEXTAREA':
                        q.push(form.elements[i].name + "=" + 
     encodeURIComponent(form.elements[i].value));
                        break;
                    case 'SELECT':
                        switch (form.elements[i].type) {
                        case 'select-one':
                            q.push(form.elements[i].name + "=" + 
       encodeURIComponent(form.elements[i].value));
                            break;
                        case 'select-multiple':
                            for (j = form.elements[i].options.length - 1; j >= 
       0; j = j - 1) {
                                if (form.elements[i].options[j].selected) {
                                    q.push(form.elements[i].name + "=" + 
       encodeURIComponent(form.elements[i].options[j].value));
                                }
                            }
                            break;
                        }
                        break;
                    case 'BUTTON':
                        switch (form.elements[i].type) {
                        case 'reset':
                        case 'submit':
                        case 'button':
                            q.push(form.elements[i].name + "=" + 
     encodeURIComponent(form.elements[i].value));
                            break;
                        }
                        break;
                    }
                }
                return q.join("&");
            }

Have fun :)

Thomas Ludewig
  • 696
  • 9
  • 17
  • Your solution worked. It was the most tedious coding ever. But it works. – Monica Oct 16 '19 at 22:31
  • 1
    Well, as said, just for the fun :) Sometimes i like to solve such riddles or quests. *laught* But please find some other way for the production release. Otherhile i will brat in hell for decades ;) Have a great day ! – Thomas Ludewig Oct 18 '19 at 08:53
0

I completely agree with @trincot comments, but i can understand your situation. If i understand your issue i guess this is what you are looking for:

var htmlBeneficiariesData = document.getElementById('select-options-beneficiaries').innerHTML;
var htmlBeneficiariesDataSelected = document.getElementById('select-options-beneficiaries').selectedIndex; // get selected index
sessionStorage.setItem('htmlBeneficiariesData', htmlBeneficiariesData);
sessionStorage.setItem('htmlBeneficiariesDataSelected', htmlBeneficiariesDataSelected); // store selected index

var sessionBeneficiariesData = sessionStorage.getItem('htmlBeneficiariesData');
var sessionBeneficiariesDataSelected = sessionStorage.getItem('htmlBeneficiariesDataSelected'); // get selected index that was stored
document.querySelector('#plan-beneficiaries-container').innerHTML = sessionBeneficiariesData;
document.querySelector('#plan-beneficiaries-container').selectedIndex = sessionBeneficiariesDataSelected; // mark the selected index on the generated select
<p>Original</p>
<select id="select-options-beneficiaries" aria-describedby="selector2">
    <option selected value="Jhon Doe">Jhon Doe</option>
    <option value="Jane Doe">Jane Doe</option>
    <option value="New Beneficiary">New Beneficiary</option>
</select>
<hr />
<p>Generated</p>
<select id="plan-beneficiaries-container"></select>

Note: for security reasons this won't work with the snippet so you have to test it yourself.

A. Meshu
  • 4,053
  • 2
  • 20
  • 34