简体   繁体   中英

Show items not in array after form submit

I have a dropdown menu which I am generating from an array like this(using fake data in this example for brevity)

    var city = document.getElementById("city");
    locarr = ["1", "2", "3", "4"];
    for(var i=0; i < locarr.length; i++) {
        var opt = locarr[i];
        var el = document.createElement("option");
        el.text = opt;
        el.value = opt;
        city.add(el);
    }

And that works fine, it populates the menu. However, when I submit the form and page reloads, I want to show the initial selected item and then all other items in the array excluding that one so I don't have a duplicate entry.

My oldInput.city value is coming from the controller which is the value that was posted upon form submission.

In its current state I have duplicate values once the form has been submitted.

<select class="chosen-select-no-single" name="city" id="city">
    <% if (!oldInput.city) { %>
    <option value="">Select City</option>
    <% } else { %>
    <option value="">Select City</option>
    <option value="<%= oldInput.city %>" selected>
        <%= oldInput.city %>
    </option>
    <% } %>
</select>

Just delete oldInput from the HTML. In the for clause you can do this :

for(var i=0; i < locarr.length; i++) {
    var opt = locarr[i];
    var el = document.createElement("option");
    el.text = opt;
    el.value = opt;
    var oldInpt="<%=oldInput%>";
    if (oldInpt!=null && opt ==oldInpt.city){
       el.selected = true;
    }
    city.add(el);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM