简体   繁体   中英

How to differentiate between an empty string and non-existing value?

When I have an HTML like this:

<input type="text" id="a" value="" />
<input type="text" id="b" />

If I do a $("#a").val() I cannot distinguish if exists a value and this is empty or if no value exists. Is there any way to distinguish these two cases?

Yes, you can check for the existence of the value attribute.

$('#a[value]') this means to find the element with id a that also has an attribute value

If you want to check after you have selected the element, if it has a value attribute then

var elem = $('#a');
if ( elem.is('[value]') ) {
  // it has a value attribute
}

You can use this:

$( '#a' ).is( '[value]' ) // true
$( '#b' ).is( '[value]' ) // false

Live demo: http://jsfiddle.net/simevidas/w8gFF/1/

Older versions of IE don't support hasAttribute , and as Šime Vidas discovered even jQuery can't be trusted on those browsers.

The way I had to do it when I needed something similar in an older version of IE was:

function hasAttribute(el, attr) {   
    if ("hasAttribute" in el)
        return el.hasAttribute(attr);

    else if ("outerHTML" in el) {
        return (el.outerHTML
                   // remove content
                   .replace(el.innerHTML, "")
                   // remove attribute values with quotes
                   .replace(/=(?:(["'])[^\1]*\1)?/, " ")
                   // remove attribute values without quotes
                   .replace(/=[^\s>]+/, "")
                   // normalize
                   .toLowerCase()
                   // search for attribute
                   .indexOf(" " + attr.toLowerCase()) > -1);
    }
}

In your case, you might use this function like so:

var hasValue = hasAttribute($("a")[0], "value");

Unfortunately, this still isn't very robust in Internet Explorer 8 and lower. False positives and negatives will be returned in those browsers for various attributes and, unfortunately, I don't believe there's a workaround.

It's good question, but I think you will not get any workaround in IE8 or early . I think so after some experiments which I made. By the way one can make the experiments with the IE9 or IE10 beta which one has installed. One should just uses meta "X-UA-Compatible" to change the Document Compatibility Mode (see here ).

I tested with:

document.getElementById("a").outerHTML = "<input type='text' id='a' value='' />";
alert(document.getElementById("a").outerHTML);

and the alert(document.getElementById("a").outerHTML) only:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=7" />
</head>

<body>
    <fieldset><input type="text" id="a" value="" /></fieldset>
    <script type="text/javascript">
    //<![CDATA[
        //document.getElementById("a").outerHTML = '<input type="text" id="a" value="" />';
        alert('In IE7 outerHTML for <input type="text" id="a" value="" />:\n' +
            document.getElementById("a").outerHTML);
    //]]>
    </script>
</body>
</html>

In case of "IE=8" the code above displays the text "<INPUT id=a type=text>" . If we would change the value of "X-UA-Compatible" to "IE=7" we will see even "<INPUT id=a"> . The same code with "IE=edge" displays <input id="a" value="" type="text"> . The corresponding demos are here: IE=edge , IE=8 , IE=7 .

So it seems that IE do some kind of "optimization" during parsing of HTML. The order and the case of attributes which will be get by outerHTML is different as in original code. IE parse HTML code with "optimization" and what we see later has no more value="" . So no tricks of jQuery can help us to get no more existing attribute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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