0

選択ボックスからオプションを選択できるコードがあります。

各選択肢は、ファイルされた TEXTAREA に異なるテキストを出力する必要があります

私は何を間違えましたか?何を変更すればよいですか?

<script src="jquery.js"></script>
<form name="form1">
    <fieldset name="Group1">
        <legend>Group box</legend>Center Title:
        <select name="ctrTitles" id="ctrTitles">
            <option value="1">Corp 1</option>
            <option value="2">Shamrock Gold</option>
            <option value="3">Hensin Way</option>
        </select>
        <br />
        <br />
        Address 1:
        <textarea name="TextArea1" id="TextArea1" cols="20" rows="2"></textarea>
        <br />
    </fieldset>
</form>
<script>
    var centerLocations = new Array({
        text1: 'some text1'
    }, {
        text2: 'some text2'
    }, {
        text3: 'some text3'
    });

    $('#ctrTitles').change(function() {
        address = $(this).val()
        val = $(":selected", this).index();
        $("#TextArea1").val(centerLocations["text" + address]);

    });
</script>
4

1 に答える 1

3

配列からオブジェクトに変更する必要がある値にアクセスする方法では、そのように機能しないプロパティ名で配列にアクセスしようとしているため、配列でのみインデックスを使用できますが、配列でそれを行うことができますすることによるオブジェクトcenterLocations["text" + address]

var centerLocations = {
    text1: 'some text1',
    text2: 'some text2',
    text3: 'some text3'
};

フィドル

配列またはオブジェクトで行うことができる2つの方法。

配列の使用 (オプションのインデックスが配列項目のインデックスと一致する場合のみ)

var centerLocations = [
  'some text1' //you can even get rid of text1, text2 etc..
,  'some text2'
, 'some text3'
 ];

$('#ctrTitles').change(function () {
    $("#TextArea1").val(centerLocations[this.selectedIndex]);

   //with your original structure you would do
   //$("#TextArea1").val(centerLocations[this.selectedIndex]['text'+this.value]);

}).change();

デモ

オブジェクトの使用

var centerLocations = {
    text1: 'some text1',
    text2: 'some text2',
    text3: 'some text3'
};

$('#ctrTitles').change(function () {
    $("#TextArea1").val(centerLocations["text" + this.value]);
}).change();

デモ

于 2013-07-11T21:38:25.157 に答える