简体   繁体   中英

Use javascript variable in html option tag

I found few posts related to my question but none of them seems to be apt for my case. I have a JSP page in which at a particular point I need to retrieve the options selected in a chosen select dropdown for which the javascript code is as below:

<script type="text/javascript">
        var arr = [];
        var listItems = $("#brand-id li span");
        listItems.each(function(idx, span) {
        var brand = $(span).html();
        arr.push(brand.toString());
        });
</script>

Now I need to send the values saved in arr to the server. For this the option tag is used. Code is as below:

<option selected="selected" value="<%=arr[i]%>"><%=arr[i]%></option>

My Compiled HTML code:

<div class="form-group">
    <label class="col-sm-3 control-label no-padding-right" for="form-field-1">Brand:</label>
    <div id="brand-id" class="col-sm-9">
        <select id="brand-select-id" data-placeholder="Select Brand" name="brand" multiple="" class="chosen-select" style="display: none;">
                        <option selected="selected" value="A">A</option>
                        <option selected="selected" value="B">B</option>
                        <option selected="selected" value="C">C</option>
                        <option value="D">D</option>
                        <option value="E">E</option>
        </select>
        <div class="chosen-container chosen-container-multi" style="width: 83%;" title="" id="brand_select_id_chosen">
            <ul class="chosen-choices">
                <li class="search-choice"><span>C</span><a class="search-choice-close" data-option-array-index="2"></a></li>
                <li class="search-choice"><span>A</span><a class="search-choice-close" data-option-array-index="0"></a></li>
                <li class="search-choice"><span>B</span><a class="search-choice-close" data-option-array-index="1"></a></li>
                <li class="search-field"><input type="text" value="Select Brand" class="" autocomplete="off" style="width: 25px;"></li>
            </ul>
            <div class="chosen-drop">
                <ul class="chosen-results">
                    <li class="result-selected" style="" data-option-array-index="0">A</li>
                    <li class="result-selected" style="" data-option-array-index="1">B</li>
                    <li class="result-selected" style="" data-option-array-index="2">C</li>
                    <li class="active-result" style="" data-option-array-index="3">D</li>
                    <li class="active-result" style="" data-option-array-index="4">E</li>
                </ul>
            </div>
        </div>
    </div>
</div>

My confusion is how do I use arr[i] in the option tag and is it even possible. If not, how can I do the same task in some other way. Thanks.

JSP file:

<div class="form-group">
    <label class="col-sm-3 control-label no-padding-right" for="form-field-1">Brand:</label>
    <div class="col-sm-9">
        <select data-placeholder="Select Brand" name="brand" multiple class="chosen-select col-xs-10 col-sm-10">
            <%
            // user.get("brand") gets the already selected brands by the user
            // masterRecords.get("brandslist") gets the complete list of brands from LDAP whether selected or not selected
            String brands="";
            if(user.get("brand")!=null && !user.get("brand").isEmpty())
                brands =user.get("brand").toLowerCase(); 
            if(masterRecords.get("brandslist")!=null && masterRecords.get("brandslist").length > 0){
            for(String brand:masterRecords.get("brandslist")){
                if(brands.contains(brand.toLowerCase().trim())){%>
            <option selected="selected" value="<%=brand.trim().toLowerCase()%>"><%=brand.trim()%></option>
                <%}else{%>
            <option value="<%=brand.trim().toLowerCase()%>"><%=brand.trim()%></option>
                <%} 
            } 
            }%>
        </select>
    </div>
</div>

In the same JSP file I have added the JS code as below:

<script type="text/javascript">
    var select = "";
    var arr = [];
    var listItems = $("#brand-id li span");
    listItems.each(function(idx, span) {
      var brand = $(span).html();

      arr.push(brand.toString());

    });
    //arr having values
    console.log(arr);


    select = ' <select id="brand-select-id" data-placeholder="Select Brand" name="brand" multiple="" class="chosen-select" style="">';
    for (var j = 0; j < arr.length; j++) {
      //appending options in selectbox
      select += '<option  selected="selected"value="' + arr[j] + '">' + arr[j] + '</option>';

    }
    select += '</select>';
    //append select to div 
    $(select).appendTo('.select');
