最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I check if value is empty? - Stack Overflow

programmeradmin1浏览0评论

I have a few select menus that include blank options. When both are blank (usually on the first page load), I would like to show some hidden div.

This is what I have:

$('.variant_options select').each(function() { 
    if ($(this).attr('value') === '') {
        // some code here to show hidden div
        console.log("No options chosen");
    }
});

This doesn't seem to work.

Edit 1

For what it's worth, I have tried something like this:

if (!$(this).attr('value'))

And that has seemed to work, but it breaks functionality elsewhere.

I have a few select menus that include blank options. When both are blank (usually on the first page load), I would like to show some hidden div.

This is what I have:

$('.variant_options select').each(function() { 
    if ($(this).attr('value') === '') {
        // some code here to show hidden div
        console.log("No options chosen");
    }
});

This doesn't seem to work.

Edit 1

For what it's worth, I have tried something like this:

if (!$(this).attr('value'))

And that has seemed to work, but it breaks functionality elsewhere.

Share Improve this question edited Aug 7, 2021 at 14:29 HoRn 1,5185 gold badges20 silver badges28 bronze badges asked Mar 26, 2013 at 10:34 marcamillionmarcamillion 33.8k57 gold badges199 silver badges393 bronze badges 3
  • 1 if ($(this).val() === '') {? – BenM Commented Mar 26, 2013 at 10:36
  • if ($(this).prop('value') === '') or just if (!this.value) – Bergi Commented Mar 26, 2013 at 10:39
  • What's with all the downvotes? – marcamillion Commented Mar 26, 2013 at 10:48
Add a ment  | 

5 Answers 5

Reset to default 5

<select> elements don't have a value attribute, so you need to use .val() on the element to find out if the currently selected option is empty.

if ($(this).val() === '') {
    // value of select box is empty
}

this.value === '' should also work

To check whether no options are selected:

if (this.selectedIndex == 0) {
    // no option is selected
}

You can do so by using the following:

if($(this).val() === '') {
  // value is empty
}

I believe also the following too:

if(!$(this).prop('value')) { 
  // It's empty 
}

You can simply do this:

$('.variant_options select').each(function () {
    if ($.trim($(this).val()) === '') {
        // some code here...
    }
});

jQuery can check for value by using $(this).val()

So you would do if ($(this).val === '')`

If you wanted to check for some other attribute, like href or src, you could do

if ($(this).attr('href') === ''

In case if you have spaces, use this trick:

if ($.trim($(this).val()) === '') { ...
发布评论

评论列表(0)

  1. 暂无评论