我對select元素有一個onchange屬性,我想在另一個函數中獲取所選選項的值,我該如何得到它? 提前致謝。 這裏是我的html我正在學習jquery,我正在練習並堅持要獲得選定的選項值
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="form-group">
<select class="form-control" name="country" id="country" onChange="stateChange(this.value)">
<option>SELECT COUNTRY</option>
//all countries name like bellow
<option value="USA"> USA </option>
................
</select>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="form-group">
<select class="form-control" name="city" id="state">
<option>SELECT CITY</option>
</select>
</div>
</div>
<div class="form-group btn-field">
<div class="row">
<div class="col-sm-12">
<input type="submit" id="create-account" tabindex="4" class="form-control btn btn-login" value="CREATE ACCOUNT">
</div>
</div>
</div>
stateChange工作完美,但我想在波紋管的功能得到這個,它總是返回選項1這裏#創建帳戶是一個按鈕的id
$('#create-account').click(function (e) {
var country = $('#country option:selected').text();
alert(country);
});
var country_arr = new Array("Afghanistan", "Albania",........);
// States
var s_a = new Array();
s_a[0]="";
s_a[1]="Badakhshan|Badghis|Baghlan|Balkh|Bamian|Farah|Faryab|Ghazni|Ghowr|Helmand|Herat|Jowzjan|Kabol|Kandahar|Kapisa|Konar|Kondoz|Laghman|Lowgar|Nangarhar|Nimruz|Oruzgan|Paktia|Paktika|Parvan|Samangan|Sar-e Pol|Takhar|Vardak|Zabol";
s_a[2]="Berat|Bulqize|Delvine|Devoll (Bilisht)|Diber (Peshkopi)|Durres|Elbasan|Fier|Gjirokaster|Gramsh|Has (Krume)|Kavaje|Kolonje (Erseke)|Korce|Kruje|Kucove|Kukes|Kurbin|Lezhe|Librazhd|Lushnje|Malesi e Madhe (Koplik)|Mallakaster (Ballsh)|Mat (Burrel)|Mirdite (Rreshen)|Peqin|Permet|Pogradec|Puke|Sarande|Shkoder|Skrapar (Corovode)|Tepelene|Tirane (Tirana)|Tirane (Tirana)|Tropoje (Bajram Curri)|Vlore";
.........
function populateStates(countryElementId, stateElementId){
var selectedCountryIndex = document.getElementById(countryElementId).selectedIndex;
var stateElement = document.getElementById(stateElementId);
stateElement.length=0; // Fixed by Julian Woods
stateElement.options[0] = new Option('Select State','');
stateElement.selectedIndex = 0;
var state_arr = s_a[selectedCountryIndex].split("|");
for (var i=0; i<state_arr.length; i++) {
stateElement.options[stateElement.length] = new Option(state_arr[i],state_arr[i]);
}
}
function stateChange(country) {
for(var pos=0;pos<=country_arr.length;pos++)
{
if (country==country_arr[pos])
{
break;
}
}
++pos;
if(pos<253)
{
populateState(pos);
}
}
function populateState(countryId)
{
var state_arr = s_a[countryId].split("|");
var select = document.getElementById('state');
for(var s = select.options.length - 1 ; s >= 0 ; s--)
{
select.remove(s);
}
for (var i = 0; i<state_arr.length; i++){
var opt = document.createElement('option');
opt.value = state_arr[i];
opt.innerHTML = state_arr[i];
select.appendChild(opt);
}
}
以創建一個按鈕'創建-account' ID,它會正常工作。 –
已經做到了。只是在描述中跳過它 –
那麼問題是什麼?它工作得很好,除了你沒有提供'stateChange'函數。 –