简体   繁体   中英

I am trying to combine a string while looping

The result I am trying to get if the first two boxes are checked would be 1 2, if 3 boxes are checked the result would be 1 2 3. The x comes out as undefined. I assume this has to do with variable scope but even if I view the x within the input function it only shows 1 selection at a time, it is not combing them.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
function MLSNumbersSelected()
{
    $("input:checkbox").each(function(){  
        var $this = $(this);    
        if($this.is(":checked")){
        var x = x+" "+$this.attr("id");
        }
    });
  alert(x); //should equal what is checked for example 1 or 1 2.
}
</script>
</head>

<body>
    <p id="checkBoxes">
        <input type="checkbox" class="checkBoxClass" id="1" />1<br/>
        <input type="checkbox" class="checkBoxClass" id="2" />2<br/>
        <input type="checkbox" class="checkBoxClass" id="3" />3</p>
    <p>
            Check off some options then click button.
      <input type="button" name="button" id="button" value="Click to Test" onClick="MLSNumbersSelected()">
    </p>
</body>

You are defining x everytime in your loop, instead define x once and keep appending to it through the loop. Eg:

    <script>
    function MLSNumbersSelected()
    {
        var x;
        $("input:checkbox").each(function(){  
            var $this = $(this);    
            if($this.is(":checked")){
                x += " "+$this.attr("id");
            }
        });
        alert(x); //should equal what is checked for example 1 or 1 2.
    }
    </script>

You have to declare x outside the .each() loop. As it is now, it is declared inside the .each() loop and then it goes out of scope before the next callback is called so you can't accumulate it's value from one callback to the next:

function MLSNumbersSelected() {
    var x = "";
    $("input:checkbox").each(function(){  
        if (this.checked) {
            x += " " + this.id;
        }
    });
    console.log(x);
}

FYI, I also removed the use of the jQuery from inside the loop because it's not necessary when the direct DOM properties give you everything you need already.


You could also let the selector do the work for you, by adding :checked to the selector so it only selects checkboxes that are already checked. And, you can then use .map() and .join() to more easily create the list:

function MLSNumbersSelected() {
    var x = $("input:checkbox:checked").map(function(){  
        return this.id;
    }).get().join(" ");
    console.log(x);
}

You re-initialize x in the loop. This should solve your issue:

function MLSNumbersSelected()
{
    var x = '';    
    $("input:checkbox").each(function(){  
        var $this = $(this);    
        if($this.is(":checked")){
        x = x+" "+$this.attr("id");
        }
    });
  alert(x); 
}

Use this to see if it achieve what you need:

var inputs = $("input:checkbox");
inputs.each(function(i){  
    if(inputs.eq(i).is(":checked")){
    x = x+" "+inputs.eq(i).attr("id");
    }
});

 $(function() { $('#button').on('click', function() { var x = $(':checkbox:checked').map(function() { return this.id; }) .get().join(' '); alert( x ); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <p id="checkBoxes"> <input type="checkbox" class="checkBoxClass" id="1" />1<br/> <input type="checkbox" class="checkBoxClass" id="2" />2<br/> <input type="checkbox" class="checkBoxClass" id="3" />3</p> <p> Check off some options then click button. <input type="button" name="button" id="button" value="Click to Test"> </p> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM