How to pass data value from Bootstrap Modal to Parent form - javascript

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

Related

Trouble getting index of class with jQuery

I have a few hidden modals on a page that I want to control with a single block of javascript code.
I'm trying to test to see if I'm getting the correct close button with class close, but my console.log is currently printing -1.
HTML
<span class="open">Button A</span>
<span class="open">Button B</span>
<!--modal-->
<div class="modal">
<!--modal content-->
<div class="modal-content">
<!--close button-->
<span class="close">×</span>
<!--content A-->
</div>
</div>
<!--modal-->
<div class="modal">
<!--modal content-->
<div class="modal-content">
<!--close button-->
<span class="close">×</span>
<!--content B-->
</div>
</div>
JS
$(document).ready( function() {
//when a class '.open' is clicked
$('.open').click(function(){
//store the index of the clicked span in a variable
var indexer = $('.open').index(this);
//test output - working
console.log("open. " + indexer);
//store all classes '.close' in a variable
var close = $('.close');
//store '.close' with same index as clicked button
var closeindex = $('.close').index(indexer);
console.log(closeindex);
});
});
I'm trying to walk through this click function and assign each class with the correct index to a variable, and I'm using console.log to print the indexes to the console.
With console.log(closeindex), I'm trying to get the index of the close button that has a matching index of span .open that was clicked, but currently it's returning -1.
I want to eventually do something like:
close.click = function() {
$('.modal').index(indexer).style.display = "none";
}
var closeindex = $('.close').eq(indexer);
Ok, so if you have a relationship between open and close such that the 3rd open related to the 3rd close, then you can get the related close by using the eq() method as above.
eq() will get you the element at that index, keeping it as a jQuery object.
If you're trying to open and close modal dialogs based on the buttons, I'd like to suggest an alternative method to indexes. With indexes, any refactoring/reordering of your elements is liable to throwing your code off entirely.
Consider using data attributes to keep track of what modal each open button is referring to. That way, no matter where your button/modals are, they are permanently linked.
If you give each modal an ID, and then add that ID to a data attribute on your open button...
<span class="open" data-modal="modal1">Open Modal 1</span>
<div class="modal" id="modal1"></div>
...then you can easily relate open buttons to their proper modals.
The close buttons can simply say "Close my parent modal" when clicked. We can do this using .closest( selector ) which traverses upwards in the DOM to find the first matching ancestor.
Working Example:
$(".open").on("click", function() {
$(".modal").hide(); //Hide all open modals
var modalId = $(this).data("modal"); //Get the Modal ID from the data-modal attribute
var $modal = $("#" + modalId); //Select the modal with that ID
$modal.show(); //Show it
});
$(".close").on("click", function() {
$(this).closest(".modal").hide(); //Close the closest modal (ancestry-wise)
});
div.modal {
display: none;
padding: 50px;
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="open" data-modal="modal1">Button A</span>
<span class="open" data-modal="modal2">Button B</span>
<!--modal-->
<div class="modal" id="modal1">
<!--modal content-->
<div class="modal-content">
I'm modal 1!
<!--close button-->
<span class="close">×</span>
<!--content A-->
</div>
</div>
<!--modal-->
<div class="modal" id="modal2">
<!--modal content-->
<div class="modal-content">
I'm modal 2!
<!--close button-->
<span class="close">×</span>
<!--content B-->
</div>
</div>
<!-- -->

How to pass and get modal value

First, my bootstrap modal is like this:
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<-- modal
header -->
<div class="modal-body">
<form class="form-horizontal" id="composeForm" method="POST" action="composeMessage">
<div class="form-group">
<label class="col-sm-2 control-label">To</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="sendToId" name="requestId">
</div>
</div>
<div class="line line-dashed b-b line-lg pull-in"></div>
<div class="form-group">
<label class="col-sm-2 control-label">Message</label>
<div class="col-sm-8">
<div class="btn-toolbar m-b-sm btn-editor"
data-role="editor-toolbar" data-target="#editor"></div>
<div id="editor" class="form-control" style="overflow:scroll;
height:150px;max-height:150px" contenteditable="true"></div>
<textarea style="display:none" id="divText" name="message"></textarea>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="sendSave" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
and my Javascript so far is like this:
$(function(){
var message;
$("#myModal").on('show.bs.modal', function(event){
var atag = $(event.relatedTarget); //I'm using a tag to open modal
var userNick = atag.data("nick");
var userComp = atag.data("comp");
var modal = $(this);
/*
skipped all dynamically setting values & changing attributes of tags
*/
document.getElementById("divText").value = document.getElementById("editor").innerHTML;
message = document.getElementById("divText").value;
});
$("button.btn.btn-primary").on('click', function(){
alert(message);
});
});
First, I have foreach loop in the same JSP, and the anchor tag opening the modal is in it. So I have multiple anchor tags.
The anchor tag opening modal is like this:
<a href="#myModal" data-target="#myModal" data-toggle="modal"
data-nick="${f.recomUserNick}" data-comp="${f.compatibility}">
I managed to set values and change attributes dynamically, and now I'm trying to send data from modal to controller (Spring MVC).
However, I have problem getting the 'message'. In the modal, the client writes something, and I first want to get the string value of that and check on alert to see if I can later send it to controller. What happens is that when I first open the modal, write something in it, and click the button (in the modal-footer, with id="sendSave"), I can't get the message. I close the modal, open it again -- in the message area it has what I wrote. I click the button, then I see my message in the alert window.
First, when I reopen the modal, I don't want to see what I wrote before, and I want to get the string value the first time, without having to open the modal again. I don't have a problem getting the string value, so I thought the problem was about where I put the codes, so I shifted my codes around for hours with no success. Can you please tell me how I should fix my codes? Thanks in advance.
You set the 'message' var in $("#myModal").on('show.bs.modal'.
At that point (in the first show) the message hasn't been typed yet.
If you move that code to the clickhandler, it takes the message after you have typed it:
$("button.btn.btn-primary").on('click', function() {
document.getElementById("divText").value = document.getElementById("editor").innerHTML;
message = document.getElementById("divText").value;
alert(message);
});

Getting the id of the anchor tag which was clicked

This is a list representation of data which is coming from a php database.The list is fetched using a foreach php loop and the data inside the achor tag is populated accordingly.
<?php foreach($array as $iterate):?>
<div class="col-sm-3">
<div class="panel panel-default">
**<a onClick='theFunction();' id="hello" href="#myModal" style="text-decoration:none;">**
<div class="panel-heading">
<img src ="audi_sillhouete.jpg" style="height:100%; width:100%;">
<p id="10" style="position:absolute; top:10%; padding-left:5%; padding-right:15%;"><?php echo $iterate->test_name ?></p>
</div>
</a>
</div>
</div>
<?php endforeach;?>
As you can see here, inside the anchor tag i have href-ed it to a modal box which will show a message whenever the user clicks on any of the link. There is a button in the modal window which will take the user to a different page.
The issue is that i want to pass certain value along with the url, but cannot do so as the link to the next page is defined in the modal window specification part.
So i came up with this solution. I thought of using the id attribute of the anchor tag, I tried to get the id attribute of the anchor which was clicked using javascript.
<script type="text/javascript">
function theFunction()
{
var id = $('a', this).attr('id');
alert(id);
}</script>
From this i wanted to initialize a php variable and then use that php variable to pass as value in the href of the modal window button. But the value i am getting in the alert box is 'undefined' for some reason. I have tried all possible combinations of this.
$('a',this).attr('id');
$this.id;
Everything return 'undefined'.
Reference-This is the code for the modal window part.
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Instructions</h4>
</div>
<div class="modal-body">
Your test is about to commence. A timer will be initiated after the moment you start the test. You may choose to answer a question, or leave it empty. You can also attempt the questions in any order that you find suitable.<br><br>Upon completion of the test, click on "Submit" to see your performance statistics.<br><br><br>Good luck!
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Continue</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
Please try this
$(document).on('click', 'a', function () {
alert(this.id);
});
DEMO
You can use other attribute in anchor like :
<a href='' id='hello' para-id='somevalue'></a>
alert($("#hello").attr("para-id"));
The below jQuery function runs through all the a tags on page load and adds id to the end of the link.
$(function(){
$('a').each(function(){
var id = $(this).attr('id');
var url = $(this).attr('href') + '?id=' + id;
$(this).attr('href',url);
});
});
https://jsfiddle.net/yc1hswet/

Unloading data from a modal

I am using bootstrap 3.3.2. How could I remove the data from modal? I want the modal to appear as fresh as it was loaded the first time.
For example a modal like :
<div class="modal fade" id="pass" tabindex="-1" role="dialog" aria-labelledby="mypass" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<h4 class="modal-title text-center" id="mypass">Characteristics</h4>
<div class="modal-body">
<form class='form-inline'>
<div class='form-group'>
<label for='playernumber_pass'>Player number</label>
<input type='text' class='form-control' id='playernumber_pass' name='playernumber_pass'/>
</div>
<label class='checbox-inline'>
<input type='checkbox' id='completed' name='completed'>Completed
</label>
</form>
</div>
</div>
</div>
</div>
when loaded again has the field filled with the previous data. How could I make sure, that the fields and other items inside the modal are loaded fresh?
Here is the fiddle that showing the same data is loaded again, when modal reloads : fiddle
I tried the following, but it didn't work :
$('#pass').on('hidden.bs.modal', function () {
$('#pass').removeData();
})
You could cache .html() of the modal and restore it on a X.bs.modal event
var modalFreshContents = $('#pass').html();
// content of the modal will be restored when the modal is fully hidden
$('#pass').on('hidden.bs.modal', function (e) {
$(this).html(modalFreshContents);
});
Demo
you can use model on show event. This event fires immediately when the show instance method is called. If caused by a click, the clicked element is available as the relatedTarget property of the event. check model events
$('#pass').on('show.bs.modal', function () {
$('form.form-inline')[0].reset();
});

Show Modal From dynamically inserted button

I have a table element :
<table id="postcon-table-success" class="table table-hover">
</table>
and I am inserting rows dynamically in the table:
postConTable = "<tr><td><input id=\""+value.processId+"-details\" type=\"button\" class=\"btn btn-primary view-details\" value=\"View Details\" /></td></tr>";
$("#postcon-table-success").append(postConTable);
here button has id as dynamic variable (processID) followed by "-value"
eg.230002-details, where 230002 is processID.
Now I am clicking the button
$('#postcon-table-running').on('click',".view-details", function() {
console.log(this.id);
$('#myModal').modal('show');
});
which is calling the jquery function and the log is getting printed :
230002-details
But its not showing the modal which is in the body tag.
<body id="fixedbody" data-spy="scroll" data-target=".bs-docs-sidebar">
<div id="master-container" class="container-fluid">
<div id="myModal" class="modal hide fade" tabindex="-1" aria-hidden="true">
<div class="modal-header">
<h3 id="myModalLabel">Please wait</h3>
</div>
<div class="modal-body">
<p>We are fetching data</p>
</div>
</div>
Please help.
To ADD- when I create my modal in the parent tag of '#postcon-table-running', it is working.
But I cant do it that way because I want to implement same functionaliy from various buttons in various other divs.
It could be that the modal is not visible to the on click function. Put your modal at the very end of the page.

Categories

Resources