如何统一来自多组单选按钮和多组复选框的文本?多组、单选、复选框、按钮

2023-09-06 19:28:10 作者:癮

我的javascript代码是这样的:

My javascript code like this :

$(function(){
    $('input[type="radio"]').click(function(){
        var $radio = $(this);
        var name = $(this).prop("name");

        // if this was previously checked
        if ($radio.data('waschecked') == true)
        {
            $radio.prop('checked', false);
            $radio.data('waschecked', false);
            $('#result-select').text('');
        }
        else{
            $radio.data('waschecked', true);
            $("input[name=""+name+""]:not(:checked)").data('waschecked', false);
            $('#result-select').text(txt);
        }

        var output = [];
        var txt;
        $('input[type="radio"]:checked').each( function() {
                txt = $(this).parent().text();
                output.push(txt);
        });
        $('#result-select').text(output.join(' - '));
    });
});

演示和完整代码如下:https://jsfiddle.net/oscar11/m7by6zcw/41/

我想:

如果我选择切尔西、马德里和尤文,结果是这样的:

If I select chelsea, madrid and juve the result like this :

切尔西 - 马德里 - 尤文

Chelsea - Madrid - Juve

如果我选择切尔西和马德里,结果如下:

If I select chelsea and madrid the result like this :

切尔西 - 马德里

如果我选择切尔西、马德里、尤文和米兰,结果是这样的:

If I select chelsea, madrid, juve and milan the result like this :

切尔西 - 马德里 - 尤文 - 米兰

Chelsea - Madrid - Juve - Milan

所以如果我选中单选按钮,它会显示文本.如果我取消选中单选按钮,它不会显示文本.我检查组合框,它显示文本.如果我取消选中组合框,它不会显示文本

So if I check radio button, it display the text. If I uncheck radio button, it not display the text. I check combobox, it display the text. If I uncheck combobox, it not display the text

例如文字:

切尔西 - 马德里 - 尤文 - 米兰

界面设置基础之复选框和单选按钮

Chelsea - Madrid - Juve - Milan

我取消选中尤文,结果是这样的:

I uncheck Juve, the result like this :

切尔西 - 马德里 - 米兰

Chelsea - Madrid - Milan

在单选按钮上,它可以工作但是在复选框上,我还是一头雾水

On the radio button, it works But on the checkbox, I'm still confused

我该怎么做?

更新:

单选按钮可以取消选中

例如:

如果我选择切尔西、马德里和尤文,结果是这样的:

If I select chelsea, madrid and juve the result like this :

切尔西 - 马德里 - 尤文

Chelsea - Madrid - Juve

然后我取消选中马德里,结果是这样的:

Then I uncheck madrid, the result like this :

切尔西 - 尤文

推荐答案

你需要修改输入元素选择器来处理输入类型复选框和单选按钮:

You need to modify the input element selector to handle both input types checkboxes and radio buttons:

$('.list-unstyled input').....

工作演示