Why can I not execute my javascript function by using an event listener? - javascript

Javascript
const btn0 = document.querySelector('.btn0');
btn0.addEventListener('click', function() {
showNum(0);
})
function showNum(value)
HTML
<input type="button" value="0" name="btn0" id="btn0" />
I have included the relevant code above. The showNum function is fully implemented and working, I just didn't include it because it was irrelevant.
I need to call the showNum function with an event listener but can't figure out why my code is not working. When debugging I can see that addBtn is null and no matter what I try it stays that way. I have been struggling with this for an hour and am frustrated at how simple it should be.
I have tried different ways of initializing addBtn such as using getElementByName, but when debugging through the program btn0 is always null.

btn0 is not a class instead it is an id so you have to use # in place of . in
const btn0= document.querySelector('#btn0');
const btn0 = document.querySelector('#btn0'); // CHANGE
btn0.addEventListener('click', function() {
showNum(0);
})
function showNum(value) {
console.log('Inside showNum functon with value: ', value);
}
<input type="button" value="0" name="btn0" id="btn0" />
You can also find button using attribute also as:
document.querySelector('[name="btn0"]');
const btn0 = document.querySelector('[name="btn0"]'); // CHANGE
btn0.addEventListener('click', function() {
showNum(0);
})
function showNum(value) {
console.log('Inside showNum functon with value: ', value);
}
<input type="button" value="0" name="btn0" id="btn0" />

You a are using querySelector to select the button element with the class name .btn0 However, in the HTML , the button element has an ID of btn0, not a class name.
To select an element by ID, you should use the getElementById method instead of querySelector. Try changing your code to the following:
const btn0 = document.getElementById('btn0');
btn0.addEventListener('click', function() {
showNum(0);
});

Related

How Can I call a dynamic index in function cshtml?

I have this function :
<script>
function f(id){
return $("#" + id).val();
}
</script>
And this html's tag:
<input id=f(#payMethod) type="radio" value=" #method.Value" name="cartaCont" />
My id is buildered with a foreach that pass value to variable:
string payMethod = "payMethod";
payMethod += method.Text;
My question is: Is correct Call this index in an other function in this way ?? :
function() {
$('input[id ^= #PayMethod]').attr('checked', headerChecked);
}
thanks for feedback
It seems that you want to write some html and javascript code, relating to each item of a list.
In this case, I often prefer to directly write html and related javascript for event binding and code customization.
I supposing that method is your razor variable in your foreach, and methods is the enumerable variable to loop, you may would write this code for html
#foreach(var method in methods)
{
// this is C#, not javascript
// replacing spaces to build right id code for html
string payMethod = "payMethod" + method.Value.Replace(" ", "");
<text>
<input id="#payMethod" class="payMethodRadio" type="radio" value="#method.Value" name="cartaCont" />
<script>
$(document).ready(function () {
$("##payMethod").on('change', function (e) {
/* here if you want to write some javascript events for each item related to its html ID, for example change event */
});
});
</script>
</text>
}
But if you want to write some common jQuery code for this set of radio buttons, I' prefer to manage it with class selector rather than ID rules, as follow
function() {
$('payMethodRadio')...
}
Hope this, help you for better code management.
Br
Andryx
Try to add Onchange event to input.Here is a demo code:
#{var payMethod = 0;}
#foreach (var method in Model.Methods)
{
<input id="#payMethod" type="radio" value=" #method.Value" name="cartaCont" onchange="Add(#payMethod)"/>
payMethod++;
}
js:
function Add(id) {
$('#'+id).attr('checked', headerChecked);
}

Submit button to call function

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">

Function to get input and assigns it to variable

I'm trying to make something using javascript/jquery that is similar to java.
The way to get input in java:
String x = JOptionPane.showInputDialog("Enter a value: ");
.showInputDialog shows GUI and submits a value after "Submit" is clicked.
This is what I've tried: https://jsfiddle.net/1t5pxhj5/2/
This behavior is not possible with Javascript.
You should use events and callbacks to retrieve the specified value.
Your Java code:
String x = JOptionPane.showInputDialog("Enter a value :");
Your Javascript code:
function showInput(message, callback) {
// display dialog
// ...
callback($("input").val()); // this should be returned to getInput after Submit is clicked
});
showInput("Enter a value:", function(x) {
// do something now
});
<input type="text" name="txt" id="txt"/>
<input type="button" onclick="gettext('txt');"/>
to retrieve data use code below
function gettext(id) {
var entereddata = document.getElementById(id);
var value = entereddata.value;
}
Hope my code works. Keep coding
Supposing you have
<input type="text" class="my-input">
<button>click me!</button>
you can retrieve input value in jQuery/Javascript with this instruction;
$(".my-input").val();
if you want to bind the data retrieval to the "click me!" button there is the complete code:
$(".click-me").click(function() {
alert($(".my-input").val());
});

Change "this" to a variable name within name space

I am doing a project that need to be done by using name space. I have some troubble getting it to work when I need to change "this" to an actually
variable name.
Thus.
I created a name space $work.
Then a class named $work.Guess (then I renamed it to "game")
Then a method named point. (the method fires from onclick on a button)
I have tried to change "this" to something else.. In my mind it SHOULD be game.point, but that did not work. So I then tried with "var point". Neither of them worked with the onclick event from the button. Then I have tried to reach the method with every name I could think would work instead of "this". Failed.
Here is a sample code.
var $work = {};
$work.Guess = function() {
this.point = function() {
alert('found' + " " + 'point');
}
}
var game = new $work.Guess;
<form name="foo">
<h2>Check scores</h2>
<input type="button" value="Check points" onclick='game.point();' />
<br />
</form>
You are right wanting to get rid of the this here. Adding instance methods this way to an object is wasteful, as it creates a new copy of the function for each object. In Javascript, "class method inheritance" (as it's classically called) is done through the prototype:
$work.Guess = function () { };
$work.Guess.prototype.point = function () {
alert('found point');
};
var game = new $work.Guess();
game.point();
And I'd be amiss not to also point to the nicer ES6 class syntax here.
Try this
var $work = {};
$work.Guess = {
point: function() {
alert('found' + " " + 'point');
}
};
var game = $work.Guess;
Update:
No idea what the downvotes are for. Either way, the above works just fine.
<form name="foo">
<h2>Check scores</h2>
<input type="button" value="Check points" onclick='game.point();' />
<br />
</form>

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.

Categories

Resources