2013-07-11 97 views
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> 
+0

好吧,嗯,首先我必須告訴你,你的縮進和HTML演示文稿很糟糕,除了有
標籤。另外,它是'.onchange = function(){}',而不是'.change(function(){})'。 – Ariane

+3

'onchange' ??? ..'.change'非常好 –

+0

呃,我從來沒有見過.change。我會相信你的。抱歉。 – Ariane

回答

3

隨着你正在訪問你應該改變從數組對象價值的方式,因爲你試圖訪問與屬性名稱的數組不工作的方式,你只能用在數組索引,但你可以通過做centerLocations["text" + address]做到這一點的對象上:

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

Fiddle

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(); 

Demo

使用對象

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

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

Demo

+0

感謝!順便說一句 - 有什麼更好的方法來正確的代碼,我需要什麼? – Roi

+0

@Roi如果你想簡化,因爲「text1」等不重要,你可以使用一個簡單的數組。 'centerLocations [0] =「some text1」'例如。但這並沒有太大的改變。 – Ariane

+0

@Roi是的,你可以優化一下,也可以用2種方法使用數組和使用對象。 – PSL