user1592380
user1592380

Reputation: 36247

Javascript : function statement requires a name

I have a html table with a row that looks like:

<tr>
    <td><input type="checkbox" name="check[]" value="265"></td>   
                 <td>265</td>
                    <td>NO MATCH</td>
                    <td>NO MATCH</td>
                    <td>No</td>
                    <td>0</td>
                    <td>f79a8316891</td>
              </tr>

I am trying to build a jquery function that will highlight a cell only if it starts with "NO" . So far I have:

$( "td" ).hover( function() {
    var contents = $( this ).html() ;
    if (contents.match("^NO")) {
            function() {
            $( this ).append( $( "<span> ***</span>" ) );
            }, function() {
            $( this ).find( "span:last" ).remove();
            }
    }   


  });

But I'm getting the error in the title. What am I doing wrong?

Upvotes: 1

Views: 2126

Answers (2)

Moob
Moob

Reputation: 16184

There's no need to add and remove stuff on hover. Simply find all the cells that match your criteria (using jQuery's filter()) then give them a class. You can then style .nomatch elements as you see fit. Here I've added the triple-star text on hover as per your requirements.

$(function(){
  var key = "NO";
  var $cellsBeginWithNo = $("td").filter(function(){
    var $this = $(this);
    if($this.text().indexOf(key) === 0){ //if text begins with [key]
        $this.addClass("nomatch");       //give it a class
        return $this;                    //add it to our collection
    }
    return false;
  });
  /* 
    Now you have a jQuery collection of matched elements that you can apply further functions to if you like. EG: 
    $cellsBeginWithNo.on("click", function(){alert("click");});
  */
});
td.nomatch {
    background-color:#ffeeee;
}
td.nomatch:hover:after {
    content : " ***";
    color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
    <tr>
        <td><input type="checkbox" name="check[]" value="265"></td>   
        <td>265</td>
        <td>NO MATCH</td>
        <td>NO MATCH</td>
        <td>No</td>
        <td>0</td>
        <td>f79a8316891</td>
    </tr>
</table>

Upvotes: 2

rwacarter
rwacarter

Reputation: 2004

You have the functions in the wrong place. Try something like this:

$( "td" ).hover( function() {
    var contents = $( this ).html() ;
    if (contents.match("^NO")) {
        $( this ).append( $( "<span> ***</span>" ) );

    }   
}, function() {
        $( this ).find( "span:last" ).remove();
});

The jQuery hover function takes two functions as it's parameters, the first for 'mouse over' and the second for 'mouse out'. You simply put these functions in the wrong place in your original code. For more information on hover, see http://api.jquery.com/hover/

Upvotes: 5

Related Questions