Ali reza Soleimani Asl
Ali reza Soleimani Asl

Reputation: 167

ASP.NET MVC : Change input text value with jQuery

I have a Bootstrap modal that shows the images of Gallery, when you click on it. I want change input value by clicking on each image and put their Url on input text for submit . But it doesn't work and value of input text doesn't change . Why?

    @model IEnumerable<tourism.Models.Gallery>

    <input type="text" name="imgUrl" id="index-img" style="width: 100%;" value="url" />

 <div class="container">
    <!-- Trigger the modal with a button -->
    <button type="button" class="btn btn-info btn-lg" id="myBtn">Choose Image</button>

    <!-- Modal -->
    <div class="modal fade" id="myModal" role="dialog">
        <div class="modal-dialog modal-lg">

            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Gallery</h4>
                </div>
                <div class="modal-body">

                    <div class="row">

                        @foreach (var item in Model)
                        {
                            <div class="col-lg-2 col-sm-3 col-xs-4">
                                <a href="#" onclick="(function () {    ('input[name=imgUrl]').val()[email protected](modelItem => item.Url); })()" class="close" data-dismiss="modal"><img src="@Html.DisplayFor(modelItem => item.Url)" class="thumbnail img-responsive" alt="@Html.DisplayFor(modelItem => item.Alt)"></a>
                            </div>
                        }

                    </div>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>

        </div>
    </div>

</div>

jQuery code for passing Url from model to input text(from above code) :

<a href="#" onclick="(function () {    ('input[name=imgUrl]').val()[email protected](modelItem => item.Url); })()" class="close" data-dismiss="modal"><img src="@Html.DisplayFor(modelItem => item.Url)" class="thumbnail img-responsive" alt="@Html.DisplayFor(modelItem => item.Alt)"></a>

Upvotes: 3

Views: 2779

Answers (1)

user3559349
user3559349

Reputation:

Change the link to add a data- value for the items url (remove your onclick=...)

<a href="#" data-url="@item.Url" class="image" .... >

and then add the script to handle the click event of the link to update the input

$('.image').click(function() {
  $('#index-img').val($(this).data('url'));
});

Upvotes: 3

Related Questions