AJFMEDIA
AJFMEDIA

Reputation: 2123

Unable to pass string in to jquery function

I wish to grab the current value of a search input and then clear the input box on focus, store the string and pass it into a function to re-populate the input box on blur.

$("input#search").bind('focus', function() {
    var search_text = document.getElementById('search').value;
    $("input#search").val("");
}).bind('blur', function(search_text) {
    $("input#search").val(search_text);
});

Currently, this successfully grabs the value on focus and clears the input box, but on blur, it populates the input with [object Object].

Am I correctly passing the string on line 4?

Upvotes: 1

Views: 1055

Answers (3)

user2345
user2345

Reputation: 3227

No. Here is how you would do, declaring the variable before the event listeners so that it's in the scope:

var search_text;
$("input#search").bind('focus', function() {
    search_text = document.getElementById('search').value;
   $("input#search").val("");
}).bind('blur', function() {
   $("input#search").val(search_text);
});

The convention in JavaScript for naming variables in Camel Case, so you would rather use searchText (not that it really matters).

Upvotes: 0

ScanQR
ScanQR

Reputation: 3820

Use .on() of jQuery to register event.

var search_text;
$("input#search").on('focus', function() {
   search_text = document.getElementById('search').value;
   $("input#search").val("");
});

$("input#search").on('blur', function() {
   $("input#search").val(search_text);
});

Alternate could be ,

$("input#search").on('focus', function() {
   var search_text = document.getElementById('search').value;
   $("input#search").val("");

   $(this).on('blur', function() {
     $("input#search").val(search_text);
   });
});

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

Firstly, don't use bind(). It was deprecated a long time ago. Use on() instead.

With regard to your issue, you can't directly pass a parameter to the anonymous handler function in the manner you're attempting. As it stands your search_text variable will hold the blur event.

To fix this you could store the variable in a data attribute on the #search element itself. Try this:

$("input#search").on('focus', function() {
  $(this).data('search-text', this.value).val('');
}).on('blur', function(search_text) {
  $(this).val($(this).data('search-text'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="search" value="foo bar" />

Also, the behaviour you're creating here is similar to the placeholder attribute. It may be worth investigating that to see if it meets your needs.

Upvotes: 2

Related Questions