在表单提交(JQuery)上将select元素设置为禁用

时间:2018-06-12 14:13:24

标签: javascript php jquery html

我有一个回送多个<select>元素的php循环作为在线订购系统的一部分,用户可以在其中选择某个项目的数量。

执行表单的按钮运行一个php脚本,将值插入我的数据库,但是,我需要能够忽略等于&#34; 0&#34;的值。

通过在提交按钮上创建onClick事件(JS函数),我执行以下代码:

$('#quantityForm').find(':select').each(function(){
    if($(this).val() == "0"){
        $(this).attr('disabled', 'disabled');
    }
})

除了将<select>元素设置为禁用的代码之外,一切似乎都能正常工作,因为我的php脚本会尝试获取所有&#34; 0&#34;值。

我做错了吗?

附加代码:

<form id="quantityForm" method="get">
    <?php get_items($example); ?>
    <button onClick="checkQuantity()" id='basket' type='submit' name='submit'><i class='fas fa-shopping-basket'></i></button>
</form>

2 个答案:

答案 0 :(得分:1)

$('#quantityForm')
    //find all the select elements in the form
    .find('select')
    //filter and return only those that have a value of 0
    .filter(function(){
        return this.value === '0';
    })
    //make them disabled
    .prop('disabled', true);

答案 1 :(得分:0)

当选择name选项时,您可以删除选择的value="0"属性,这样您的表单就会忽略选择输入。

$(document).on('change', 'select', function() {
    if ($(this).val() == 0) {
        $(this).attr('name', '');
    }
    else {
        $(this).attr('name', '<name>');
    }
});