Search code examples
javascriptjqueryeachselected

Javascript/jquery write each text value from :selected option to separate input


I'm retrieving some data from MySQL and write it in certain select tags, then i retrieve every selected option value and display it in a DIV, here is the javascript:

 function main() {
 $("select").change(function () {
 var str = "";

 $("select option:selected").each(function () {
    str += $(this).text() + " ";
  });

 $("div#one").text(str);
 })
  .trigger('change');

  }

So, i want each retrieved value to be written in separate input:

First value: <input type="text" id="test" />
Second value: <input type="text" id="test2" />
Third value: <input type="text" id="test3" />

How can i do that? Many thanks!


Solution

  • For adding the selected options in a "div" tag:

    //empty div at start using .empty()
    $("select").change(function () {
        //get the selected option's text and store it in map
        var map = $("select :selected").map(function () {
            var txt = $(this).text();
            //do not add the value to map[] if the chosen value begins with "Select"
            return txt.indexOf("Select") === -1 ? txt + " , " : "";
        }).get();
        //add it to div
        $("#one").html(map);
    });
    

    For adding the selected options in an "input" tag:

    //empty textboxes at start using .val("")
    $("select").change(function () {
        var text = $(":selected", this).text() //this.value;
        //get the index of the select box chosen
        var index = $(this).index();
        //get the correct text box corresponding to chosen select
        var $input = $("input[type=text]").eq(index);
        //set the value for the input
        $input.val(function () {
            //do not add the value to text box if the chosen value begins with "Select"
            return text.indexOf("Select") === -1 ? text : "";
        });
    });
    

    Consolidated demo

    http://jsfiddle.net/hungerpain/kaXjX/