简体   繁体   中英

Select a value on a drop down field with then pre selects values in a multi-select field

I have two fields. I am dynamically pulling in values for each field. I can not hard code any of the data because it its changing.

With javascript i want to select a value with the 1st single select drop down field. on click i want the second one to update with the matching ids.

ex (again values are dynamically getting pulled)

field 1- single select drop down list Name (text displayed) - Id (value submitted) Fruits - 1 Vegetables - 2 Sweets - 3 Meat- 4

Field 2- multi sect list box Name (text displayed) - Id (value submitted) Apple - 1 Carrot-2 Ice Cream - 3 Hamburger- 4 Orange- 1 Steak -4 Chocolate- 3 Raspberries -1

Desired outcome: If the user selects Fruits from field 1 then the field 2 should pre select apple, orange, Raspberries (because they all have the same id of 1)

I am dynamically pulling the data from salesforce in c# Page_Init data binding it to the fields

<asp:Panel CssClass="form-group" runat="server">
<label id="Field1" class="control-label" for="Field2" runat="server">
<asp:DropDownList ID="Field1" ClientIDMode="Static" 
onchange="myFunction(event)" CssClass="form-control" runat="server" />

<asp:Panel CssClass="form-group" runat="server">
<label id="field2" class="control-label" for="field2" runat="server"> 
</label>
<asp:ListBox ID="field2" CssClass="form-control" SelectionMode="Multiple" 
ClientIDMode="Static" runat="server" />
</asp:Panel>

<script type="text/javascript">
function myFunction(e) {
        document.getElementById("field2").value = e.target.value
    }
 </script>

I originally had this jquery in when i was just updating a single select drop down field. it is still selecting 1 value not all the values with the matching ids

I ended up looking up a similar request and edited it to be dynamic values not hard coded

<select name='field1' id="field1">
<option value="1">Fruits</option>
<option value="2">Vegetables</option>
<option value="3">Sweets</option>
<option value="4">Meat</option>
</select>

<select name='field2' id="field2" multiple >
<option value="1">Apple</option>
<option value="2">Carrot</option>
<option value="3">Ice Cream </option>
<option value="4">Hamburger</option>
<option value="1">Orange</option>
 <option value="4">Steak </option>
  <option value="3">Chocolate</option>
   <option value="1">Raspberries </option>
 </select>

 var foodsToSelect = $("#field1").val();
 var foods = document.getElementById( 'field2' );

 for ( var i = 0, l = foods.options.length, o; i < l; i++ )
 {
 o = foods.options[i];
 if ( foodsToSelect.indexOf( o.value ) != -1 )
 {
  o.selected = true;
}
}

http://jsfiddle.net/jw8rugse/2/

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