jQuery - Applying css style to input element

23,860

Solution 1

Couple things wrong. You didn't include the () on the call to $(this).val, and your this reference within the callback doesn't refer to the element intended.

function CheckLinks(){
  $('#new_post_links_table tbody > tr')
    .find("input")
    .each(function(index, element) {
      UrlExists($(this).val(), function(status){
        if(status === 404) $(element).css('background-color','#FC0');
      }); 
    });
}

Keep in mind when doing this you might run into some snags with Access-Control-Allow-Origin.

You might want to modify your UrlExists function to run through a proxy script on your server. You could do something like the following:

$.getJSON('checklink.php', { location: url }, function ( data ) {
  callback.apply( null, data.status );
});

On your backend, test the URL and send out the response via JSON:

$response = array( 
  'location' => $location, 
  'status' => $status 
);
echo json_encode( $response );

This way your JavaScript communicates with your back-end, and has no problem with origin control.

Solution 2

My feeling is that this is no longer referring to the input. You should add a variable to store the input so you can access it within closure

var input = $(this);
UrlExists($(this).val(), function(status){
  if(status === 404){
     input.css('background-color','#FC0');
  }
});
Share:
23,860
xperator
Author by

xperator

I like this quote the most and I'd love to live up to it : "If you don't build your own dream, Someone else will hire you to build their"

Updated on May 03, 2020

Comments

  • xperator
    xperator about 4 years

    I am trying to check all links and change the background color of broken links field. Here is my function

    function CheckLinks(){
    $('#new_post_links_table tbody>tr').find("input").each(function() {
        UrlExists($(this).val(), function(status){
        if(status === 404){
           $(this).css('background-color','#FC0');
        }
    }); });}
    

    Input fields looks like this :

    <table id="new_post_links_table">
    ...
    <td><input type="text" name="mp3_link[]"/></td>
    <td><input type="text" name="mp4_link[]"/></td>
    </tr>
    </tbody>
    </table>
    

    For some reason the css is not applying.

    Note: my CheckLinks function does work, except the $(this).css... part. (FireBug'ed)

    Note: The rows are added dynamically

    EDIT : Here is the function:

    function UrlExists(url, cb){
        jQuery.ajax({
            url:      url,
            dataType: 'text',
            type:     'GET',
            complete:  function(xhr){
                if(typeof cb === 'function')
                   cb.apply(this, [xhr.status]);
            }
        });
    }