Jonas
Jonas

Reputation: 111

jQuery value of variable is [object Object]

If the form field is empty, the value of cityName should be displayed. The value should be displayed before the user types his own value in and if he deletes the input, the span should change back to the default value (in my case 'London' as string).

I was playing around with .prop('outerHTML') and $("#messageOutput")[0].outerHTML, but this didn't work and the output remains [object Object] after the users deleted his input. Before the first input in the form field, the span is empty.

var cityName = 'London';
console.log(cityName);
var messageVar = $('#messageInput').bind('input keyup', function() {
  if (messageVar.val().length == 0) {
    $('#messageOutput').text(cityName);
    console.log(cityName);
  } else {
    $('#messageOutput').text(this.value);
    cityName = messageVar;
    console.log(cityName);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="messageInput" />
<span id="messageOutput"></span>

Upvotes: 1

Views: 1105

Answers (1)

charlietfl
charlietfl

Reputation: 171669

The [object Object] is coming from cityName = messageVar;

In prior lines you use messageVar.val() to get the value but in that line you are assigning the whole jQuery object , not it's value, to cityName.

When you try to stringify an object you get "[object Object]" as output.

As for initial page load you can trigger one of the events to get the event handler to set the text.

Following is a bit more straightforward version that also does the initial event trigger. Note also that bind() is deprecated in favor of using on()

var cityName, originalCity = 'London';

$('#messageInput').on('input keyup', function() {
  const val = this.value.trim();
  // use input value if it has length or use the original
  cityName = !!val.length ? val : originalCity;
  
  $('#messageOutput').text(cityName);
  
  console.clear()
  console.log(cityName);

}).trigger('input')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="messageInput" />
<span id="messageOutput"></span>

Upvotes: 1

Related Questions