</script>

JSP file updated with your code:

<div class="form-group">
    <label class="col-sm-3 control-label no-padding-right" for="form-field-1">Brand:</label>
    <div id="brand-id"  class="col-sm-9">
            <%
            // user.get("brand") gets the already selected brands by the user
            // masterRecords.get("brandslist") gets the complete list of brands from LDAP whether selected or not selected
            String brands="";
            if(user.get("brand")!=null && !user.get("brand").isEmpty())
                brands =user.get("brand").toLowerCase(); 
            if(masterRecords.get("brandslist")!=null && masterRecords.get("brandslist").length > 0){
            for(String brand:masterRecords.get("brandslist")){
                if(brands.contains(brand.toLowerCase().trim())){%>
            <div class="select"></div>
                <%}
                //else part left for now
            } 
            }%>
        </select>
    </div>
</div>

EDIT 1: The complete code from JSP file has been added. I was playing with the code generated by the 'chosen' plugin to get the custom sorting done.

You can append value of array to your options using for-loop and then use appendTo method of jquery to put that options inside <div id="select"></div> .Working example :

 var select = ""; var arr = []; var listItems = $("#brand-id li span"); listItems.each(function(idx, span) { var brand = $(span).html(); arr.push(brand.toString()); }); //arr having values console.log(arr); select = ' <select id="brand-select-id" data-placeholder="Select Brand" name="brand" multiple="" class="chosen-select" style="">'; for (var j = 0; j < arr.length; j++) { //appending options in selectbox select += '<option selected="selected"value="' + arr[j] + '">' + arr[j] + '</option>'; } select += '</select>'; //append select to div $(select).appendTo('#select');
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="form-group"> <label class="col-sm-3 control-label no-padding-right" for="form-field-1">Brand:</label> <div id="brand-id" class="col-sm-9"> <!--inside this div option will display--> <div id="select"></div> <div class="chosen-container chosen-container-multi" style="width: 83%;" title="" id="brand_select_id_chosen"> <ul class="chosen-choices"> <li class="search-choice"><span>C</span> <a class="search-choice-close" data-option-array-index="2"></a> </li> <li class="search-choice"><span>A</span> <a class="search-choice-close" data-option-array-index="0"></a> </li> <li class="search-choice"><span>B</span> <a class="search-choice-close" data-option-array-index="1"></a> </li> <li class="search-field"><input type="text" value="Select Brand" class="" autocomplete="off" style="width: 25px;"></li> </ul> </div> </div> </div>


Update 1 :

As i have already said in comment that you need to make some function so that it be called whenever options are selected or deselected from the chosen select-box.In below code i have used change event to check if any change occur in select box then call function to do required update.Working code:

 $('select.chosen-select').chosen(); //call function when page load update_values(); //whenever changes occur on select-box ie: if item is removed or added this will be called $(document).on('change', 'select.chosen-select', function(obj, result) { //calling function update_values(); }); function update_values() { var select = ""; var arr = []; var listItems = ""; //this will refresh values in chosen-select $('select.chosen-select').trigger("chosen:updated"); listItems = $("#brand-id li span"); listItems.each(function(idx, span) { var brand = $(span).html(); //adding values in array arr.push(brand.toString()); }); select = ' <select id="brand-select-id" data-placeholder="Select Brand" name="brand" multiple="" style="">'; for (var j = 0; j < arr.length; j++) { //appending options in selectbox select += '<option selected="selected"value="' + arr[j] + '">' + arr[j] + '</option>'; } select += '</select>'; //add select to div $('.select').html(select); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css"> <div class="form-group"> <label class="col-sm-3 control-label no-padding-right" for="form-field-1">Brand:</label> <div id="brand-id" class="col-sm-9"> <select id="brand-select-id" data-placeholder="Select Brand" name="brand" multiple="" class="chosen-select" style="width:300px"> <option selected="selected" value="A">A</option> <option selected="selected" value="B">B</option> <option selected="selected" value="C">C</option> <option value="D">D</option> <option value="E">E</option> </select> </div> <!--select box will come inside this--> <div class="select"> </div> </div>

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