简体   繁体   English

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

[英]Toggle disabled attribute if select box option has value

I have a submit button that's disabled by default and has a grayed out image in the src attribute. 我有一个默认情况下处于禁用状态的提交按钮,并且src属性中的图像为灰色。

Here's the HTML: 这是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>

By default, the user must select the country. 默认情况下,用户必须选择国家。 When a country is selected that has a value, I'd like to update the image and remove the disabled attribute as long as the value of the dropdown option isn't blank. 选择具有值的国家/地区后,只要下拉选项的值不为空,我想更新图像并删除禁用的属性。

Here's the jQuery I've come up with so far but it needs to toggle the disabled attribute based on the value of the select item_location select box. 到目前为止,这是我想到的jQuery,但它需要根据select item_location选择框的值来切换Disabled属性。

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");     
        });
    });
}

You can do this: 你可以这样做:

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

This will disable the submit , in case the item_location value is empty, else enabled. 如果item_location值为空,则将禁用submit ,否则将启用。

UPDATE UPDATE

// 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';
});

use .val() to get selected value of drop-down list 使用.val()获取下拉列表的选定值

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

or better use .prop() 或更好地使用.prop()

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

Read .prop() vs .attr() 阅读.prop()与.attr()


Updated after OP's comment OP评论后更新

 jQuery(".submit").prop("src", "http://www.paypalobjects.com/en_US/i/btn/btn_buynow_LG.gif"); 

Try this. 尝试这个。

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"); 
    }

})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM