Во-первых, у тега абзаца нет атрибутов name
или value
. Если вы хотите создать новые атрибуты, используйте HTML5 data-attribute .
Чтобы упростить последующий код JS, мы добавим эти атрибуты к элементу input
. Например,
<tr>
<td><input type="checkbox" name="case" data-name="Computer1" data-connect="Computer3"></td>
<td>Computer1</td>
<td>Computer3</td>
</tr>
Во-вторых, ваш код JS был немного запутанным. Я думаю, почему вы получаете повторяющиеся результаты, потому что вы рекурсивно звоните getElementRelation()
.
Я бы упростил ваш код, как показано ниже
$(function() {
// cache jQuery objects that we will be re-using
var checkBoxes = $("input[name=case]");
var myModal = $("#myModal");
// get all relationships i.e. key = name, value = connect or null
var relations = {};
checkBoxes.each(function () {
relations[this.dataset.name] = this.dataset.connect;
});
// when the getElementRelation() function is called normally, it is expected
// to have 2 arguments (element1 and element2);
// but as an event handler it will have 1 argument (Event object)
$('#checkBtn').click(function getElementRelation(e) {
// get checked checkboxes
var checkedBoxes = checkBoxes.filter(":checked");
// validate first
if (checkedBoxes.length != 2) {
alert("You must check 2 checkbox!");
return false;
}
// build modal body
var html = '';
var current = checkedBoxes[0].dataset.name,
end = checkedBoxes[1].dataset.name;
while (current) {
html += current;
// check if it is connected
var next = relations[current];
// if it is not connected, stop
if (!next) {
html = 'Not related';
break;
}
// otherwise append HTML
html += ' -> ' + next + '<br>';
// if it is the end, stop
if (next == end) break;
// you may want to delete the key to avoid any infinite loop in case
// delete relations[current];
// start over using connected one
current = next;
}
// update modal
myModal.find('.modal-body').html(html);
// open the modal dynamically once it is ready
myModal.modal('show');
});
});
И последнее, вернемся в ваш HTML, удалите data-toggle="modal"
и data-target="#myModal"
, поскольку мы открываем модальное динамически .
Демо
$(function() {
// cache jQuery objects that we will be re-using
var checkBoxes = $("input[name=case]");
var myModal = $("#myModal");
// get all relationships i.e. key = name, value = connect or null
var relations = {};
checkBoxes.each(function() {
relations[this.dataset.name] = this.dataset.connect;
});
$('#checkBtn').click(function() {
// get checked checkboxes
var checkedBoxes = checkBoxes.filter(":checked");
// validate first
if (checkedBoxes.length != 2) {
alert("You must check 2 checkbox!");
return false;
}
// build modal body
var html = '';
var current = checkedBoxes[0].dataset.name, // start with
end = checkedBoxes[1].dataset.name; // end with
while (current) {
html += current;
// check if it is connected
var next = relations[current];
// if it is not connected, stop
if (!next) {
html = 'Not related';
break;
}
// otherwise append HTML
html += ' -> ' + next + '<br>';
// if it is the end, stop
if (next == end) break;
// start over using connected one
current = next;
}
// update modal
myModal.find('.modal-body').html(html);
// open the modal dynamically once it is ready
myModal.modal('show');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Checkboxes -->
<div class="container">
<div class="row">
<div class="col-sm-6">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Connect</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" name="case" data-name="Computer1" data-connect="Computer3"></td>
<td>Computer1</td>
<td>Computer3</td>
</tr>
<tr>
<td><input type="checkbox" name="case" data-name="Computer2"></td>
<td>Computer2</td>
<td></td>
</tr>
<tr>
<td><input type="checkbox" name="case" data-name="Computer3" data-connect="Computer4"></td>
<td>Computer3</td>
<td>Computer4</td>
</tr>
<tr>
<td><input type="checkbox" name="case" data-name="Computer4"></td>
<td>Computer4</td>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- Input button -->
<div class="container">
<div class="row">
<div class="col-sm-12">
<input type="button" id="checkBtn" value="View" class="btn btn-info">
</div>
</div>
</div>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Title</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body" id="modaldata">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>