1

我有一个 HTML 表单,其中包含 3 个组(A、B 和 C)中的一系列问题,用户只能回答任一组的问题。我有一个脚本可以验证他们的输入,以检查他们是否只回答了一组中的所有问题。

我想捕捉他们回答了哪组问题并将其作为隐藏输入发送。我已经设置了这样的隐藏输入:

<input type="hidden" name="type" value="" id="type">

理想情况下,我想在提交时将其替换为:

<input type="hidden" name="type" value="groupA" id="type">

我已经设置了一个显示表单/脚本的小提琴:

http://jsfiddle.net/fmdataweb/CGp8X/

这是我当前的验证脚本:

$('#editRecord').on('submit', validate);
$('input.sectionclear').on('click', function() {
    $(this).next().find('input').attr('checked', false);
});
function validate(ev) {
    var sectionsTouched = $('tbody').has(':checked'),
       inputs = {},
       errorMessage = '';

    if (sectionsTouched.length === 0) {
        errorMessage = 'Please check something before submitting.';
    } else if (sectionsTouched.length > 1) {
        errorMessage = 'Please complete A or B or C only';
    } else {
        sectionsTouched.find('input').each(function(i, e) {
            var me = $(e), name = me.attr('name');
            inputs[name] = !!inputs[name] || me.is(':checked');
        });
        $.each(inputs, function(k, v) {
            if (!v) {
                errorMessage = 'It appears you have not completed all questions.';
            }
            return v;
        });            
    }
    if (errorMessage !== '') {
        $('#error').html(errorMessage);
        ev.preventDefault();
        return false;
    }
    return true;
}


function seriesNames() {
    var names = [];
    $('h3').each(function(i, e) {
        names.push($(e).text());
    });
    return names;
}

function namesCommaDelimited(namesArr, conjunction) {
    var retval = '', i, l = namesArr.length - 1, delimiter = '';
    if (l === 0) {
       return retval;
    }
    for (i = 0; i < l; i += 1) {
        retval += delimiter;
        retval += namesArr[i];
        delimiter = ', ';
    }
    retval += delimiter;
    retval += conjunction;
    retval += ' ';
    retval += namesArr[l];
    return retval;
}
​

是否有可能以某种方式扩展它以捕捉他们回答的哪组问题?HTML 表有 3 个标签来标识每个组:

<tbody class="groupA">
4

3 回答 3

1

您可以通过检查检查输入的数量是否是输入数量的一半来生成它们。

$('tbody[class^=group]').each(function (i, val) {
  if ($('input:checked', val).length == $('input', val).length / 2) {
    console.log($(val).attr('class'));
  }
});
于 2012-11-30T01:18:26.900 回答
1

我希望你没有嫁给你的代码:)

这有点难以理解,所以我只是制作了一个原型,希望你可以遵循它并且应该允许你做你正在寻找的事情:将答案限制为特定形式。我还进行了一些简单的验证,以确保完整填写表单并在表单无效时关闭按钮。现在看代码:

HTML

<h2>Table A</h2>
<table id="tableA" border="1">
    <tr>
        <td>
            A1
        </td>
        <td>
            <input type="radio" name="a1" value="1" /> Yes
            <input type="radio" name="a1" value="0" /> No
        </td>
    </tr>
    <tr>
        <td>
            A2
        </td>
        <td>
            <input type="radio" name="a2" value="1" /> Yes
            <input type="radio" name="a2" value="0" /> No
        </td>
    </tr>
    <tr>
        <td>
            A3
        </td>
        <td>
            <input type="radio" name="a3" value="1" /> Yes
            <input type="radio" name="a3" value="0" /> No
        </td>
    </tr>
</table>

<h2>Table B</h2>
<table id="tableB" border="1">
    <tr>
        <td>
            B1
        </td>
        <td>
            <input type="radio" name="b1" value="1" /> Yes
            <input type="radio" name="b1" value="0" /> No
        </td>
    </tr>
    <tr>
        <td>
            B2
        </td>
        <td>
            <input type="radio" name="b2" value="1" /> Yes
            <input type="radio" name="b2" value="0" /> No
        </td>
    </tr>
    <tr>
        <td>
            B3
        </td>
        <td>
            <input type="radio" name="b3" value="1" /> Yes
            <input type="radio" name="b3" value="0" /> No
        </td>
    </tr>
</table>

<p>
    <button id="submit">Submit</button>
    <button id="reset">Reset</button>
</p>

<input type="hidden" id="activeTable" />

JS

window.ns = {};
ns.activeTable = null;
ns.validate = function() {
    // Simple validation
    // If we don't have 3 checked radio buttons, it is invalid
    var checked = $("#" + ns.activeTable).find("input[type=radio]:checked");
    var valid = (checked || []).length === 3;
    $("#submit").prop("disabled", !valid);
    return valid;
};

ns.validate();

$("#submit").click(function() {
    var valid = ns.validate;
    if (valid == false) {
        alert("You must complete the form!");
        return;
    }

    var results = $("#" + ns.activeTable).find("input[type=radio]:checked");
    var output = ns.activeTable + " Results\n";
    $.each(results, function(idx, data) {
        output += "\t" + $(this).prop("name") + 
            " - " + $(this).val() + "\n";
    });
    alert(output);
    $("#activeTable").val(ns.activeTable);
});

$("#reset").click(function() {
    $("input[type=radio]").prop("checked", false);
    ns.activeTable = null;
    ns.validate();
});

$("input[type=radio]").click(function() {
    var selectedTable = $(this).closest("table");
    if (ns.activeTable != null && 
        selectedTable.prop("id") != ns.activeTable) {
        alert("Invalid form selection. Onlye selections from " + 
              ns.activeTable + " are allowed");
        $(this).prop("checked", false);
    } else {
        ns.activeTable = selectedTable.prop("id");
    }
    ns.validate();
});​

​<strong>CSS

不需要,只是想让它看起来不错:)

html { margin: 10px; }
table { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
table td { border: 3px solid #CCC; padding: 5px; }
table td:nth-child(1) { width: 75%; }
table td:nth-child(2) { text-align: center; }
h2 { font-size: 1.8em; font-weight; bold }
button { padding: 5px; border-radius: 15px; background-color: #CCC; 
         width: 100px; }​

最后,看看它的实际效果:jsFiddle

我正在使用表 id 来确定哪个表单是“活动的”并存储该值。这就是我可以限制用户必须使用哪种形式的方法。

验证很简单:它只是确保为当前表单选中了 3 个复选框。这适用于示例,但除非每个表单的问题数量相同,否则您会想要更强大的东西。

验证还控制何时启用提交按钮。还有一个重置按钮可以清除单选按钮的值,以便您再次尝试。

希望这证明有用如果没有,我仍然玩得很开心:)

编辑

男孩,我是一个吸毒者吗?我完全没有放入隐藏字段并设置被问到的问题的值!这种“疏忽”已得到纠正。另外,只是为了表明该值是在提交时设置的:

隐藏字段值已设置

于 2012-11-30T02:05:32.613 回答
0

I can suggest a few changes to make it more readable, first, what does "namesComaDelimited" do? can't you just use javascript's join method? http://www.w3schools.com/jsref/jsref_join.asp

for your question, this gives to the class of the section touched:

$(sectionsTouched[0]).attr('class')

for the validation about the inputs being checked I would just compare the :checked length against the inputs length

sectionTouched = $(sectionsTouched[0]);
if (sectionTouched.find('input').length/2 != sectionTouched.find('input:checked')) {
  errorMessage = 'It appears you have not completed all questions.';
}

just a few, you can do a more optimizations

于 2012-11-30T01:24:22.277 回答