Get checkbox value into a div like content

我的未来我决定 提交于 2019-12-23 04:43:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!