私信  •  关注

gavgrif

gavgrif 最近创建的主题
gavgrif 最近回复了
6 年前
回复了 gavgrif 创建的主题 » 如何从复选框jquery中收集选中的值

您可以根据所选元素生成选项的动态列表,并在字段集的点击上触发。

$('fieldset').click(function(){
  var food = document.querySelectorAll('[name="food"]:checked');
  var foodStr = ''; 
  food.forEach(function(item){
    foodStr += '<li>' + item.value + '</li>';
  })
  $('#selectedItems').html(foodStr);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset>
        <legend>Pick the foods you like.</legend>

        <input id="tacos" type="checkbox" name="food" value="tacos">
        <label for="tacos">Tacos</label>

        <input id="crepes" type="checkbox" name="food" value="crepes">
        <label for="crepes">Crepes</label>

        <input id="dumplings" type="checkbox" name="food" value="dumplings">
        <label for="dumplings">Dumplings</label>

    </fieldset>
    <br/>
    <ul id="selectedItems"></ul>
6 年前
回复了 gavgrif 创建的主题 » jquery keyup未引发警报

您遇到了一些语义问题(例如没有关闭body标记),还有一些拼写错误—我还将脚本块移动到了页面的末尾,以便可以在调用脚本之前加载页面。确保在将外部JS文件调用到页面时关闭脚本标记-它们需要位于自己的脚本标记中-而不是与页面内的javascript块连接。我还为文本区域添加了HTML5 doctype和占位符文本。您还应该为输入设置标签。

另外,调试时最好使用console.log()而不是alert。

<!doctype html>
 <head>
   <title>City Finder</title>
 </head>
 <body>
   <form>
    <label for ="cityField"> Enter A Utah City:</label>
     <input type = "text" id="cityField" value= ""><br>
      Suggestion: <span id="txtHint">Empty</span>
     <input id="weatherButton" type ="submit" value="Submit">
   </form>
   <label for="displayCity">City</label><br>
   <textarea id = "displayCity" placeholder="No city"></textarea>
   <p>Current Weather</p>
   <div id="weather">No Weather</div>
     <button type = "button" onclick = "alert('hello')" name = "ok" >Climb out window</button>
            
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
 $(document).ready(function() {
    $( "#cityField" ).keyup(function() {
        console.log("Handler for .keyup() called.");
    });
  });
</script>
</body>
</html>