jQuery复制单选按钮组

时间:2018-10-02 00:28:03

标签: jquery

我正在尝试使用JQuery在应用程序中复制单选按钮组。但是我不知道该怎么做。我看到大多数解决方案都建议增加重复编号并设置name属性。

我的重复表格如下。数组上的名称( educationDetails [mark_type] [] )不提供唯一名称吗?该表格在Laravel集体中。

要复制的目标

<!-- Target to be copied -->
    <div class="education-fields">
    </div>

<!-- Source to copy -->
    <div class="education-fields-template>
        <div class="col-sm-6 col-md-4 col-lg-4 mt-4 form-inline">
                <div class="form-check form-check-inline">
                    {!! Form::radio('educationDetails[mark_type][]', 'GPA', false, ['class' => 'form-check-input']); !!}
                    <label class="form-check-label" for="gpa">GPA</label>
                </div>
                <div class="form-check form-check-inline">
                    {!! Form::radio('educationDetails[mark_type][]', 'Percentage', true, ['class' => 'form-check-input']); !!}

                    <label class="form-check-label" for="percentage">Percentage</label>
                </div>
                <label for="subject" class="text-gray percentage-label">Percentage
                    <small>*</small>
                </label>
                {!! Form::text('educationDetails[mark][]', null, ['class' => 'form-control ml-2 percentage-field', 'placeholder' => 'Enter percentage']) !!}
            </div>
    </div>

任何无需手动设置名称即可复制此元素的想法都会很有帮助。

我的JQuery代码

let educationFormField = '<div class="row education-fields">' + $('.education-fields-template').html() + '</div>';
        $('body').find('.education-fields:last').after(educationFormField);

1 个答案:

答案 0 :(得分:0)

那么对于初学者来说,首先要考虑的两个问题:

  • 您在这里缺少结尾引号:<div class="education-fields-templat>
  • 这不是JavaScript / JQuery还是HTML,不是吗?:{!! [...] !!}仅在下一次提供一个示例,该示例将自动运行^^:)

不过,只需将元素innerHTML复制到其他元素:

JavaScript:

document.getElementById("copyButton").addEventListener("click", () => {
  document.getElementsByClassName("education-fields")[0].innerHTML =
  document.getElementsByClassName("education-fields-template")[0].innerHTML;
});
<!-- Source to copy -->
<p>Education Fields Template</p>
<div class="education-fields-template">
  <input type="text">
  <input type="text">
</div>
<!-- Button to copy the element -->
<button id="copyButton">Copy!</button>
<!-- Target to be copied -->
<p>Education Fields</p>
<div class="education-fields"></div>

然后我很快得出了一些jQuery代码。.我以前从未真正使用过它,所以可能是错误的。

jQuery

$("#copyButton").click(() => $(".education-fields").html($(".education-fields-template").html()));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Source to copy -->
<p>Education Fields Template</p>
<div class="education-fields-template">
  <input type="text">
  <input type="text">
</div>
<!-- Button to copy the element -->
<button id="copyButton">Copy!</button>
<!-- Target to be copied -->
<p>Education Fields</p>
<div class="education-fields"></div>