0

我正在尝试根据单选框的选择来更改输入的 ID。

<input type="text" name="judge"/>

<input type="radio" name="type" value="percent"/>Percent |
<input type="radio" name="type" value="decimal"/>Decimal
<br/>
<button type="button" id="mybutton">Check</button>
<br/><br/>
<div id="output"/>

单击单选按钮百分比或小数将更改输入框的 ID。

//Set the ID of the input box on radio change
$('input[name=type]').change(function() {
    if ($(this).val() == "percent") {
        $('input[name=judge]').attr('id', 'judge_percent');
    } else if ($(this).val() == "decimal") {
        $('input[name=judge]').attr('id', 'judge_decimal');
    }
});

//IF statement depending on the input ID created from the radio button
$('#mybutton').click(function() {
    if ($('input[name=type]').val() == "percent") {
        value_percent = parseFloat($('#judge_percent').val());
        $('#output').html(value_percent);
    } else if ($('input[name=type]').val() == "decimal") {
        value_decimal = parseFloat($('#judge_decimal').val());
        $('#output').html(value_decimal);
    }
});

这只能半途而废。如果我检查“十进制”并单击我的按钮,我会得到“NaN”,就好像它没有读取输入 ID。

编辑:这是正确的Jsfiddle:http: //jsfiddle.net/6FbdJ/1/

4

3 回答 3

2
} else($('input[name=type]').val() == "decimal") {

应该:

} else if($('input[name=type]').val() == "decimal") {

这就是你在 DEMO 中得到的。

更新:

将选择器更改为:

$('input[name=type]').val();

到:

$('input[name=type]:checked').val();

固定演示

您可以替换$(this).val()this.value.

于 2012-06-03T06:29:58.897 回答
1

更好的方法是为此创建一个闭包,将状态保留在其中以做出决定:

(function() {
    var inputField = $('input[name=judge]'), // keep reference to the text input field
    inputType = 'percent', // set default input type to percentage
    outputBox = $('#output'); // keep reference of the output area

    $('input[name=type]').change(function() {
        // change the input type based on the value (verbatim copy)
        inputType = $(this).val();
    });

    $('#mybutton').click(function() {
        var tmp;

        if (inputType == 'percent') {
            tmp = parseFloat(inputField.val()) / 100; // make a percentage
        } else if (inputType ='decimal') {
            tmp = parseFloat(inputField.val()); // don't change anything
        }
        outputBox.text(tmp); // output the calculated value
    });
}());

它将选定的输入类型保存在局部变量中,并根据单选按钮进行更改;单击按钮时,它将检查该局部变量并根据该值做出决定。

于 2012-06-03T06:44:41.817 回答
0
$('#mybutton').click(function() {
    if ($('input[name=type]:checked').val() == "percent") {
        value_percent = parseFloat($('#judge_percent').val() || 0);
        $('#output').html(value_percent);
    } else if ($('input[name=type]:checked').val() == "decimal") {
        value_decimal = parseFloat($('#judge_decimal').val() || 0);
        $('#output').html(value_decimal);
    }
});
于 2012-06-03T06:39:05.193 回答