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);
    }
});

これは中途半端にしか機能しません。「decimal」をチェックしてボタンをクリックすると、入力IDを読み取っていないかのように「NaN」が表示されます。

編集:正しいJsfiddleは次のとおりです:http://jsfiddle.net/6FbdJ/1/

4

3 に答える 3

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

する必要があります:

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

これはあなたがデモで得たものです。

アップデート:

セレクターを次の場所から変更します。

$('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 に答える