简体   繁体   中英

How to pass data value from Bootstrap Modal to Parent form

How to pass data attribute or click event from Bootstrap modal to parent form/window.

for example, On clicking the below input box, the modal will popup with divs having data attribute

<input type="text" name="menu_image_id" class="form-control" data-toggle="modal" data-target=".show_modal_w" />

<input type="text" name="menu_image_id_2" class="form-control" data-toggle="modal" data-target=".show_modal_w" />

Modal window

<div class="modal fade show_modal_w" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div data-id="1"  data-dismiss="modal">Hello</div>
        <div data-id="2"  data-dismiss="modal">Welcome</div>
        <div data-id="3"  data-dismiss="modal">Morning</div>
    </div>
</div>

Now when the user clicks the div inside the modal for example either Hello, Welcome or Morning, then we need to pass the id value from modal to parent input box with name menu_image_id.

I tried using the below close function, but not able to get the modal data id to parent window.

$('.show_modal_w').on('hidden.bs.modal', function (e) {
    $(e.relatedTarget);
})

I'm trying a different way than you did,

instead of capturing the hidden.bs.modal, I'm capturing the div.on.click, so instead of:

$('.show_modal_w').on('hidden.bs.modal', function (e) {
    $(e.relatedTarget);
})

I wrote

$("body").on("click", ".show_modal_w div[data-id]", function() {
    $("input[name='menu_image_id']").val($(this).data("id") + " - " + $(this).text());
    $(".show_modal_w").modal("hide");
});

And here is a jsfiddle: https://jsfiddle.net/f9urohoo/ I put the id and the text of the div clicked in the input with [name="menu_image_id"] but you can adapt that as you wish.

Tell me if it is what you wanted

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM