Tony D. Tony D. - 2 months ago 10
jQuery Question

asp.net mvc - pass text box value to a hidden value with jquery

I need to pass the value of a text box to a hidden field. I am currently setting a default value to the field, but the user may change it before the submitting of the form. I thought this could be accomplished with jquery, but I feel I am missing a piece here:

$(document).ready(function () {
$(function () {
var value = $("#myTextBoxVal").val();
$('#myHiddenFieldVal').val(value);
});
});


The above provides me with the default value only. But as I mentioned above, I need the value that exists when the form submits, either the default or the user input.

Any thoughts?

Answer

You can use change event like following.

$(document).ready(function () {
    $("#myTextBoxVal").change(function() {
        $('#myHiddenFieldVal').val(this.value);
    }).change();
});