开发者

jQuery join multiple labels

开发者 https://www.devze.com 2023-02-23 23:54 出处:网络
Hi I have a div element that contains a list of checkboxes like this <ul> <li><input type=\"checkbox\" ID=\"check1\" /><label for=\"check1\">Monday</label></li>

Hi I have a div element that contains a list of checkboxes like this

 <ul>
 <li><input type="checkbox" ID="check1" /><label for="check1">Monday</label></li>
 <li><input type="checkbox" ID="check2" checked="checked"/><label for="check2">Tuesday</l开发者_如何学运维abel></li>
 <li><input type="checkbox" ID="check3" /><label for="check3">Wednesday</label></li>
 <li><input type="checkbox" ID="check4" checked="checked"/><label for="check4">Thursday</label></li>
</ul>

I want to get the values checked in a string like 'Tuesday-Thursday'. So I wrote this very concise jQuery instruction

$('input:checked', 'ul').next().text() 

This give me 'TuesdayThursday'. I could not find the way to pass a separator and have 'Tuesday-Thursday'


Try something like

$('input:checked', 'ul').map(function(){
    return $(this).next().text();
}).get().join('-');


you need to use each function

var input = '';
$('input:checked', 'ul').each(function{
    input += $(this).next().text() + "separator";
});


use a aregex ?

var str =$('input:checked', 'ul').next().text().replace( /([a-z])([A-Z])/g, "$1-$2");
alert(str);

modified fiddle too just forgot the g for to make it handle more than 2

EXPLAINATION

please not I am note a regex expert so my explaination may not be 100% accurate

.replace() is a javascript function that will allow you to replace text strings. It can take Regular expression

in the example I give the regex is inbetween the the / / backslashes the first section

[a-z]

says look for lowercase letters

in the second part of the regex

[A-Z]

says look for Uppercase letters

putting them in parenthesis says we want lowercase followed by uppercase

then the "g" after says to do a global replace i.e. after the first set is found do it again until you find no more

then after the regex we need to tell it what we want to replace it with so

$1

and

$2

are variables assignments from the regex and we put the hyphen between them to give us the desired result

DEMO


Try this:

function getDaysString(){
    var returnValue = "";
    $("input:checked+label", "ul").each(function(){
        returnValue += $(this).text() + "-";
    });
    return returnValue.replace(/-$/, "");
}


checkedBoxes = new Array();
$('input').each(function(){ checkedBoxes.push($(this).next().text()+'-') });
checkedBoxes.join('-');


$(document).ready(function() {
    var days = $.map($("input:checked"), function(element, index) {
        return $(element).next().text();
    }).join("-");
    alert(days);
});

Working example: http://jsfiddle.net/peeter/t4X3S/

0

精彩评论

暂无评论...
验证码 换一张
取 消