根据文本字段值更改单选按钮检查状态

时间:2015-04-09 15:28:26

标签: javascript radio-button

抱歉,我对javascript很新,需要帮助。我有这个表单在文本字段输入一个整数,我想根据文本字段的值自动更改单选按钮的检查状态。

因此,如果该值大于20,则会选中“有时”单选按钮。 如果值大于40,则选中“常”单选按钮。但如果值小于20,则选中“从不”单选按钮

到目前为止,这是我的代码。

HTML

    1. DT Result
    <input class="DT-input-container" id="DTResult" name="DTResult" type="text" value=""/><label for="inf_option_1DigestiveTract">1. Digestive Tract</label>
            <input checked="checked" id="inf_option_1DigestiveTract_748" name="inf_option_1DigestiveTract" type="radio" value="748" />
            <label for="inf_option_1DigestiveTract_748">Never</label>
            <input id="inf_option_1DigestiveTract_752"  name="inf_option_1DigestiveTract" type="radio" value="752" />
            <label for="inf_option_1DigestiveTract_752">Sometimes</label>
            <input id="inf_option_1DigestiveTract_750" name="inf_option_1DigestiveTract" type="radio" value="750" />
            <label for="inf_option_1DigestiveTract_750">Often</label>
<input type="submit" value="Submit" />         

的Javascript

$(function() {
var result1 = document.getElementById('inf_custom_1DigestiveTractResult').value
    if ( result1 > 20 ) {
        $("input[id=inf_option_1DigestiveTract_752]").attr('checked', true);
    } else if ( result1 > 40 ) {
        $("input[id=inf_option_1DigestiveTract_750]").attr('checked', true);
    }});

1 个答案:

答案 0 :(得分:0)

您可能正在寻找的是跟踪onkeyup事件(jquery

$('DTResult').keyup(function() {
    var len = $(this).val().length;

    if (len < 20) {
        $("#inf_option_1DigestiveTract_748").attr('checked', true);
    else if (len >= 20 && len < 40) {
        $("#inf_option_1DigestiveTract_752").attr('checked', true);
    } else {
        $("#inf_option_1DigestiveTract_750").attr('checked', true);
    }
});

编辑:要求已更改

$(document).ready(function() {
    var setDTcheckboxes = function () {
        var len = $(this).val().length;

        if (len < 20) {
            $("#inf_option_1DigestiveTract_748").attr('checked', true);
        else if (len >= 20 && len < 40) {
            $("#inf_option_1DigestiveTract_752").attr('checked', true);
        } else {
            $("#inf_option_1DigestiveTract_750").attr('checked', true);
        }
    }

    $('DTResult').keyup(setDTcheckboxes);
    setDTcheckboxes();
});
相关问题