<...">

JQuery join multiple shortcuts

Hi I have a div element that contains a list of checkboxes such as

<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</label></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 the values ​​to be marked on a tuesday-thursday string. So I wrote this very brief jQuery instruction

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

This will give me "TuesdayThursday". I could not find a way to pass the delimiter and have a Tuesday-Thursday.

+4
source share
6 answers

use begex?

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

the modified fiddle too simply forgot g to handle more than 2

Explaination

please do not want to point out the regex expert, so my explanation may not be 100% accurate.

. replace () is a javascript function that allows you to replace text strings. It may take regular expression

in the example in which I specify the regex is between them // reverse oblique first section

 [az] 

says lowercase letters

in the second part of the regular expression

 [az] 

says top level letters

putting them in parentheses, we want uppercase letters to be entered

then the "g" after says you need to make a global replacement ie after the first set is found, repeat this until you find more

then after regular expression we need to say that we want to replace it like this

 $1 

and

 $2 

are the assignments of variables from a regular expression, and we put a hyphen between them to give us the desired result

Demo

+1
source

Try something like

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

you need to use each function

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

Try the following:

 function getDaysString(){ var returnValue = ""; $("input:checked+label", "ul").each(function(){ returnValue += $(this).text() + "-"; }); return returnValue.replace(/-$/, ""); } 
0
source
 checkedBoxes = new Array(); $('input').each(function(){ checkedBoxes.push($(this).next().text()+'-') }); checkedBoxes.join('-'); 
0
source
 $(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
source

Source: https://habr.com/ru/post/1347537/


All Articles