Link to home
Start Free TrialLog in
Avatar of Crystal Rouse
Crystal RouseFlag for United States of America

asked on

Copy drop-down selection to another form element

I need to copy a drop-down section on a form to another form element.

So I have a drop-down List:

<div class="row">
                        <div class="col-xs-6">
                            @Html.Label("Select one or more Item(s):")
                            @Html.DropDownListFor(x => x.List, sl.getItem(s)(), new
                       {
                           @type = "drop",
                           @multiple = true,
                           @style = "width: 100%",
                           @id = "List",
                           data_placeholder = "Select Item(s)",
                       })
                        </div>

                        <div class="col-xs-2 col-xs-offset-1">
                            <button type="button" class="btn btn-info" style="vertical-align:bottom;" onclick="NewRequest.copyList();">
                                Copy to Summary
                            </button>
                        </div>
                    </div>

The View also has:

<script type="text/javascript">
    var NewRequest = new NewRequestClass();
    NewRequest.init();
</script>

My JavaScript file has:

function NewRequestClass() {
    this.List;
    this.notes;
}

copyList: function (sender) {
        alert(this.List);
        this.notes = this.List;
    },

    //Maps variables to the correct field
    init: function () {
        this.List = document.getElementById("List");
        this.notes = document.getElementById("notes");
    },
Avatar of Dustin Saunders
Dustin Saunders
Flag of United States of America image

So you want to copy it from one <div> to another?

You can do so with JS:
document.getElementById('targetid').innerHTML = document.getElementById('source').outerHTML

Open in new window


This would copy selections as well.

Typically what I have done for dynamic forms is generate a 'template' that is in a hidden <div> then when adding elements I copy from that template with its defaults.

<html>
<head>

</head>
<body>

<div id="template" hidden>
	<div class="row">
		<select>
			<option>One</option>
			<option>Two</option>
		</select>
	</div>
</div>

<div>
   <div class="row" id="data">
   
   </div>
   <button onclick="loadanother()">Load Another</button>
</div>


<script>
function loadanother(){
	var template = document.getElementById('template');
	var data = document.getElementById('data');
	data.innerHTML += document.getElementById('template').innerHTML;
}
</script>
</body>

</html>

Open in new window


I use an attribute like 'data-istemplate' when collecting results to skip the templates, unless I'm generating ids for each new element.
Avatar of Crystal Rouse

ASKER

Thanks for the help!  When I try this, the contents are added to my "notes" div except they are added after
the placeholder and when I click in the field the text goes away.  They also show up as:

<option value="the contents">TEXT</option>
If you've got a placeholder, the example has += which will append.  You can use just = to overwrite the innerHTML.

Here's an example (without using a template).
<html>
<head>

</head>
<body>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>


					<br><br><br>
					
<div class="row">
	<div class="col">
		<select type="drop" multiple=true style="width: 100%" id="List">
			<option id="1">One</option>
			<option id="2">Two</option>
			<option id="3">Three</option>
		</select>
	</div>
</div>

<div class="row">
	<div class="col">
		<select type="drop" multiple=true style="width: 100%" id="Notes">
		</select>
	</div>
</div>

<button onclick="copyList()">CopyList</button>


<script>
function copyList(){
	var options = document.getElementById('List');
	var target = document.getElementById('Notes');
	target.innerHTML = options.innerHTML;
}
</script>
</body>

</html>

Open in new window


I'm not sure without seeing the page why it would copy like that but if you're still having an issue if you scrub any private info and paste the HTML after the page is generated I can take a look.
The methods that you need here is `.cloneNode()` to clone the element and `.appendChild()` to append it to the specific area you want, something like :

NewRequestClass.prototype = {
  init: function() {
    this.List = document.getElementById("List");
    this.notes = document.getElementById("notes");
  },
  copyList: function() {
    this.notes.appendChild( this.List.cloneNode() );
  }
}

Open in new window

NOTE: The only problem that you'll face is the correctness of your HTML since the id must be unique in the same document and when you copy the element the id will be duplicated, what I would suggest is the use of class instead :

...
@multiple = true,
@style = "width: 100%",
@class = "List"
...

Open in new window


And get your element in the js part like:

this.List = document.querySelector(".List");

Open in new window


Working live fiddle
If you want to keep the id in the main drop-down, then I would suggest changing the id of the cloned new drop-down using JS code like :

copyList: function() {
    var cloned_list = this.List.cloneNode();
    cloned_list.id = "the_new_id";

    this.notes.appendChild( cloned_list );
}

Open in new window

Thanks for all of the help. I actually need to copy the selected values from the drop down list to a Notes text field.  I've tried variations of both approaches and need some more help please.
I sorry I didn't get you the first time, is this what you want?

http://jsfiddle.net/z_acharki/pkxz603a/9/

  copyList: function() {
    this.notes.value = this.List.value;
  }

Open in new window

I figured out some of this:

function copyList() {

var list = document.getElementById("List");
var notes = document.getElementById("Notes");

notes.value += list.value;

}

This actually copies the selected item from the drop-down list to my Notes text box.  But, what I need to do is copy all of the selections since its a multi-select drop-down list.  It only copies the first item selected.
Then you need this one using the selected options :

  copyList: function() {
    const selected_options = this.List.querySelectorAll('option:checked');
    const values = Array.from(selected_options).map(el => el.value);
    
    this.notes.value = values;
  }

Open in new window


http://jsfiddle.net/z_acharki/pkxz603a/14/
I misunderstood what you needed as well, here's my sample updated.

<html>
<head>

</head>
<body>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>


					<br><br><br>
					
<div class="row">
	<div class="col">
		<select type="drop" multiple=true style="width: 100%" id="List">
			<option id="1">One</option>
			<option id="2">Two</option>
			<option id="3">Three</option>
		</select>
	</div>
</div>

<div class="row">
	<div class="col">
		<textarea id="Notes" rows=4></textarea>
	</div>
</div>

<button onclick="copyList()">CopyList</button>


<script>
function copyList(){
	var options = document.getElementById('List').selectedOptions;
	document.getElementById('Notes').value = Array.from(options).map(o=>o.value);
}
</script>
</body>

</html>

Open in new window

Thank you for the responses!  I am getting errors when trying either solution.

1) when I try:  var options = document.getElementById('List').selectedOptions;

    copyList: function () {
        var List = document.getElementById("List");
        var options = List.selectedOptions;
        alert(options);
    },

I get a returned value of:  undefined

2) when I try:  

 var List = document.getElementById("List");
        var selected_options = List.querySelectorAll('option:checked');
        alert(selected_options);

I get:  [object NodeList]
On the 2nd option, I get errors on this line: var values = Array.from(selected_options).map(el => el.value);
Try to replace it by :

const values = Array.from(selected_options).map(function(el){
    	return el.value;
});

Open in new window

Thank you so much for your help and patience working with me on this!  I get an error on the Array.from that Object doesn't support property or method 'from'
ASKER CERTIFIED SOLUTION
Avatar of Zakaria Acharki
Zakaria Acharki
Flag of Morocco image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
That worked!  Thanks again for all of your help!
With pleasure, happy to help anytime.
Sorry, didn't get a chance to circle around before it got answered but glad to see you got it working