如果选择框选项具有值,则切换禁用的属性

Toggle disabled attribute if select box option has value

本文关键字:属性 选择 选项 如果      更新时间:2023-09-26

我有一个默认禁用的提交按钮,并且在 src 属性中有一个灰色的图像。

这是 HTML:

<form>
<select id="item_location">
    <option value="">- Choose Destination -</option>
    <option value="US">US</option>
    <option value="CN">Canada</option>
    <option value="IN">International</option>
</select>
<input class="submit" type="image" src="http://website.com/images/btn_buynow_LG--disabled.png" border="0" name="submit" disabled>
</form>

默认情况下,用户必须选择国家/地区。当选择具有值的国家/地区时,只要下拉选项的值不为空,我想更新图像并删除禁用的属性。

这是我到目前为止想出的jQuery,但它需要根据选择item_location选择框的值切换禁用的属性。

function submitButton() {
    jQuery(".submit").change(function() {
        if (jQuery("#item_location") !== "" {
            jQuery(".submit").attr("src", "http://www.paypalobjects.com/en_US/i/btn/btn_buynow_LG.gif").removeAttr("disabled");     
        });
    });
}

你可以这样做:

jQuery(".submit").prop("disabled", jQuery("#item_location").val() === "")

这将禁用submit,如果item_location值为空,否则启用。

更新

// Cache the submit button
var $submit = jQuery(".submit");
// Disable the button based on the dropdown value
$submit.prop("disabled", jQuery("#item_location").val() === "");
// Change the src image, based on disabled attribute of submit button
$submit.prop("src", function (i, val) {
    return $submit.prop("disabled") ? 'old_image_src' : 'new_image_src';
});

使用.val()获取下拉列表的选定值

if (jQuery("#item_location").val() !== "") {
                             ^           ^ //added ) here

或者更好地使用 .prop()

jQuery(".submit").prop("disabled", jQuery("#item_location").val() === "")

Read .prop() vs .attr()


OP评论后更新
jQuery(".submit").prop("src", "http://www.paypalobjects.com/en_US/i/btn/btn_buynow_LG.gif");

试试这个。

jQuery("#item_location").change(function() {
    if (this.value) {
        jQuery(".submit").prop("src", "http://www.paypalobjects.com/en_US/i/btn/btn_buynow_LG.gif").removeAttr("disabled"); 
    }
})