simonkaspers1
simonkaspers1

Reputation: 626

Classes and this with a function

I have series of inputfields that i have given the class replaceInput. The point with this is to have a simple function that replace the value to empty when the user focus in the field and take it back to X if the field is empty on focus out.

My question is, is this a syntax-error or is it possible that when i moved the logic to a separat function this does not work with the class? If i just use the class, every value is empty every time.

HTML

<input id="goal" class="biggerFont replaceInput"  value="X" >

jQuery and javascript

$( ".replaceInput" ).focusin(function() {
        placeholderFix('X', '');

            //OLD  WORKING CODE
              /*if ($(this).val() == 'X') {
                $(this).val('');
              };*/
          });



function placeholderFix(oldValue, newValue){
  $(this).val() == oldValue ? $(this).val(newValue): $(this).val(oldValue);
}

Upvotes: 0

Views: 58

Answers (4)

Satpal
Satpal

Reputation: 133403

You can use bind()

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Code

$(".replaceInput").focusin(function () {
    placeholderFix.bind(this)('X', '');
});

function placeholderFix(oldValue, newValue) {
    $(this).val() == oldValue ? $(this).val(newValue) : $(this).val(oldValue);
}

Simplified DEMO

Upvotes: 2

Amit
Amit

Reputation: 3289

Replace this line of code

placeholderFix('X', '');

to

placeholderFix('X', '' , this);

so that this refers to input element.

Upvotes: 0

CodingIntrigue
CodingIntrigue

Reputation: 78525

You can use call to call your function with a custom this argument:

$( ".replaceInput" ).focusin(function() {
    placeholderFix.call(this, 'X', '');
});

function placeholderFix(oldValue, newValue){
    $(this).val() == oldValue ? $(this).val(newValue): $(this).val(oldValue);
}

Upvotes: 1

Anoop Joshi P
Anoop Joshi P

Reputation: 25527

You should pass that object to the new function. In placeholderFix method, this is not refering to the input element.

$( ".replaceInput" ).focusin(function() {
        placeholderFix('X', '',this);

            //OLD  WORKING CODE
              /*if ($(this).val() == 'X') {
                $(this).val('');
              };*/
          });



function placeholderFix(oldValue, newValue,obj){
  $(obj).val() == oldValue ? $(obj).val(newValue): $(obj).val(oldValue);
}

Upvotes: 3

Related Questions