DEV Community

Bilal Ahmed
Bilal Ahmed

Posted on

How to show the retrieved values from local storage in javascript when the browser window of the form is duplicated?

I want to get the data in form fields when the browser window is duplicated. I am storing the data in local storage for the below form:

`<div class="col-sm-6">
                    <div class="form-group">
                        <label>CRU ID</label>
                        <select name="cru_agent_detail_id" class="form-control select2" id="user_list">
                            <option value="">Select CRU ID</option>
                            @foreach ($users as $user)
                                <option value="{{ $user->id }}">{{ $user->cru_id }}</option>
                            @endforeach
                        </select>
                    </div>
                </div>

                <div class="col-sm-6">
                    <label for="exampleInputEmail1">Agent Name</label>
                    <input type="text" class="form-control" name="name" id="agent_name" placeholder="Agent Name"
                        readonly>
                </div>`
Enter fullscreen mode Exit fullscreen mode

The form's CRU ID field is a select box which is populated from database and upon the selection of the menu the name of agent is shown in agent name field. I am storing the values of the above fields in local storage but cannot fetch them in the input fields when the browser window is duplicated. The code I did for it is:

`$(document).ready(function() {
        /* let id;
        id = localStorage.getItem('cru_id');
        console.log(id) */

        $('#user_list').change(function() {
            cru_id = $('#user_list').find(":selected").text();
            localStorage.setItem('cru_id', cru_id);
            get_cru_id = JSON.stringify(localStorage.getItem('cru_id'));
            console.log(get_cru_id);
            id = $(this).val();
            $.ajax({
                url: 'get-user-detail/' + id,
                type: 'get',
                dataType: 'json',
                success: function(response) {
                    let user = response.data
                    $("#agent_name").val(user.name);
                    agent_name = $("#agent_name").val();
                    localStorage.setItem('agent_name', $("#agent_name").val());
                    get_agent_name = JSON.stringify(localStorage.getItem('agent_name'));
                    console.log(get_agent_name);
                }
            })
        });
    });`
Enter fullscreen mode Exit fullscreen mode

The values are stored in local storage but are not retrieve when the browser window is duplicated.

Top comments (0)