Pravayest Pravayest Pravayest Pravayest - 3 months ago 10
jQuery Question

get input value and if statement

I have input field and I want to get input value when input loses focus ( if input is empty ) or just get input value ( if input isn't empty )

My input

<input type="text" id="title" value="Value test" kl_virtual_keyboard_secure_input="on">


And I try

var input_length=$.trim($("#title").val());

function blurTitleValue() {
$('#title').blur(function() {
var str = $.trim($("#title").val());
var str_ref = str.substring(0,3);
return str_ref;
});
}
function TitleValue() {
var str = $.trim($("#title").val());;
var str_ref = str.substring(0,3);
return str_ref;
}
if(input_length.length>0)
{
TitleValue();
}
else{
blurTitleValue();
}
alert(str_ref);


But I can't get str_ref value

Answer

If you return str_def you are not setting variable str_def of parent scope to its value, you are just losing your value because you didn't asign it to anything. You need to save returned value to your variable. Try it on JSFiddle.

var input_length = $.trim($("#title").val());
var str_ref;

function blurTitleValue() {
  return $('#title').blur(function() {
    var str = $.trim($("#title").val());
    var str_ref1 = str.substring(0, 3);
    str_ref = str_ref1;
  });
}

function TitleValue() {
  var str = $.trim($("#title").val());;
  var str_ref1 = str.substring(0, 3);
  return str_ref1;
}
if(input_length.length > 0) {
  str_ref = TitleValue();
} else {
  blurTitleValue();
}
alert(str_ref);