I am trying to get the text value from the input box. I have followed the W3 schools example on how to do it. After adding it to my my code, I still cannot get the text value from the input bpx and display it on the screen. My code pen with the problem: https://codepen.io/Ag_Yog/pen/ayJQgR.
My attempted solution:
function submit(){ var x = document.getElementById("page").value; document.getElementById("result").innerHTML = x; }
Thanks for any help
Your immediate fix to this to move your submit() function outside of the jquery document.ready check.
However, I would take this a step further. I personally don’t think you should assign the event handler inside the HTML. I’d remove the onclick = "submit()"
from your HTML, and change your function submit()
to something like this:
$('#submit').on('click', function() {
//submit code here
});
you have your submit function wrapped in a function; therefore, the html can’t find the submit function. Instead of doing this:
function submit(){
You could instead do something like this:
window.submit = function (){
Both my ‘immediate fix’ and @codyseibert solution work, but I would go with the second option I put. These two here will pollute the global scope.
I would agree with @ryanjgross, you should try not to pollute the global space.
<div align="center">
<input type="text" id = "page" value="" />
<button id="submit">Submit</button>
<p id = "result"></p>
</div>
function submit(){
var x = document.getElementById("page").value;
document.getElementById("result").innerHTML = x;
}
//jQuery version
$('#submit').on('click', submit);
//vanilla JS version
var submitButton = document.getElementById("submit");
submitButton.addEventListener("click", submit);
1 Like