0

我有几个带有表单元素的表格 - 所有这些元素都作为单个表单提交并进行解析。我想添加一些验证,对 .submit() 参数使用 jQuery。

我在网上找到了一些代码,但是这些会产生错误消息,我想知道是否有人知道任何可以执行以下操作的示例代码:

On .submit()
if textBox1 = ""
    then replace empty textBox1 with "1"
else if textBox2 = ""
    then replace empty textBox2 with "-1"
and continue to submit the form
4

3 回答 3

1
var textBoxDefaultValues = {
    textBox1 : '1',
    textBox2 : '-1' 
};

$(formSelector).on('submit', function () {
    $(this).find('input[type="text"]').each(function() {
        if($(this).val() == '') {
            $(this).val(textBoxDefaultValues[$(this).attr('name')]);
        }
    });
    return true;
});
于 2013-05-30T06:58:19.513 回答
1

这是另一个解决方案:

$("#myForm").submit(function() {
  if $(this).find("input[type='text']").each(function() {
    if $(this).val() == "") $(this).val("1");
    if $(this).val() == "..") $(this).val("-1");
  });
});

这个解决方案可能更直接/更容易理解。如果您有很多输入,Atber 的解决方案可能会更合适。

于 2013-05-30T07:05:37.447 回答
1

您的伪代码准确翻译:

$("form").submit(function() {
    if ($('input[name="textBox1"]').val() == "") {
        $('input[name="textBox1"]').val("1");
    } elseif ($('input[name="textBox2"]') == "") {
        $('input[name="textBox2"]').val("-1");
    }
});

编辑:

如果出于某种原因,您需要name跨多个输入复制属性,则可以id改为按属性定位输入:

// HTML form
<input type="text" name="textBox1" id="foo" />
<input type="text" name="textBox1" id="bar" />

// Javascript
$("form").submit(function() {
    if ($('input[id="foo"]').val() == "") {
        $('input[id="foo"]').val("1");
    } elseif ($('input[id="bar"]') == "") {
        $('input[id="bar"]').val("-1");
    }
});
于 2013-05-30T07:08:59.843 回答