Convert div text to dropdown and div text to selected option

The div text should become the selected selection of the generated selection. I am successfully creating a dropdown and replacing the div, but the value set to set the selected option is not getting selected.

Below is how I get the div value and how I create the dropdown

<script type="text/javascript">

var d = document.getElementById("val_to_set");

 var rvalue = d.innerHTML;    //Getting the value of div

//The options of a dropdown are populated from another dropdown menu 

 var listOptions =  document.getElementById("dropdown");

 var newddown = '<select name="displayoption">'+listOptions.innerHTML+'</select>';

 //Replace the div with the created dropdown menu 

d.innerHTML = newddown;    //TARGET ELEMENT

</script> 

      

I found this link which explains how to select by value, text or index

[1] http://www.daftlogic.com/information-programmatically-preselect-dropdown-using-javascript.htm

When trying to get the options of the newly created dropdown I get "options is undefined"

The new dropdown will not select this option - I've tried all the cases in this link to include adding the following lines before I replace the div with the dropdown.

var seeker = ">"+rvalue+"<";
newddown = newddown.replace(seeker, "selected"+seeker);

      

What I do? I am a beginner with jQuery and I would like to stick with JavaScript.

EDITED - an included dropdown used to populate the options of the target element

<select id="dropdown" name="listedoptions" >
<?php

echo "    <option value=''></option>  \n";
          $ores = sqlStatement("SELECT option_id, title, is_default FROM list_options" .
                  " WHERE list_id = 'adjreason'  ORDER BY seq, title");

            while ($orow = sqlFetchArray($ores)) {
            echo "    <option value='" . $orow['option_id']). "'";
            echo ">" . $orow['title'] . "</option>\n";
            } 
 ?>
 </select>

      

+3


source to share


1 answer


Here's an example working with your code and some examples:

http://jsfiddle.net/m6y3mgky/

Instead of replacing the text, it is very easy to iterate over the options and select the correct one programmatically, this is consistent with the article you linked to. It's also less error prone.



var opts = d.childNodes[0].options;
for (var i = 0; i < opts.length; i++) {
    if (opts[i].value == rvalue) {
        opts[i].selected = true;
        break;
    }
}

      

Note: d

refers to a <div>, not a <select> node, this is because you are using innerHTML

.

0


source







All Articles