I have to mention from the beginning that i am new in this world, so any help would be more than appreciated!
I have some Bootstrap checkboxes that i want to print (window.print) using jQuery.
The only problem is that the array that i create from the checkboxes, lists the results one after another.
HTML:
<div class="form-check">
<input class="form-check-input" name="type" type="checkbox" value="Question1" id="flexCheckDefault">
<label class="form-check-label" for="flexCheckDefault">
Question1
</label>
</div>
<div class="form-check">
<input class="form-check-input" name="type" type="checkbox" value="Question2" id="flexCheckDefault">
<label class="form-check-label" for="flexCheckDefault">
Question2
</label>
</div>
jQuery:
$("#results_message").text("The results are:");
$("button").on("click", function () {
var array = [];
$("input:checkbox[name=type]:checked").each(function () {
array.push($(this).val());
});
$("#results_after").text(array);
$('#results_after').printThis();
});
CSS:
#results_after {
color: green;
font-size: 24px;
font-weight: bold;
visibility: hidden;
}
#results_message {
visibility: hidden;
}
@media print {
#results_message,
#results_after {
visibility: visible;
}
}
Because it's an array, the results are separated by a comma and i want them to be one below each other. I was thinking <br>
would solve the situation but i dont know how to add it.
Many thanks!
CodePudding user response:
The short answer is: use array.join()
to separate the array by a delimiter. I chose <br />
which meant I needed to use .html()
rather than .text()
.
$("#results_after").html(array.join('<br />')).show()
The .show()
is because you were hiding the output divs in the css.
$("#results_message").text("The results are:").show();
$("button").on("click", function() {
var array = [];
$("input:checkbox[name=type]:checked").each(function() {
array.push($(this).val());
});
$("#results_after").html(array.join('<br />')).show();
});
#results_after {
color: green;
font-size: 24px;
font-weight: bold;
display: none;
}
#results_message {
display: none;
}
@media print {
#results_message,
#results_after {
visibility: visible;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-check">
<input class="form-check-input" name="type" type="checkbox" value="Question1" id="flexCheckDefault">
<label class="form-check-label" for="flexCheckDefault">
Question1
</label>
</div>
<div class="form-check">
<input class="form-check-input" name="type" type="checkbox" value="Question2" id="flexCheckDefault">
<label class="form-check-label" for="flexCheckDefault">
Question2
</label>
</div>
<hr>
<button>click</button>
<div id='results_message'></div>
<div id='results_after'></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>