Submit button to call function - javascript

My submit button is not doing anything when I click on it. I believe my event listener is correctly established. Any ideas on why it wont do anything?
JS FILE
document.getElementById("submitbutton").addEventListener("click", saveNames());
function saveNames() {
var player1name = document.getElementById("player1").value;
var player2name = document.getElementById("player2").value;
var player3name = document.getElementById("player3").value;
var player4name = document.getElementById("player4").value;
var player5name = document.getElementById("player5").value;
savePlayer(player1name);
savePlayer(player2name);
savePlayer(player3name);
savePlayer(player4name);
savePlayer(player5name);
gameScreen(2);
}
HTML FILE:
<input type="text"name="p1"><br>
<input type="text"name="p2"><br>
<input type="text"name="p3"><br>
<input type="text"name="p4"><br>
<input type="text"name="p5"><br>
<input id="submitbutton"type="submit" value="Submit">;

You're not binding to the function, you're binding to the result of the function. Just pass the function itself, don't invoke it. (Get rid of the parentheses):
document.getElementById("submitbutton").addEventListener("click", saveNames);
Why?
Because when that one line of code above executes, if you have the errant parentheses then the first thing it does is execute the saveNames function in order to get the result to pass to the addEventListener function. And that result is undefined because saveNames doesn't return anything.
Presumably also that first invocation of the saveNames function doesn't visibly do anything (though it does execute) because the inputs have no values in them yet at that time.
Consider as a contrived example:
doSomething( doSomethingElse() )
This would execute doSomethingElse() and then pass its returned result to doSomething(). The same is true when adding event listeners, you're just calling a function like any other function.

add the listener like this -
document.getElementById("submitbutton").addEventListener("click", saveNames);
note , I have removed () at end.
Use Id instead of name. you are reading these elements with id then you need to specify that.
Give a spaces before name or type.

//Remove the parenthese after "saveNames" - leaving them will call saveNames when it is encountered
document.getElementById("submitbutton").addEventListener("click", saveNames);
function saveNames() {
//Use an array as it's neater
var players = [
document.getElementById("player1").value,
document.getElementById("player2").value,
document.getElementById("player3").value,
document.getElementById("player4").value,
document.getElementById("player5").value
]
//loop and save
players.forEach(function(name) {
if (name) {
savePlayer(name);
}
});
//gameScreen(2);
}
function savePlayer(name) {
console.log(`${name} saved.`);
}
<input id="player1" type="text" name="p1"><br>
<input id="player2" type="text" name="p2"><br>
<input id="player3" type="text" name="p3"><br>
<input id="player4" type="text" name="p4"><br>
<input id="player5" type="text" name="p5"><br>
<input id="submitbutton" type="button" value="Submit">

Related

Use of "this" keyword in javascript

I have read about "this" keyword and I learned that 'this' keyword works for the object which is in context.
<!DOCTYPE html>
<html>
<body>
<form id="myForm">
<label>Type anything but "fun": <input id="noFun" type="text" oninput="checkValid" required ><input type="submit"></label>
<div><button onclick="previewMessage()">Preview errors</button></div>
<div id="err"></div>
</form>
<script>
function checkValid() {
if (this.value == "fun") {
this.setCustomValidity("You're having too much fun!");
} else {
// input is fine -- reset the error message
this.setCustomValidity('');
}
}
function previewMessage() {
var myform = document.getElementById("noFun")
document.getElementById("err").innerHTML = myform.validationMessage;
}
</script>
</body>
</html>
But when I use oninput = "checkValid" , it should copy the checkValid function and the "this" keyword inside the function should point to input object.But that's not the case!!!
Check out this another piece of code, it means the same as the previous one, but runs normally.
<form id="myForm">
<label>Type anything but "fun": <input id="noFun" type="text" oninput="checkValid(this)" required ><input type="submit"></label>
<div><button onclick="previewMessage();">Preview errors</button></div>
<div id="err"></div>
</form>
<script>
function checkValid(input) {
if (input.value == "fun") {
input.setCustomValidity("You're having too much fun!");
} else {
// input is fine -- reset the error message
input.setCustomValidity('');
}
}
function previewMessage() {
var myform = document.getElementById("noFun")
document.getElementById("err").innerHTML=myform.validationMessage;
}
</script>
Can you explain me the difference between the two snippets and why the first example does not work as expected.
Thanks in advance!!!
But when i use oninput="checkValid" , it should copy the checkValid function and the "this" keyword inside the function should point to input object.
No, it shouldn't.
The value of an intrinsic event attribute is the body of the event handler function.
The HTML oninput="checkValid" is equivalent to the JavaScript:
reference_to_input.oninput = function (event) {
checkValue;
};
Mentioning a variable (like checkValue) without doing anything to it (like putting () after it to call a function) does nothing.
The way you've set up the event handler is such that the value of this will not be the <input> element. You've got what amounts to a "naked" function call, so this will refer to the window object.
If, however, you were to establish the event handler in JavaScript like this:
document.getElementById("noFun").oninput = checkValid;
you'd get this referring to the element.
Note that your code will pass the reference to the element as a parameter, which is why your second sample of code works.

How to get the return value of a event

