1

I have the following code:

<input type="checkbox" name="module" value="module1" />
<input type="checkbox" name="module" value="module2" />
<input type="checkbox" name="module" value="module3" />
<div id="result"></div>

And the Javascript:

$('input[name="module"]').click(function(){ 
if (this.checked) {
var span = "<span id='" + this.value + "'>" + this.value + "<br /></span>";
$("#result").append(span);
}else{
$("#" + this.value).remove();
}
});

All this works well. However, when I introduce a value for the checkbox with a space in it stops removing the item from the list.

http://jsfiddle.net/n1cubk0e/5/

You can see from the above what happens when a space is introduced. How to I get it to work with the space in the checkbox value?

Thanks in advance

andy
  • 447
  • 2
  • 6
  • 23
  • As pointed out in http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html, HTML 5 does not allow any spaces for id attribute. – jaaw Feb 10 '16 at 10:49

2 Answers2

2

As per the HTML5 specifications for id attributes, The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters

Try this:

$('input[name="module"]').click(function() {
  var id = this.value.replace(/ /g, "");
  if (this.checked) {
    var span = "<span id='" + id + "'>" + this.value + "<br /></span>";
    $("#result").append(span);
  } else {
    $("#" + id).remove();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="checkbox" name="module" value="module 1 1 1" />
<input type="checkbox" name="module" value="module 2 2 2" />
<input type="checkbox" name="module" value="module 3 3 3" />
<div id="result"></div>

Fiddle here

Rayon
  • 34,175
  • 4
  • 40
  • 65
  • This works for 1 space, for example: Module 1 but if I had "The Module of All Modules 1" it fails to remove it once unclicked. – andy Feb 10 '16 at 10:45
1

One way of solving this is to use non-breaking space

<input type="checkbox" name="module" value="module&nbsp;1" />
<input type="checkbox" name="module" value="module&nbsp;2" />
<input type="checkbox" name="module" value="module&nbsp;3" />

Fiddle

user5226582
  • 1,748
  • 1
  • 18
  • 33