skip to Main Content

I’ve a group of divs that I show after I click an option from a select. The data option is saved after reload to keep the option selected. That works correctly but the problem is onreload, I want to save the value div to show it but I don’t know how to do that: look:

This is my div group:

<center>
    <div>
        <div class="opc" id="cerDiv" style="display:none;">
            <div class="divTag" style="width: 350px;">
                <p>
                    <span class="spanrojo">|</span>
                    <span class="spangris">Certificaciones</span>
                    <span class="spanrojo">|</span>
                </p>
                <form method="post" onsubmit="return captchaValidar(this)" action="@Url.Action("Pdf", "Home")">
                    <label for="solicitud">Solicitud: </label>
                    <input type="text" id="solicitud" minlength="5" maxlength="7" name="solicitud" placeholder="Ingrese la solicitud..." required
                           title="Sólo letras y números. Cantidad mínima de caracteres: 5. Cantidad máxima de caracteres: 7"
                           onkeypress="return validarCertificadosYSolicitudes(event)" autofocus>
                    <input class="buscar" type="submit" id="btn" value="Buscar" />

                    @if (ViewBag.Alert != null)
                    {
                        <div class="alert">
                            <span class="closebtn">&times;</span>
                            <strong>Providus informa: </strong>
                            <p>@ViewBag.Alert</p>
                        </div>
                    }
                </form>
            </div>
        </div>

        <div class="opc" id="cuoDiv" style="display:none;" >
            <div style="width: 350px; ">
                <p>
                    <span class="spanrojo">|</span>
                    <span class="spangris">Cuotas</span>
                    <span class="spanrojo">|</span>
                </p>
            </div>
            <div class="divTag" style="width: 350px;">
                <form id="frmCU" method="post" action="@Url.Action("DetalleCuota", "Cuotas")">
                    <label for="titulo">Título: </label>
                    <input type="number" id="titulo" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" name="titulo" maxlength="6" placeholder="Ingrese su título..." required
                           title="Sólo letras y números. Cantidad mínima de caracteres: 4. Cantidad máxima de caracteres: 5"
                           onkeypress="return cuotasYTitulos(event)" autofocus>
                    <input class="buscar" type="submit" id="btn" value="Buscar" />
                    @if (ViewBag.Alert != null)
                    {
                        <div class="alert">
                            <span class="closebtn">&times;</span>
                            <strong>Providus informa: </strong>
                            <p id="textoAlerta">@ViewBag.Alert</p>
                        </div>
                    }
                </form>
            </div>
        </div>
    </div>
</center>

And this is my select options:

            <select id="sort-item" class="term">
                <option data-sort="0">Elija una opción</option>
                @foreach (var nivel in Model)
                {
                    if (nivel.nivel == 0 || nivel.nivel == 1 || nivel.nivel == 2 || nivel.nivel == 7)
                    {
                        <option value="cerDiv" data-sort="1">Certificados</option>
                        <option value="cuoDiv" data-sort="2">Cuotas</option>
                    } 
                }
            </select>

I have a this in my js file:

let selItems = JSON.parse(sessionStorage.getItem("SelItem")) || [];
var div_status = JSON.parse(sessionStorage.getItem("div_status")) || [];

$(function () {
    if (selItems) {
        selItems.forEach(obj => {
            const [k, v] = Object.entries(obj)[0]
            $("#" + k).val(v)
        })
    }
    $('.term').on("change", function () {
        selItems = $('.term').map(function () {
            return {
                [this.id]: this.value
            }
        }).get();
        console.log(selItems)
        sessionStorage.setItem("SelItem", JSON.stringify(selItems));
        saveDiv(this.value);
    });
});

function saveDiv(div) {
    div_status[div] = true;
    sessionStorage.setItem("div_status", JSON.stringify(div_status));
}

window.onload = function () {
    console.log(div_status);
    Object.values(div_status).forEach(function (div) {
        monstrarDiv(document.querySelector("#" + div))
    });
}

function mostrarDiv(target) {
    var opciones = document.getElementsByClassName('opc');
    var tagt = document.getElementById(target);
    var esVisible = tagt.style.display == 'block';

    //hide all
    for (var i = 0; i < opciones.length; i++) {
        opciones[i].style.display = 'none';
    }

    //toggle actual
    tagt.style.display = esVisible ? 'none' : 'block';

    return false;
}

I’m trying change the code but nothing works because I don’t know how to call the value to show a div.

2

Answers


  1. You need to restore the value by the same key you saved it.

    var data = sessionStorage.getItem("SelItem");
    
    // usually this value would be JSON
    var SelItem = JSON.parse(data)
    
    // do something with SelItem
    console.log(SelItem)
    

    Edit:

    So in order to save the visibility state of a few div id’s, you can store in sessionStorage an array or an object.

    // an object is preferable for easy access to keys
    var div_status = JSON.parse(sessionStorage.getItem("div_status")) || {};
    
    // onload
    Object.values(div_status).forEach(function(div) {
      monstrarDiv(document.querySelector("#" + div))
    })
    
    // on term change:
    function saveDiv(div) {
      div_status[div] = true
      sessionStorage.setItem("div_status", JSON.stringify(div_status));
    }
    
    function removeDiv(div) {
      delete div_status[div]
      sessionStorage.setItem("div_status", JSON.stringify(div_status));
    }
    Login or Signup to reply.
  2. I’m addressing your original question, as it was before the edit. selItems is an array and your issue is the problem illustrated here: https://jsfiddle.net/ax48kwpf/1/

    (cannot create a snippet here, as stackoverflow does not allow me to interact with sessionStorage for security reasons).

    let myArray = [1, 2, 3, 4];
    
    sessionStorage.setItem("myArray", myArray);
    
    console.log(sessionStorage.getItem("myArray"));
    

    enter image description here

    As we can see, I had a nice array and it has been converted into a String. So, I will need to decode from String into array. But how do I know it’s an array and how do I make sure that every array will be handled well? Well, the answer is simple: I use a controlled and generic approach to convert my variable into String:

    let myArray = [1, 2, 3, 4];
    
    sessionStorage.setItem("myArray", JSON.stringify(myArray));
    
    console.log(JSON.parse(sessionStorage.getItem("myArray")));
    

    https://jsfiddle.net/ax48kwpf/2/

    enter image description here

    We can see that it’s converted back into an array successfully. So, I convert my variable into String via JSON.stringify() and convert it back via JSON.parse(), of course, always passing the proper parameter.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search