JavaScript jQuery ternary or .val() operator issue

I have following code:

var result = $('#txtResult').val();
var input = $('#txtInput').val();
if (result == "0") {
  $('#txtResult').val($('#txtInput').val());
} else {
  $('#txtResult').val($('#txtResult').val());
}

When i have ” result== ‘0’ “ i want to change it with the input text box value and it works fine.

My question is why when i write it like this:

$('#txtResult').val($('#txtResult').val() == "0" ?  $('#txtResult').val($('#txtInput').val()) : $('#txtResult').val($('#txtResult').val()));

use ternary (question mark) operator the result text box and .val() from jQuery it shows me [object Object] on the result text box. If i try to debug it using f11 first it work fine, but without debugging doesn’t work fine.


solution

It’s because you’re setting a jQuery object as the value.

You could simplify it to:

var result = $('#txtResult').val();
$('#txtResult').val($(result == 0 ? '#txtInput' : '#txtResult').val());

As a side note, you should probably be parsing the value as a number so that you are comparing a number to 0 rather than a string.

var result = parseInt($('#txtResult').val(), 10);
$('#txtResult').val($(result === 0 ? '#txtInput' : '#txtResult').val());