I use firebug to see the following code,
<input type="text" oncut="return false">
then try to get the return value of the event oncut,
var a=document.querySelector('input[type="text"]');
document.write(a.oncut);
I want to get the return value of oncut: false, however , I get the definition of the function oncut,as follows,
function oncut(event){
return false;
}
How can I only get the return value "false" from the event oncut?
oncut in your case is intended as a handler(event handler). "return false" is a definition of that handler. To get the returned value from function - just call the function:
...
document.write(a.oncut());
...
For example:
window.onload = function(){
document.write(document.getElementsByClassName("cut")[0].oncut());
}
<input type="text" class='cut' oncut="return false">
You can declare a function (giving it an arbitrary name) then add it to the cut event. Place your statement within this function. I used contentText instead of document.write because of this.
function cutFalse() {
return document.body.textContent = false;
}
<input type="text" oncut="cutFalse()">

using a variable to define elements

My function uses two variables which I define in my input-tag
function insert(aTag, eTag) {
var input = document.forms['form'].elements['textarea'];
input.focus();
...
}
...
<input type="button" name="bold" value="bold" onClick="insert('<b>', '</b>')">
The function will place the aTag and the eTag around selected parts in the textarea.
As I want to use this function in other textareas in the same form, I tried to use another variable in this function. This unfortunatly doesn't work.
I tried a lot of variants. Concept about like here:
function insert(aTag, eTag, selectInput) {
var input = document.forms['form'].elements[selectInput];
...
<input type="button" name="bold" value="bold" onClick="insert('<b>', '</b>', 'thistextarea')">
In the onClick handler, this refers to the object that was clicked. So you can simply do:
<input type="button" name="bold" value="bold" onClick="insert('<b>', '</b>', this)">
The function would receive the object without re-selecting it from anywhere:
function insert(aTag, eTag, input) {
input.focus();
...
}
Side note: unobtrusive event handlers are preferred to inline.

JS function not displaying anything

I have made a function and captured the value of a textbox. On a button click, it should alert the value.
The code is:
function substitute (argument) {
var myVal=document.getElementById('myTextBox').value();
alert(myVal);
if (myVal.length==0) {
alert('Empty Textbox');
};
}
It is then executed using this:
<input type="button" name="Button" value="Click Me" onclick="substitute();">
But nothing happens. Please tell me where am I doing it wrong.
You have a few errors:
.value() is not a function: use .value
You don't need that semicolon at the end of the if statement
Your text box might not have the id that you're referring to: make sure that you have id="myTextBox" in the opening tag
While it won't cause any errors, your function definition lists a parameter, but you do not pass one when you call it.
Always check your browser console for errors if nothing is happening. Always.
function substitute () { // Parameter "argument" is not necessary
var myVal=document.getElementById('myTextBox').value; //.value, not .value()
alert(myVal);
if (myVal.length==0) {
alert('Empty Textbox');
}; // You don't need this semicolon
} // You were missing this curly brace
Demo
value is not a function, it's a property, therefore:
var myVal=document.getElementById('myTextBox').value;
As you're brand new to JS, I'll give you a piece of advice: If you want to manipulate the DOM, use jQuery.
In Your code, you are not passing any parameter to function subsititute(), But # function definition you wrote substitute(argument). Thats a big issue, and also you put there is a semi-column after if condition inside the function. No need of it
Try This..
<input type="text" id="myText" value="Hello" />
<input type="button" name="Button" value="Click Me" onclick="substitute();" />
In script part,
function subsitute()
{
var myVal=$('#myText').val();
alert(myVal);
if (myVal=='')
{
alert('Empty Textbox');
}
}
http://jsbin.com/tewudopi/1/edit
Add an ID to the button. When referencing the button, it is not ".value()", it is simply ".value".
As a side note, you should use === instead of == to compare.
function substitute() {
var myVal=document.getElementById('myTextBox');
alert(myVal.value);
if (myVal.value.length===0) {
alert('Empty Textbox');
}
}
Maybe something like the following.
<script type="text/javascript">
function substitute() {
var myVal=document.getElementById('myTextBox').value;
if (myVal.length>0) {
alert(myVal);
}
if (myVal.length==0) {
alert('Empty Textbox');
}
}
</script>
<input type="button" name="Button" value="Click Me" onclick="substitute();">
<textarea name="myTextBox" id="myTextBox"></textarea>
Fiddle demo

How to use *this* in a javascript onlick function and traverse with jquery

I don't know if this is possible but I'm trying to use this in an onclick javascript function in order to traverse in jquery.
HTML
<input type="text" />
<button onclick="javascript:$.addItem(this)">Add</button>
JS
$.addItem= function(e) {
var n = parseFloat($(e).siblings('input').val());
};
Is this even possible or am I missing something?
There is no point in putting the function in the jQuery object, just declare a regular function.
function addItem(e) {
var n = parseFloat($(e).siblings('input').val());
};
Don't use the javascript: protocol in an event handler attribute. That's used when you put code in an href of a link.
<input type="text" />
<button onclick="addItem(this);">Add</button>
Demo: http://jsfiddle.net/Guffa/q8b4e/
you can use both event and this like this:
html
<input type="text" />
<button onclick="javascript:$.addItem(this,event)">Add</button>
JS:
$.addItem= function(elemnt, evnt) {
alert(evnt);
//var n = parseFloat($(e).siblings('input').val());
};
Jsfiddle

Categories

Resources