Sagar Sagar - 1 month ago 8
Javascript Question

How to call a jQuery function when textbox is edited

In my code there is one text box which is disabled. when user click on edit pencil icon textbox is enabled for edit something. and when user edit the textbox it must check whether edited value is already exit or not. for that i have call checkOwnerId method. but there is no any call goes to that function.

This is my jQuery code

var parcel = $('#parcel_no').val();
$('#pin-edit').click(function () {
$('#owner_id_txt').removeAttr("disabled");
$("#pin-edit").hide();
$("#save-pin").show();
oldOwnerId = $('#owner_id_txt').val();
});
$('#save-pin').click(function () {
if ($("#owner_id_txt").val() == "") {
displayErrorMessage('Please enter owner Id');
$("#owner_id_txt").focus();
$('#owner_id_txt').val(oldOwnerId);
return;
}


$("#pin-edit").show();
$('#owner_id_txt').attr("disabled", true)
$("#save-pin").hide();
var data = { 'owner_id': $("#owner_id_txt").val(), 'parcel_no': parcel };
BlockUI();
var urlstring = "@Url.Content("~")Parcel/UpdateOwnerId";
$.post(urlstring, data, function (result) {
UnblockUI();
if (result.success == true) {
displaySuccessMessage('Owner Id updated successfully!');

}
else {
displayErrorMessage('There was an error while updating Owner Id!');
}
});

$('#owner_id_txt').change(function () {
//alert("Check Exist or Not");
var data = { 'owner_id': $("#owner_id_txt").val() };
var urlString = "@Url.Content("~")Parcel/CheckOwnerId";
urlString = sanitize_url_path(urlString);
$.post(urlString, data,
function (result) {
if (result) {
displayErrorMessage("Owner Id already exists");
$("#pin-edit").show();
$('#owner_id_txt').attr("disabled", true);
$("#save-pin").hide();
}
});
})
});

Answer

Your '$('#owner_id_txt').change(function () {' is called inside ' $('#save-pin').click(function () {' so its not getting called once you type the text box. Put the function outside of it, then it will check the value. Refer the below jsfiddle sample

code: JS

$(document).ready(function() {
   $('#pin-edit').click(function () {
      $('#owner_id_txt').removeAttr("disabled");
      $("#pin-edit").hide();
      $("#save-pin").show();
      oldOwnerId = $('#owner_id_txt').val();
   });
   $('#save-pin').click(function () {
      if ($("#owner_id_txt").val() == "") {
      $("#owner_id_txt").focus();
      $('#owner_id_txt').val(oldOwnerId);
      return;
      }
      $("#pin-edit").show();
      $('#owner_id_txt').attr("disabled", true)
      $("#save-pin").hide();
   });
   $('#owner_id_txt').change(function () {//alert("Check Exist or Not");
      console.log($(this).val());
   });
   $('#owner_id_txt').attr("disabled", true);
});

code: HTML

<input type="text" id="owner_id_txt" >
<div id="pin-edit">edit</div>
<div id="save-pin">save</div>

https://jsfiddle.net/pitchiahn/fr6gdeyd/