Search code examples
javascriptjsfiddle

JsFiddle Javascript not firing?


I've got a huge feeling I'm simply being idiotic here, but is it me or is Js not firing in JsFiddle?

I built this snippet here but can't seem to get it to fire. Im probably missing something super obvious, but would be grateful for any assistance.

HTML

  <div id="col">

    <h3 class="txt spacer">Dynamic input, based on select value...</h3>
    <input type="text" name="field-one" class="txt stretch" />

    <div class="boxes">
      <input type="checkbox" id="box-2" onChange="myFunction()" checked>
      <label for="box-2">Apply a name?</label>
    </div>
  </div>
</div>

Javascript

function myFunction() {
  // Text field element.
  var a = document.getElementByName('field-one');
  // Checkbox element.
  var b = document.getElementById('box-2');

  if (b.checked) {
    a.disabled = false;
    a.placeholder = 'Not Applicable';
    alert('Checkbox State Changed.');
  } else {
    a.disabled = true;
    a.placeholder = 'Enter Your Full Name';
    alert('Checkbox State Changed.');
  }
}

JS FIDDLE

Thanks in advance for the assistance.

Regards,

-B.

EDIT

I'm an idiot. Thanks guys.


Solution

  • Couple of things here, it should be document.getElementsByTagName (plural) and you need to change the settings, that will embed the JS code in before the body closes.

    var a = document.getElementsByName('field-one')[0];
    

    I am using [0] here to access the very first element of the array as document.getElementsByName() will return you an array of elements if encountered multiple matching elements. If you want to select a specific one, make sure you select the DOM element in a more specific way.

    And change the Load Type to

    No wrap - in <body> (<head> will work as well)

    Demo