开发者

Complex Javascript and HTML question, <select> and <textarea>

Let's 开发者_如何学Csay I have multiple select box with options that have different options. On click, I want to values to be transported to a textarea. I'll try to show them in images.

Complex Javascript and HTML question, <select> and <textarea>


Possible without jQuery as well and not really complex.

Have this JS:

<script type="text/javascript">
function CopyValues(oDDL, sTargetId) {
    var arrValues = new Array();
    for (var i = 0; i < oDDL.options.length; i++) {
        var curOption = oDDL.options[i];
        if (curOption.selected)
            arrValues.push(curOption.value);
    }
    document.getElementById(sTargetId).value = arrValues.join("\n");
}
</script>

Activate it from within the select tag like this:

<select multiple="multiple" onclick="CopyValues(this, 'txtData');">

And whenever user click the drop down the selected values will be copied to textarea with the given ID, e.g.:

<textarea id="txtData"></textarea>

Live test case: http://jsfiddle.net/yahavbr/UBwML/


Assuming your textarea has an ID of "text":

(Note: this uses the jQuery framework, which makes things a lot easier. See section further down for non-jQuery solution):

$('select').change(function () {
    $('#text').val($(this).find('option:selected').text());
});

This will replace any text already inside the textarea though. If you want to simply add it to the end (with a space), then:

$('select').change(function () {
    $('#text').val($('#text').val() + ' ' + $(this).find('option:selected').text());
});

Pure Javascript solution:

var selects = document.getElementsByTagName('select'),
    textarea = document.getElementById('text');
for (var i = 0, select; select = selects[i]; i++) {
    select.selectedIndex = -1;
    select.onchange = (function (s) {
        return function () {
            textarea.value +=
                ' ' + s.options[s.selectedIndex].innerHTML;
            s.selectedIndex = -1;
        };
    })(select);
}

Demo: http://jsfiddle.net/Gdp6p/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