1

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?

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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);
   });
});

1 Comment

While this may work, I'd suggest avoiding global variables where possible.
0

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).

1 Comment

Though this still has a global variable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.