Monday 17 July 2017

MVC - jQuery - dynamically change width of textbox or EditorFor

Watch this example on YouTube
<iframe width="560" height="315" src="https://www.youtube.com/embed/FjX4YbTWMzE?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>

add ID to EditorFor
    @Html.EditorFor(model => model.CompanyName, new { htmlAttributes = new { @class = "form-control", @id="myText" } })

add this script
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")

    <script type="text/javascript">
        $(document).ready(function () {
            var textVal = $('#myText').val();
            $('#myText').css('width', ((textVal.length + 2) * 10).toString() + 'px');
        });     
    </script>
}

No comments:

Post a Comment