使用JavaScript基于复选框输入创建动态字符串

时间:2017-06-22 22:14:01

标签: javascript jquery html checkbox

我在页面的表格中有一组复选框。我想要做的是当用户点击复选框时,其值将打印在表格下方。多个值可以按行打印,用' +':

分隔
"a+b+c+d"

我在base_pro.html中有这段代码:

 <html>
  <head>
    <title>{% block title %}Offer engineering{% endblock %}</title>
    {% block css %}
    <link rel="stylesheet" href="/static/css/reset-min.css" />
    <link rel="stylesheet" href="/static/css/main.css" />
    {% endblock %}
    {% block script %}
    <script src="/static/js/main.js" type="text/javascript"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="/static/js/my_jq.js"></script>
    {% endblock %}
  </head>
  <body>
    <div id="header">{% block header %}{% endblock %}</div>
    <div id="messages-wrap">
      <div id="messages">
        {% for category, msg in get_flashed_messages(with_categories=true) %}
          <p class="message flash-{{ category }}">{{ msg }}</p>
        {% endfor %}
      </div>
    </div>
    <div id="content">{% block content %}{% endblock %}</div>
    <div id="footer">{% block footer %}{% endblock %}</div>
  </body>
</html>

main.html中:

{% extends "base_pro.html" %}
{% block content %}
Hi {{ user.name }}!

<table style="width:100%">
<tr>
<th>v1</th>
<th>v2</th>
<th>v3</th> 
<th>v4</th>
<th>v5</th>
</tr>
<tr>
<td><label><input type="checkbox" name="selected" value="a" class="offers" />a</label></td>
<td><label><input type="checkbox" name="selected" value="b" class="offers" />b</label></td> 
<td><label><input type="checkbox" name="selected" value="c" class="offers" />c</label></td>
    <td><label><input type="checkbox" name="selected" value="d" class="offers" />d</label></td>
</table>


{% endblock %}

my_js.js:

$("input[type=checkbox]").on("change", function(){
var arr = []
$(":checkbox").each(function(){
   if($(this).is(":checked")){
     arr.push($(this).val())
   }
})
var vals = arr.join("+")
var str = vals
console.log(str);

})

选中复选框后,我无法显示字符串。我究竟做错了什么?

2 个答案:

答案 0 :(得分:0)

您可以在表格下方创建一个空div,它会在激活复选框时显示该值。我在下面提出了一个解决方案。

try:
    while(True):
        i+=1
        put = input("\tEnter name of feature number " + str(i) +":\t")
        features.append(put)
except KeyboardInterrupt:
    print("\n\tFeatures Added!")
    sleep(SLEEP)
    return None
except:
    exit("\nError has occurred, please come back later...")`
$("input[type=checkbox]").on("change", function(){
var arr = []
$(":checkbox").each(function(){
   if($(this).is(":checked")){
     arr.push($(this).val())
   }
})
var vals = arr.join("+");
var str = vals;
$("#val").text(str);
})

答案 1 :(得分:0)

您需要显式地在DOM中注入连接的字符串值 比如说桌子下方有一个div

var vals = arr.join("+")之后,您可以将上述div中的值插入

$('#displayConcatenatedString').html(vals)