0

How can I pass a jQuery selector to this function? It works fine this way:

$("input[name='this_field']").blur(function() {
    var text = $(this).val();
    if ( $("#repeat").val('') ) {
        $("#repeat").val(text);
    };
});

But when I try it this way;

function repopulateFields(target){
    var text = $(this).val();
    if ( $(target).val('') ) {
        $(target).val(text);
    };
}
$("input[name='this_field']").blur(function() {
    repopulateFields("#repeat");
});

It doesn't work and throws an error. What's wrong here?

yerme
  • 810
  • 5
  • 15

3 Answers3

2

It fails because this in function repopulateFields() is reference to function repopulateFields(), not element anymore. You have to pass this from blur() listener too. I've named it that.

function repopulateFields(that, target) { 
   // use `that`
   var text = $(that).val();
   if ($(target).val('') ) {
       $(target).val(text);
   };
}
$("input[name='this_field']").blur(function() {
   repopulateFields(this, "#repeat"); // pass `this`
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="this_field"/>
<input id="repeat"/>
Jax-p
  • 7,225
  • 4
  • 28
  • 58
1

You should be very carefull with this reference scope.

function repopulateFields(el, target){
    var text = $(this).val();
    if ( $(target).val('') ) {
        $(target).val(text);
    }
}
$("input[name='this_field']").blur(function() {
    repopulateFields(this, "#repeat");
});
Giga Kokaia
  • 879
  • 8
  • 15
0

What is wrong is that $(this) in the function repopulateFields() has no declaration, you need to set $("input[name='this_field']") explicitly:

function repopulateFields(target) {
  var text = $("input[name='this_field']").val();
  if ($(target).val('')) {
    $(target).val(text);
  };
}
$("input[name='this_field']").blur(function() {
  repopulateFields("#repeat");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="this_field" />
<input id="repeat"/>
matthias_h
  • 11,356
  • 9
  • 22
  • 40