问题
I found this code here... Instead of displaying the values on an alert, how to show them on a div like text content?
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function(){
var favorite = [];
$.each($("input[name='sport']:checked"), function(){
favorite.push($(this).val());
});
alert("My favourite sports are: " + favorite.join(", "));
});
});
I want to show the values on the div "checkboxvalues", how do i do that?
<div id="checkboxvalues"></div>
<form>
<h3>Select your favorite sports:</h3>
<label><input type="checkbox" value="football" name="sport"> Football</label>
<label><input type="checkbox" value="baseball" name="sport"> Baseball</label>
<label><input type="checkbox" value="cricket" name="sport"> Cricket</label>
<label><input type="checkbox" value="boxing" name="sport"> Boxing</label>
<label><input type="checkbox" value="racing" name="sport"> Racing</label>
<label><input type="checkbox" value="swimming" name="sport"> Swimming</label>
<br>
<button type="button">Get Values</button>
</form>
回答1:
$("#checkboxvalues").html('My favourite sports are: ' + favorite.join(", "));
回答2:
You can simplify your code as follows
$(document).ready(function() {
$("button").click(function() {
$('#display').html($("input[name='sport']:checked").map(function() { return this.value; }).get().join());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="checkboxvalues"></div>
<form>
<h3>Select your favorite sports:</h3>
<label>
<input type="checkbox" value="football" name="sport">Football</label>
<label>
<input type="checkbox" value="baseball" name="sport">Baseball</label>
<label>
<input type="checkbox" value="cricket" name="sport">Cricket</label>
<label>
<input type="checkbox" value="boxing" name="sport">Boxing</label>
<label>
<input type="checkbox" value="racing" name="sport">Racing</label>
<label>
<input type="checkbox" value="swimming" name="sport">Swimming</label>
<br>
<button type="button">Get Values</button>
</form>
<div id=display></div>
来源:https://stackoverflow.com/questions/32147493/get-checkbox-value-into-a-div-like-content