1

I made a web page where if a person clicked on a

<input type = "radio" name = "city" value = "lubum" onclick = "citySelect(city.value)">

This code...

function citySelect(cty) {
if(cty == "lubum"){
    document.getElementById("desc").innerHTML = "This is for Lubumbashi city/town! ^_^";
}else {
    document.getElementById("desc").innerHTML = "City Description";
}

}

...would change the text to "This is for Lubumbashi city/town! ^_^" here is the interesting part. I did not declare a city variable and yet the code runs. I changed the input tag's name attribute and the "citySelect(city.value)" to "d". Just to check if it would work.

It worked.

I did not need any of this

var k = document.getElementId("city"); //or the var city = k.value;

So is this something new in JS. I don't see people using it.

Kitanga Nday
  • 3,517
  • 2
  • 17
  • 29
  • 1
    Some browsers automatically create global variables that match some attributes of some DOM elements. Because the general reliance and use of globals is fraught with risk in Javascript, it is not considered a best practice in order to use these automatic globals. – jfriend00 Jun 13 '15 at 04:27
  • 1
    Post the entire code. On the face of this, it shouldn't work. And neither should "getElementById('city') if there is no element with an ID of city. What browser are you using? – Matt Runion Jun 13 '15 at 04:28
  • Well you are getting the value of Name = city. Then that means cty = lubum. Because that's what your passing to the constructor – James111 Jun 13 '15 at 04:29
  • @mrunion I'm using Google Chrome. – Kitanga Nday Jun 13 '15 at 04:30
  • I don't understand your question... you are explicitly calling the function with the onClick event handler. The only reason you'd need to set `var k` is if you were making changes to the DOM element itself from within javascript, not the function it points at. – marblewraith Jun 13 '15 at 04:32
  • Can I post code so that you can see it? – Kitanga Nday Jun 13 '15 at 04:33
  • it is part of the html5 spec, that id are global vars. – Vitim.us Jun 13 '15 at 04:33
  • It isn't the id i'm talking about. It's the name attribute of the input tag. I was able to refer to it's value attribute without the document.getEle....(gibberish) – Kitanga Nday Jun 13 '15 at 04:35
  • I know that you can reach names like document.{formname}.{elementname} I guess since you're calling the function from the element itself, it assumes the current form as the default scope. but idk – Vitim.us Jun 13 '15 at 04:39

0 Answers0