2014-10-16 47 views
1

我有一個輸入和兩個單選按鈕。如果使用jquery選擇收音機,則填充輸入

輸入接受一個人住在某個住所的時間段的數字。

單選按鈕是月&年。

我想使用第一個輸入值(居住長度的數值)填充第二個輸入,並根據所選無線電選擇月或年的值。

我已經吐出了時間,但它吐出兩個單選按鈕的值,因爲我沒有if語句來檢查。我已經在我的表單中有jquery,它可以工作。我只需要我的表格的這一小部分工作。

我的問題是,我如何設置條件語句來檢查什麼廣播被檢查?

HTML

<input type="number" value="" required maxlength="5" class="form-control" name="homeLength" id="homeLength"> 
<input type="radio" id="years" value="Years" name="length" required> Years 
<input type="radio" id="months" value="Months" name="length"> Months 

jQuery的

$('#months').click(function() { 
    if ($(this).attr("checked") == "checked") { 
    $('#homeLength, #months').bind('keypress blur', function() { 
     $('#homeTime').val($('#homeLength').val() + ' ' + ' ' + $('#months').val() + ' ' + ' '); 
    }); 
    } 
}); 

$('#years').click(function() { 
    if ($(this).attr("checked") == "checked") { 
    $('#homeLength, #years').bind('keypress blur', function() { 
     $('#homeTime').val($('#homeLength').val() + ' ' + ' ' + $('#years').val() + ' '); 
    }); 
    } 
}); 
+0

哪裏是'<... ID = 「hometime」 ...>'? – mplungjan 2014-10-16 13:54:33

回答

0

Replave你這個

$('#months').click(function() { 
     console.log($(this).prop('id')); 
     $('#homeLength, #months').bind('keypress blur', function() { 
     $('#homeTime').val($('#homeLength').val() + ' ' + ' '+$('#months').val()+ ' ' + ' '); 
     }); 
    }); 
    $('#years').click(function() { 
     console.log($(this).prop('id')); 
     $('#homeLength, #years').bind('keypress blur', function() { 
     $('#homeTime').val($('#homeLength').val() + ' ' + ' ' + $('#years').val()+ ' '); 
     }); 
    }); 

javascript代碼,只要用戶將選擇任何單選按鈕ü可以它的值由

$(this).prop('value'); 
+0

沒有必要檢查一臺收音機是否被檢查,因爲點擊它會檢查它 – mplungjan 2014-10-16 13:51:39

+0

是的,你是對的,但是對他的代碼的詛咒我沒有太大的改變。所以他可以很容易地明白 – 2014-10-16 14:01:53

+0

謝謝,這工作到完美。我很感激。 – 2014-10-16 14:04:03

1

這類checkings最可用的條件語句是:

if ($(this).is(':checked')) 

所以你可以看到響應是布爾值。

2

通過

$(this).prop('id'); 

獲得其ID,您需要只檢查選中的收音機的價值,並做到這一點上的密碼/模糊和點擊任何收音機

$(function() { 
 
    $('#homeLength').on('keyup, blur', function() { 
 
    var lgt = $("input:radio[name=length]:checked").val(); 
 
    $('#homeTime').val($(this).val() + ' '+lgt); 
 
    }); 
 
    $("input:radio[name=length]").on("click",function() { 
 
    $('#homeLength').blur(); // trigger the blur event of the field to update 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<input type="number" value="" required maxlength="5" class="form-control" name="homeLength" id="homeLength"> 
 
<input type="radio" id="years" value="Years" name="length" required> Years 
 
<input type="radio" id="months" value="Months" name="length"> Months 
 
<hr/> 
 
<input type="text" value="" class="form-control" name="homeTime" id="homeTime">