【问题标题】:Manipulating Text with JavaScript Based on Checkbox State基于复选框状态使用 JavaScript 操作文本
【发布时间】:2019-09-20 08:46:49
【问题描述】:

我正在尝试创建一个简单的 HTML 页面,该页面通过复选框为用户提供多个选项。我需要生成一个字符串,存储在一个变量中,当单击按钮时我可以在页面上使用该变量,这将根据选中的框而有所不同。

该字符串将是一个 URL ("http://example.com/index.htm&term="),并且需要为每个选中的复选框附加额外的文本。

例如,如果只选中一个框,比如 box1,则字符串“box1”应附加到 URL 变量中,看起来像“http://example.com/index.htm&term=box1

如果选中了多个框,例如选中了 box2 和 box3,则应将字符串“box2%20OR%20box3”附加到 URL 字符串中。

我很确定这可以用 JavaScript 完成,但我没有这方面的经验,希望得到一些指导/示例。

【问题讨论】:

  • 使用querySelectorAll 并使用参数"input[type='checkbox']" 选中所有复选框。您将获得一组复选框元素,您可以循环查看它们是否被选中,并从中构建您的 URL。祝你好运! developer.mozilla.org/en-US/docs/Web/API/Document/…

标签: javascript


【解决方案1】:

我建议不要将它存储在变量中,而是在按下按钮时调用一个构建链接的函数。如果你真的想把它放在一个变量中,你可以为每个复选框的change 事件设置一个事件监听器,并在每次选中或取消选中其中一个复选框时调用函数来更新变量。

function checkboxUrl(checkboxes) {
    const
        url = `http://example.com/index.html`,
        checkedArray = [];

    for (let checkbox of checkboxes) {
        if (checkbox.checked) checkedArray.push(checkbox);
    };
    
    const checkboxString = checkedArray.map(checkbox => checkbox.value).join(`%20OR%20`);
    return url + (checkboxString ? `?term=` + checkboxString : ``);
}

let checkboxes = document.querySelectorAll(`input[type='checkbox']`);
label {
  display: block;
}
<label><input type='checkbox' value='box1'>box1</label>
<label><input type='checkbox' value='box2'>box2</label>
<label><input type='checkbox' value='box3'>box3</label>
<button onclick='console.log(checkboxUrl(checkboxes))'>Get URL</button>

【讨论】:

    【解决方案2】:

    如果你使用Jquery,你可以这样做:

    <input type="checkbox" id="box1">
    <input type="checkbox" id="box2">
    <button type="button" id="myButton">Submit</button>
    
    <script>
    $(document).ready(function(){
        $('#myButton').click(function(){
            var url = 'www.myurl.com/index.html&term=';
            var checkboxList = [];
            var params = '';
    
            $(':checkbox:checked').each(function(){
                checkboxList.push($(this).attr('id'));
            });
    
            params = checkboxList.join('%'); //will output "box1%box2"
            url += params //www.myurl.com/index.html&term=box1%box2
    
            window.location.href = url;
        });
    });
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-25
      • 2019-02-22
      • 1970-01-01
      • 2017-11-13
      • 2011-09-06
      • 2012-04-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多