0

Basically, I am trying to use a data attribute from a input text element to set a default value:

$('.fontsizepick').val($("#preview-iframe").contents().find($(this).data('obj')).css('font-size'));

The goal is to get the font size from another element and give it as a value to this input text element. There can be many elements.

This does not work. It gives me no error either.

Here is How I did it with a select:

$(".fontpick option").filter(function() {
    //may want to use $.trim in here
    return $(this).text() == $("#preview-iframe").contents().find($(this).parent().data('obj')).css('font-family');
}).prop('selected', true);

So, I am wondering how I can set a element with a class and give it a value and use its own attributes, basically I want access to the $(this)...

How can I do that?

John Svensson
  • 461
  • 1
  • 5
  • 17

2 Answers2

0

jQuery's .val() can accept a function, whose context will be the input element, so you can use $(this).

$('.fontsizepick').val(function(){
    return $("#preview-iframe").contents().find($(this).data('obj')).css('font-size');
});

From the .val() docs:

A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.

MrCode
  • 63,975
  • 10
  • 90
  • 112
0

You need to use a function, so that $(this) will be set to the appropriate element.

$('.fontsizepick').val(function() {
    return $("#preview-iframe").contents().find($(this).data('obj')).css('font-size');
});
Barmar
  • 741,623
  • 53
  • 500
  • 612