1

I have an input form e.g.

<input type="checkbox" id="a.b">

I want to print its value whenever I click on it using the console.log() javascript function.

<input type="checkbox" id="a.b" onclick="console.log(a.b.value)">

Obviously, Javascript complains that a is undefined and that the property b of value does not exist. The only way I found of doing this was to rename my field using _ instead of a . (period). I end up with

<input type="checkbox" id="a_b" onclick="console.log(a_b.value)">

Is there a better way? Can I escape dots in identifiers? I am aware that . is an invalid character in Javascript identifiers but it is not in HTML. Can I get around this issue using jquery?

David Brossard
  • 13,584
  • 6
  • 55
  • 88

2 Answers2

4

Javascript uses . notation to use object. And you can only escape when using as String. So the answer is No.

Why not just using this

<input type="checkbox" id="a.b" onclick="console.log(this.value)">

If you are playing with it, that is fine but as someone already pointed in comments, do not use inline events. Instead add events on elements

  var checkbox = document.getElementById("a.b");
    checkbox.onchange = function() {
    if(this.checked) {
        console.log("checked");
      } else {
        console.log("un checked");
      }
    }
<input type="checkbox" id="a.b">
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

You can access it by doing console.log(window["a.b"].value). I wouldn't suggest this as accessing elements directly like that is not a best practice, but it will do what you are asking.

Joe Lissner
  • 2,181
  • 1
  • 15
  • 21