0

I was messing around with forms, and I was working with a JSfiddle, and I couldn't get the page to return an alert.

Here is my HTML:

<form>
<input type="text" id="first"></input>
<input type="text" id="last"></input>
<input type="button" value="Submit" onClick="construct()"></input>
</form>

Here is my JavaScript:

function construct() {
var firstName = document.getElementById("first").value;
var lastName = document.getElementById("last").value;
alert("Welcome to the party " + firstName + " " + lastName + "!");
}

And I can't tell why it is not returning a value. Any help is appreciated! Oh and here is the fiddle: http://jsfiddle.net/nickpalmer789/4DJ4e/1/ Thanks!

3 Answers 3

1

Because the fiddle is set up to run onload so the function is not available in global scope. Either change it to run in the head or on the body

enter image description here

or attach the event handler in a non obtrusive way.

document.getElementsByTagName("button")[0].onclick = construct;
Sign up to request clarification or add additional context in comments.

4 Comments

Can you explain how to do this, so that I can make it in a regular javascript file?
Explain how to go into the drop down and select the other option as shown in the image above?
Sorry, I meant what do the different options mean?
0

You need to change onload (top left) to no wrap - in <head>. You're interfering with scope, so construct() isn't declared in the global scope (which the onclick attribute is looking for).

Otherwise, declare it as window.construct = function(){ ... }

As an aside, you should really be keeping markup and javascript separated. that is to say don't use the on* attributes of elements, and instead bind to them within javascript. Something like:

<!-- give n ID to the button -->
<input type="submit" value="Submit" id="submit-btn" />

<script>
  // grab the button (using the ID)
  var submitBtn = document.getElementById('submit-btn');
  // attach en event handler for click
  submitBtn.addEventListener('click', function(){
    // construct() code goes here
  });
</script>

2 Comments

Can you explain to me what the difference between all of the different options on that menu are used for?
@NickP: onLoad, onDomReady, no wrap - in <head> just places it directly in the <head> of the document, and no wrap - in <body> places in within the <body> tag.
0

construct is defined inside another function, so it isn't a global and isn't accessible to intrinsic event attributes.

Don't use intrinsic event attributes, bind your event handlers with JS.

document.querySelector('input[type="button"]').addEventListener('click', construct);

Such: http://jsfiddle.net/4DJ4e/3/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.