javascript - Set Form Input Attribute by Selected Option Attribute -


my goal add value , attribute(s) of options in select field input element.

the options generated dynamically - feasible me give each unique id if divine solution.

i have following code ( here's fiddle ):

html

<select size="3" width="220" style="width:220px" id="select_trainer" multiple="yes">      <option value="1" name="unique-code-1" id="unique-id-1">jillian</option>     <option value="2" name="unique-code-2" id="unique-id-2">james</option>     <option value="3" name="unique-code-3" id="unique-id-3">jean</option> </select> <input value="" name="" id="save_select_profile" checked="checked"/> 

javascript

document.getelementbyid('select_trainer').onchange = function () {     document.getelementbyid('save_select_profile').value = event.target.value;     document.getelementbyid('save_select_profile').setattribute('name', event.target.name); }        

the javascript (from here , here) great job of setting value of input field match option selected.

but addition - document.getelementbyid('save_select_profile').setattribute('name', event.target.name); - not set selected-option name attribute input.

i found if <select> element has name value set, value added input instead.

how pass selected, child element name value input field?

event.target return whole select element, not nested option tag, stores name you're trying set. selected option, need do:

event.target.options[event.target.selectedindex] 

then selected option's name, do:

event.target.options[event.target.selectedindex].getattribute('name'); 

then set name, way doing setattribute function.

here working codepen


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -