2011-08-10 44 views
1

我有幾組單選按鈕,最後一個是「其他」字段,用戶可以在其中指定他們的「其他」回答。將單選按鈕的值設置爲Jquery中其他輸入字段的值

我想將「其他」單選按鈕的值設置爲剛填寫的「其他」文本輸入字段的值。

這是我的html:

<fieldset> 
    <h3>We are online via ...</h3> 
    <label for="online_via[1]"> 
     <input type="radio" name="online_via" id="online_via[1]" value="laptop" /> Laptop 
    </label> 
    <label for="online_via[2]"> 
     <input type="radio" name="online_via" id="online_via[2]" value="desktop" /> Desktop 
    </label> 
    <label for="online_via[3]"> 
     <input type="radio" name="online_via" id="online_via[3]" value="mobile" /> GSM, Smartphone, PDA 
    </label> 
    <label for="online_via[4]"> 
     <input type="radio" name="online_via" id="online_via[4]" alue="tablet" /> Tablet 
    </label> 
    <label for="online_via[other]"> 
     <input type="radio" name="online_via" id="online_via[other]" value="other" /> Other, specify: <input type="text" id="online_via[specified]" class="other" /> 
    </label> 
</fieldset> 

正如你所看到的,最後一個單選按鈕,其標籤標記中包含輸入[類型=「文本」。我想把它的價值,並將其用作另一個單選按鈕的值。 這是我一直在嘗試jQuery的:

$(function(){ 
    $('.other').keyup(function(){ 
     var radio = $(this).attr('id').replace('specified','other'); 
     $('input#' + radio).attr("value", $(this).val()); 
     console.log($('input#' + radio).val()); 
    }); 
}); 

我不斷收到「未定義」。我究竟做錯了什麼? jquery jedis團結!

P.S .:請記住,我有幾組單選按鈕。 P.P.S:爲什麼#online_via [specified]字段沒有name屬性,是因爲我想在發佈數據時忽視它,因爲我希望將其值存儲在#online_via [other]字段中。

期待您的回覆。

回答

1
$(function(){ 
    $('.other').keyup(function(){ 
     $(this).parent().find('input[type=radio]').val($(this).val()); 
    }); 
}); 

會這樣做嗎?

+0

哇!一個真正的jquery jedi,你是!我接受你的答案,但是SO告訴我等10分鐘。 – maartenmachiels

+0

偉大的:)高興地幫助! – Pelshoff

+1

只是爲了澄清爲什麼你的代碼不工作,這是因爲jQuery如何在選擇中使用'[]'。它用在上面的代碼中,在它們的屬性上搜索某些東西,所以在你的代碼中,jQuery正在尋找一個帶有其他屬性的#id。 所以你應該只使用id和類中的字母數字。 – ThoKra

0

爲此,首先:

<label for="online_via[other]"> 
     <input type="radio" class="otherClass" name="online_via" id="online_via[other]" value="other" /> Other, specify: <input type="text" id="online_via[specified]" class="other" /> 
    </label> 

則:

$('.other').keyup(function(){ 

     $('.otherClass').val($(this).val()); 
     console.log($('.otherClass').val()); 
    }); 
相關問題