在jQuery中成功后更改数字字段属性“max”值

时间:2018-02-08 09:34:30

标签: javascript php jquery ajax wordpress

我还在学习jQuery。

我有这样的表格:

<form class="simple-checkout" enctype="multipart/form-data" method="POST" action="<?php echo admin_url('admin-ajax.php'); ?>">
    <input type="hidden" name="add-to-cart" value="<?php echo htmlspecialchars($getid); ?>"/>
    <input type="number" name="quantity" min="1" max=<?= $available_stock ?> value="1"/>
    <input type="hidden" id="thwepof_product_fields" name="thwepof_product_fields" value="order_date">
    <input type="hidden" id="order_date" name="order_date" value="<?php echo htmlspecialchars($get_day); ?>">
    <input type="hidden" name="action" value="create_ajax_checkout"/>
    <input type="submit" value="Add to cart"/>
</form>

我将此添加到此功能:

add_action('wp_ajax_create_ajax_checkout', 'create_ajax_checkout');
function create_ajax_checkout()
{
wp_send_json_success($_POST);
}

并使用此js文件来处理Ajax请求:

jQuery(document).ready(function ($) {
$('.simple-checkout').ajaxForm({
    success: function (response) {
        console.log(response);
        //alert("Success");

    },
    error: function (response) {
        console.log(response);
        alert("Error!");
        }
    });
});

我的问题是$_POST['quantity']有一个max=<?= $available_stock ?>。我想按照$_POST['quantity']的数量减少默认最大值。

因此,如果默认数量为30,并且您向购物车添加了2件,那么我想将最大可用值设置为28。

3 个答案:

答案 0 :(得分:0)

为您的字段提供ID(例如&#34; myField&#34;),然后更改属性值,如下所示:

$('#myField').attr('max', '28');

要获得您的字段的价值,请不要传递第二个参数:

var myFieldVar = $('#myField').attr('max');

答案 1 :(得分:0)

您可以使用成功函数中的代码来设置它

$("input[type='number']").attr('max',response.quantity);

答案 2 :(得分:0)

获取当前值

var currentValue = $('#idOfNumberField').attr('max');

使用新值更新:

$('#idOfNumberField').attr('max', newValue);