将数据传递给模态弹出窗口

时间:2017-01-18 20:32:56

标签: javascript html

我有一个打开模态的按钮,它没有任何问题,但我现在想要将数据从按钮传递到模态中的字段。

HTML

<input type=button value='Add Background' id='myBtn2' data-toggle="modal" data-id="@book.Id" title="Add this item" class="open-AddBookDialog">

<div id="myModal2" class="modal">

<!-- Modal content -->
<div class="modal-content">
<span class="close2">&times;</span>
<form action="includes/back.php" method="post" enctype="multipart/form-data">
  <center>

    <h2><b>Background Information</b></h2>
    <INPUT TYPE="text" NAME="army_id" id="army_id" size="auto" value="">
    <font>Background Title:&nbsp;&nbsp;&nbsp;</font>
<INPUT TYPE="text" NAME="back_name" size="auto" value="">
<font>Background Info:&nbsp;&nbsp;&nbsp;</font>
<INPUT TYPE="textarea" NAME="commander" size="auto" value="">
<input type="text" name="bookId" id="bookId" value=""/>
<font>
<b>STOP!</b><br>
Please check your information before pressing the submit button below. Looking over your information now will make sure editing later won't be necessary. Thank you.<BR>
<input type="hidden" name="FormSubmit" value="Yes">
<INPUT TYPE="submit"  name="submit" value="Submit Regiment"> &nbsp; <INPUT TYPE="reset" value="Reset Fields">

JS

var modal2 = document.getElementById('myModal2');

// Get the button that opens the modal
var btn2 = document.getElementById("myBtn2");

// Get the <span> element that closes the modal
var span2 = document.getElementsByClassName("close2")[0];

// When the user clicks the button, open the modal 
btn2.onclick = function() {
modal2.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span2.onclick = function() {
modal2.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal2) {
modal2.style.display = "none";
}
}

我希望有人可以告诉我该怎么做?

1 个答案:

答案 0 :(得分:0)

你真的不需要“传递数据”到模态 - 它是窗口的一部分,你可以像使用按钮一样使用Javascript来影响它。例如,如果要更改模态中的文本,则可以执行以下操作:

btn3.onclick = function() {
    modal2.textContent = 'different text!';
}

没有任何理由将数据编码到模态的属性中,至少除非你计划的事情比你的例子更复杂。

此外,您的代码中存在一些奇怪的不一致 - 为什么您的输入元素有时会写为INPUT,有时会写为input?这对于页面如何工作没有任何影响,但它使得阅读起来有点困难。最后,HTML5中不推荐使用font元素 - 而是使用CSS来设置字体规则。