AJFMEDIA AJFMEDIA - 22 days ago 10
Javascript Question

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?

Answer

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.