让两个单选按钮充当一个复选框

时间:2019-07-17 13:53:08

标签: html css checkbox input radio

是否可以不做大的修改就具有两个单选按钮,这些单选按钮将显示为一个复选框?

实际上,我们面临的问题是,我们正在提交表单数据,这些数据将由系统自动处理,如果使用复选框,则不可能。 到目前为止,我们使用了两个单选按钮(启用X:是|否),但是我们当前的客户希望使用一个复选框。

我们知道,如果我们扩展后端会更容易,但是不幸的是这是不可能的。

编辑:我们可以访问后端,并且可以更改验证行为,但是在我们看来,这比前端更改要付出更多的努力。另外,我们也希望尽可能避免使用JS。

谢谢。

4 个答案:

答案 0 :(得分:1)

您可以进行以下操作:

<label class="radioButtons">
  <input type="radio" name="option" value="true">
  <input type="radio" name="option" value="false">
</label>

<input type="checkbox" onchange="changeCheckbox(this)"></input>

JavaScript

function changeCheckbox(checkboxBtn) {
  if (checkboxBtn.checked) {
    document.querySelector('.radioButtons input:first-child').checked = true; // mark first radio as checked
  } else {
    document.querySelector('.radioButtons input:last-child').checked = true; // mark second radio as checked
  }
}

然后,您当然会隐藏radio buttons

.radioButtons {
  display: none;
}

答案 1 :(得分:1)

您可以尝试使用CSS

    input[id^="radio"] {
        display: none;
    }

    input[id^="radio"]:checked+label {
        display: none;
    }

    input[id^="radio"]+label {
        content: '';
        height: 15px;
        width: 15px;
        display: inline-block;
        border: 1px black solid;
        position: relative;

    }

    input[id^="radio"]+label:first-of-type::after {
        content: '';
        height: 10px;
        width: 5px;
        border-right: solid black 3px;
        border-bottom: solid black 3px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translateX(-50%) translateY(-60%) rotate(30deg);
    }

    input[id^="radio"]+label {
        display: none;
    }

    input[id^="radio"]:not(checked)+label {
        display: inline-block;
    }
<input type="radio" checked name="radioCb" id="radio1"><label for="radio1"></label>

<input type="radio" name="radioCb" id="radio2"><label for="radio2"></label>

答案 2 :(得分:0)

否,如果您无权访问后端,那么如何修改复选框的代码。 您不需要扩展后端,只需隐藏另一个单选按钮即可。

答案 3 :(得分:0)

可以使用JS(在我的示例中为jQuery)来修改收音机的功能。

然后,您可以仅检查无线电是否已检查,具体取决于您的后端设置。这是一个相当广泛的问题-但从本质上讲,是的,您可以使单选按钮像复选框一样工作。在这种情况下,如果选择了收音机,它只会发出警报。

CodePen Example

<form method="post">
<h4>Form XYZ</h4>
<label><input name="question1" type="radio" id="radio"> I agree to be contacted by StackOverflow</label>
  <button type="submit" id="submit">Submit</button>
</form>
$("input:radio:checked").data("chk", true);
$("input:radio").click(function() {
  $("input[name='" + $(this).attr("name") + "']:radio")
    .not(this)
    .removeData("chk");
  $(this).data("chk", !$(this).data("chk"));
  $(this).prop("checked", $(this).data("chk"));
});

$('#submit').click(function() {
   if($('#radio').is(':checked')) { alert("it's checked"); }
});