2016-04-14 50 views
1

嗨選擇,變化值(寫入輸入)時,選擇從選擇

我得到了下面輸入

<input type="text" class="input-text" value="South Yorkshire" placeholder=" county" name="calc_shipping_state" id="calc_shipping_state"> 

,我需要改變它的選擇幾個選項的下拉菜單。問題在於輸入使用數據庫進行驗證,並且我無法訪問HTML。所以我隱藏了輸入並添加了一個使用jQuery的選擇選項,將所選選項寫入輸入。我不確定如何寫入隱藏的輸入選項上選擇的選項。使用.change().val()

這是添加代碼的選擇:

$('#calc_shipping_state_field').after("<p class='form-row form-row-wide' id='calc_shipping_state_field' id=''> <select name='' id='county_selected' class='' rel=''> <option value=''>Select a county…</option> <option value='BE'>Bedfordshire</option> <option selected='selected' value='BER'>Berkshire</option> <option value='BRI'>Bristol</option> <option value='BUCK'>Buckinghamshire</option> <option value='CA'>Cambridgeshire</option> <option value='CHES'>Cheshire</option> <option value='LN'>City of London</option> </select></p>"); 

我對「伯克希爾」選項添加selected='selected'默認情況下,使

<option selected='selected' value='BER'>Berkshire</option> 

這是我已經嘗試使用的代碼.change()但不起作用。

$("#county_selected").change(function() { 
    var county = $("select :selected").county(function() { 
    var txt = $(this).text(); 
    }).get(); 
    //add it to div 
    $('input.input-text').val('county'); 
    }); 

我希望有人能幫助我。

謝謝!

回答

1

您可以使用find()獲取選定的選項,然後在其上調用.text()。在更改功能中,this指向選擇,因此不需要重新選擇它。

$("#county_selected").change(function() { 
    $('input.input-text').val($(this).find('option:selected').text()); 
}); 

上述代碼必須在添加select後運行。如果你喜歡,你可以委託給父母或文檔,它沒有運行選擇加入後:

$(document).on('change', '#county_selected', function(){ 
    $('input.input-text').val($(this).find('option:selected').text()); 
}); 
+0

你好@MrCode非常感謝。有用。這更簡單,我認爲它.. – andresgl

1

那麼,你可以做到這一點通過使用JQuery replaceWith Method

$(document).ready(function() { 
    /* 
    * Make your new HTML ELEMENT 
    */ 
    var newHTMLelment = "<select name='calc_shipping_state'>"; 
     newHTMLelment += "<option value='01'>01</option>"; 
     newHTMLelment += "<option value='02'>02</option>"; 
     newHTMLelment += "</select>"; 
    /* 
    * Replace current HTML element with new one 
    */ 
    $("#calc_shipping_state").replaceWith(newHTMLelment); 

}); 
+0

感謝@hmd你的代碼的作品,但我認爲另一個更乾淨。 – andresgl

+0

那麼,你至少可以投票:)然後:) @andresgl – hmd

+1

當然!再次感謝! – andresgl