Hassan
Hassan

Reputation: 2843

jQuery - Applying css style to input element

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]);
        }
    });
}

Upvotes: 2

Views: 28231

Answers (3)

Sampson
Sampson

Reputation: 268344

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.

Upvotes: 4

Rob
Rob

Reputation: 570

Does that function know that there are added rows dynamically? While ago I've had similar issue. Problem was that jQuery didn't know that there are added new rows with some content. Try console out what is under $(this) in function and tell us what result have You get.

Upvotes: 0

Pete Lada
Pete Lada

Reputation: 1318

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');
  }
});

Upvotes: 2

Related Questions