Reputation: 14161
My View code is as below where I am calling a javascript function on key up event. I want to pass the control value to javascript function. I tried using 'this' and @this, but it didn't work.
@Html.TextBoxFor(m => m.LeaveDetailsList[0].LeaveTaken, new {id = "numLeaveTaken1", width = "100", @onkeyup = "checkInp2(this);" })
** Edited ** Javascript code:
function checkInp2(ControlId) {
var x = document.getElementById(ControlID).value;
if (isNaN(x)) {
document.getElementById("btnSave").disabled = true;
return false;
}
else {
document.getElementById("btnSave").disabled = false;
}
}
Upvotes: 1
Views: 3474
Reputation: 6271
I figure your onkeyup
event should work (even though inline events is not really top of the best practice list now days), but not with the current function. Try changing it to:
function checkInp2(ControlId) {
var x = ControlId.value;
...
}
You're sending this
, referring to the element that triggered the event, to the function so there is no need to use getElementById
.
If you instead wanted to get the element explicitly by Id, you could use..
document.getElementById('numLeaveTaken1').value; //pure JavaScript
$('#numLeaveTaken1').val(); //jQuery
In this case you can skip this
all together.
Upvotes: 1
Reputation:
You should avoid polluting your mark-up with behavior and instead use Unobtrusive Javascript. Give the textboxes a class name
@Html.TextBoxFor(m => m.LeaveDetailsList[0].LeaveTaken, new { @class = "leave-taken" })
Then the script
var button = $('#btnSave'); // cache it
$('.leave-taken').keyup(function() {
if(isNaN($(this).val())) {
button.prop('disabled', true);
} else {
button.prop('disabled', false);
}
});
or it could be reduced to
$('.leave-taken').keyup(function() {
button.prop('disabled', !isNaN($(this).val()));
});
Note also the controls with can now be style with css - .leave-taken { width: 100px; }
Upvotes: 1