Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery val not working properly in Chrome

I have a simple jQuery function:

$('#selectable1 span').live('mousedown', function() {
        var ff = $(this).css("font-family");
        $("#family").val(ff);
});

When a span element is clicked (mousedown) an input (#family) gets its font family value. It works in FireFox but in Chrome it works only for font families composed from only one word. Georgia will work but Times New Roman will not.

You can see the code here:

http://jsfiddle.net/aLaGa/

or live at http://www.typefolly.com

What is wrong with this? Thanx

like image 582
Mircea Avatar asked May 27 '10 10:05

Mircea


2 Answers

Chrome wraps font families having multiple words with single quotes. So the value for font-family returned in Chrome is: 'Times New Roman' which does not match the value in the select list Times New Roman.

Considering all these browser variations, I think the best solution is to split apart the family names by comma, trim the single quote (if any) around each font name, and join them later. Use this sanitized value inside the select list.

$('#selectable1 span').live('mousedown', function() {
    var fontFamily = $(this).css('font-family');

    var fonts = fontFamily.split(',');
    var sanitizedFonts = $.map(fonts, function(name) {
        // trim single quotes around font name (if any) for Chrome/Safari
        // trim double quotes around font name (if any) for Firefox
        return name.trim().replace(/^['"]|['"]$/g, '');
    });

    $('#family').val(sanitizedFonts.join(', '));
});

See an example. The select list had to be changed to follow this consistent naming scheme for values:

fontName[, fontName]

This heavily relies on the fact that a font-name will not contain any commas, quoted or unquoted.

like image 68
Anurag Avatar answered Oct 20 '22 07:10

Anurag


You can change your script slightly to replace the quotes that WebKit adds when the font name contains spaces, like this:

$('#selectable1 span').live('mousedown', function() {
  var ff = $(this).css("font-family").replace(/\'/g,"");
  $("#family").val(ff);
});    ​

You can see a working demo here :)

And here's a RegEx approach pulling the literal value out of style that's probably easier than anything, but I'm not a RegEx guru, someone feel free to improve this and update the answer (I suck at RegEx, sorry!) This works for all examples you have.

like image 21
Nick Craver Avatar answered Oct 20 '22 07:10

Nick Craver