Friday, March 2, 2012

How to compare space with jquery?

Compare the space we can use unicode to comparing it.
the space unicode is 32.
<b> </b>

The below code show how to compare the space use jquery.
if( $("b").html().charCodeAt() == 32 ) {}

Click below demo button will show the alert popup when find the li tag have space.

DEMO


  • Text1
  • Text2

  • Text3

Below is the source code:
<html>
<body>
<div class="demo">
<h2>DEMO</h2>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
function test(){
    $("li").each(function(e){
        if($(this).html().charCodeAt() == 32){
            alert("I have a space");
        }
    });
}
</script>
<ul> 
      <li>Text1</li>
      <li> </li>
      <li> </li>
      <li>Text2</li>
      <li></li>
      <li>Text3</li>
      <li>    </li>
</ul>
<button onclick="test();">Click Me</button>
</div>
</body>
</html>

Related Articles
jquery disable button

1 comment: