Change onclick function in javascript - javascript

the code below is used to change the onclick event when pressed, however it only alters the function of the parameter, which it simply will not do.
function addWhere(nameID)
{
document.getElementById('addWhereButton').setAttribute("onclick",addWhere(nameID++), false);
document.getElementById('addWhereButton').onclick = function () {addWhere(nameID++)};
}
neither code works and no one else seems to have asked this specific questions before.
Thanks
EDIT
Further testing shows something complete bizarre, a bit of code to display the nameID like so
document.getElementById('Testing').innerHTML = nameID++;
shows that nameID is actually getting incremented, but the number passed by the onclick never changes.

Like:
function addWhere(nameID) {
console.log(nameID);
};
let nameID = 1;
document.getElementById('addWhereButton').onclick = function () {addWhere(nameID++)};
<button id="addWhereButton">click to increment nameID</button>

Related

Qualtrics API functions not working within custom function called in EventListener

I defined a custom function in the header section that checks, alerts the user, and resets the value of a particular slider bar when it fails certain restrictions.
This function works beautifully when called on question clicks:
this.questionclick = chkVals;
I would like to also run the function when the user are exiting the text input field (as some users are using the keyboard to do the survey). I implemented an Event Listener for each sliders' text input field that runs the function when the focus is out of the text input field.
// choices is an array of choice ids
for (i = 0; i < choices.length; i++) {
var x = document.getElementById(choices[i]);
x.addEventListener("blur", chkVals, true);
};
I know that the event listener works, because the correct alerts are popping up. It is just not able to reset the values as this.setChoiceValue is not a function within the environment. I have tried setting var that = this; and calling that.setChoiceValue in the function, but it still does not work.
Any help will be greatly appreciated!
You haven't shown all your code, so I'm making some assumptions.
this is the Qualtrics question object in the addOnload function. Since chkVals is outside the addOnload function, this (or that) is undefined. So, you need to pass it in your function call (function chkVals(qobj)) then use qobj.setChoiceValue in the chkVals function. Then your function calls become:
this.questionClick = chkVals(this);
and
x.addEventListener("blur", chkVals(this), true);
#T. Gibbons 's answer helped me get to this point. As suggested I needed to add a parameter to chkVals() to be able to reference the this object. However,
this.questionClick = chkVals(this);
does not work due to this being a reserved object, so the whole header script will not run. I ended up changing all reference of this to that in my custom function and adding the parameter that as suggested:
function chkVals(that) {
...
... that.setChoiceValue(x, y)
}
To call the function with a parameter, I had to explicitly defined an anonymous function that called chkVals, otherwise it will not work (I am not sure why):
var that = this;
this.questionclick = function() {chkVals(that);}
for (i = 0; i < choices.length; i++) {
var x = document.getElementById(choices[i]);
x.addEventListener("blur", function() {chkVals(that);}, true);
};
The above works!

How to use a variable after it was a jquery function has run

I realise similar questions have been asked before but still dont understand what is happening with my code. I want to access the variable seq outside of the jQuery function after the user has inputed their sequence into the textarea. The console.log inside the jquesry function returns the inputed sequence but the console.log outside of the jQuery function(where I eventually want to put some other code to analyse the sequence) runs before the jquery function and returns an empty string. How can I make the code that uses the var seq only run after the submit button is clicked? Thanks!
var seq = "";
$("#subSeqType").on("click", function() {
if ($("#proteinButton").is(":checked")) {
$("#newTextArea").append("<textarea name = 'sequence' rows = '10' cols = '80' placeholder = 'Enter Protein Sequence here' > < /textarea><br>");
}
if ($("#dnaButton").is(":checked")) {
$("#newTextArea").append("<textarea name = 'sequence' rows = '10' cols = '80' placeholder = 'Enter DNA Sequence here' > < /textarea><br>");
}
$("#subSeqType").remove();
$("#newTextArea").append("<input id = 'subSeq' type='Submit'>");
$("#subSeq").on("click", function() {
seq = $("textarea:input[name=sequence]").val();
console.log(seq);
});
});
console.log("The sequence " + seq);
Im gonna try to explain this but you should read a little about how a code works and runs.
Lets state to types of code statement:
Run time code
Run time code is every line of code that run when it is loaded by the browser
Run when call code
Run when call code is the code that will run after an event has occured.
Uniting this concepts:
When you create a listener, the rule that creates that listener is a run time code. But the code inside that listener will only run when called for.
I made a small example of this bellow, your problkem is not at changing the variable but when you are printing.
The printer button will print the var value
The cahnge calue will change that value one time
Hope this helps :)
let myVar = "before";
console.log(myVar);
function myFun(){
myVar = 'after';
}
function printer(){
console.log(myVar);
}
console.log(myVar);
<button onclick="myFun()">change value</button>
<button onclick="printer()">print</button>
You seem to using "click" event inside another "click" event.
An event action triggers and performs its operation and does not wait for another event inside or outside.
If you want variable value after certain operation of event, you need to assign it to variable and work when the event is triggered and operating.

Javascript Button OnClick not working, method runs normally

I am trying to create a button in Javascript, that when clicked will send an AJAX Request to some PHP Code.
I have already setup 3 buttons that do the same thing and they are all working fine.
The most bizarre thing is that if I call the method directly it runs fine.
The code for the button:
<button id="toggle-button">Toggle</button>
The Javascript:
var toggleButton = document.getElementById('toggle-button');
...
function init()
{
...
toggleButton.onClick = handleToggleClick;
...
}
function handleToggleClick(event)
{
alert("Sending Request");
var admin_url = "http://localhost/wp-admin/admin-ajax.php";
var data = {
action : 'toggle',
}
$.post(admin_url, data, function(resp) {
alert(resp);
});
}
I have called the following in the Chrome Developer Tools Console:
handleToggleClick(null); // The request is sent
autoScheduleButton.onClick(); // The request is sent
autoScheduleButton.onClick; //It prints out the function
autoScheduleButton; //It displays the HTML of the button.
As I mentioned before there are 3 other buttons which do practically the same thing and work fine, so I really can't see why this isn't working.
Hopefully this is just something really obvious i missed.
EDIT:
Originally I made an error while anonymising the code, the code above is now correct in the init method.
Previous code:
function init()
{
...
toggleButton.onClick() = handleToggleClick;
...
}
In init function you have code like toggleButton.onClick() = handleToggleClick;. This means that you assign to the result of the onClick() function to the handleToggleClick.
You need to assign to onClick and not call it.
Try this instead toggleButton.onClick = handleToggleClick;
function init()
{
...
toggleButton.onClick = handleToggleClick;
...
}
The code toggleButton.onClick() = handleToggleClick; in the init function is not a right assignment. It actually means You are calling onClick function on toggleButton and then assigning to the result handleToggleClick.
change it ti toggleButton.onClick= handleToggleClick meaning you are listening to a click event on toggleButton and then calling function handleToggleClick

How to handle events simpler in javascript?

As a beginner with javascript, I am following this tutorial . At the top of that page simple forms and the use of an event handler is explained, while at the bottom of the page an exercise to create a simple calculator is given calculator.html.
I have come up with a very cumbersome solution to handle events when a number or operation is pressed. Here is what I have implemented:
function pressingNumber(number) {
document.getElementById("calc-output").innerHTML = number;
}
function press1() {pressingNumber(1);}
function press2() {pressingNumber(2);}
function press3() {pressingNumber(3);}
var button1 = document.getElementById("button-1");
var button2 = document.getElementById("button-2");
var button3 = document.getElementById("button-3");
button1.onclick = press1;
button2.onclick = press2;
button3.onclick = press3;
Is this the way to go? Is there a simpler way? I tried the following syntax which does not seem to work:
function pressingNumber(number) {
document.getElementById("calc-output").innerHTML = number;
}
var button1 = document.getElementById("button-1");
var button2 = document.getElementById("button-2");
var button3 = document.getElementById("button-3");
button1.onclick = pressingNumber(1);
button2.onclick = pressingNumber(2);
button3.onclick = pressingNumber(3);
Look at this line of code:
button1 = document.getElementById("button-1");
What does it do? It calls the function document.getElementById and assigns its return value to button1.
Now look at this line of code:
button1.onclick = pressingNumber(1);
What does this do? It calls the function pressingNumber and assigns its return value to button1.onclick.
So what does pressingNumber(1) return? Well, nothing, since pressingNumber has no return statement.
So you're assigning nothing to button1.onclick, and then wondering... why is it doing nothing? ;)
One of the things you'll learn is that if you just read your code aloud, explaining what it does step by step, you'll quickly solve your own problems. I have a rubber duck on my desk that I explain things to, and most of the time that's all I need to solve a problem.
In this case, you want to stick with the original code. It assigns the function itself, it doesn't call it. It is only called when onclick triggers.
In this particular case, this is your shortest method
<input type="button" value="1" onclick="pressNumber(1)">
<input type="button" value="2" onclick="pressNumber(2)">
function pressNumber(number) {
document.getElementById("calc-output").innerHTML = number;
}
The problem in your original code was that you are calling a function with ()in a place where you have to assign a function.
Note that onclick events always come with a link to the div that triggered the event. You should make use of that to capture which button was clicked. e in below function will refer to the clickevent. e.target will refer to the div, e.target.id will refer to the id of said div.
function buttonClicked(e){
console.log(e.target.id);
console.log('clicked in',document.getElementById(e.target.id).parentNode.id);
}
You could then attach said function to your div like so.
document.getElementById(buttonDivName).addEventListener("click", buttonClicked)
You can use
button1.addEventListener("click", pressingNumber(1));
button2.addEventListener("click", pressingNumber(2));
button3.addEventListener("click", pressingNumber(3));

How can I add a link to dynamically created button?

Once the buttons are created, is there anyway I can add a link or use window.location method like this: `window.location = 'nextpage.html?foo=number'. I currently have this
var typeValue = location.search;
var typeStringValue= typeValue.replace("?type=","");
var containers = typeValue.replace("?type=multi","");
var containersValue = parseInt(containers);
var sampleLetter = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
function createButton(buttonName){
var buttonDivBlock = document.getElementById("sampleSets");
var buttonElement = document.createElement("input");
buttonElement.setAttribute("type","button");
buttonElement.setAttribute("name",buttonName);
buttonElement.setAttribute("value","Sample Set"+" "+buttonName);
buttonElement.setAttribute("id",buttonName);
buttonDivBlock.appendChild(buttonElement);
// document.getElementById(sampleLetter[i]).setAttribute('onclick',window.location='SampleInfo.html'+typeStringValue+bottonName);<!--add the button link -->
}
function setButtons(numberOfContainers){
for(i=0;i<numberOfContainers;i++){
createButton(sampleLetter[i]);
}
}
window.onload = function(){
setButtons(containersValue);
}
But document.getElementById("'"+sampleLetter[i]+"'").setAttribute('onclick',window.location='SampleInfo.html'+typeStringValue+bottonName);<!--add the button link -->
returns a null value.
Well, maybe I can help you along with an example:
function getFive() { return 5;}
callOtherFunction("stringArgument", getFive());
The second argument to callOtherFunction is going to be 5, not the getFive function. In many cases, like adding event listeners and AJAX code, you actually want to pass the function itself as an argument, so it can be called later. But if you don't want to bother declaring that function seperately, it looks like this:
callOtherFunction("stringArgument", function() { return 5; });
To make code look cleaner, you can press Enter after the { and make a multi-line function.
Now, all that in mind, take another look at the line you've commented out. Do you see what's missing? (PS. Apologies for the "egging-on" format - I find people get much better at figuring things out if I help them find the solution, rather than just showing it to them)
The sampleLetter variable is not defined where you are trying to use it (judging by commented code). Use the value you had just set to the id attribute a few lines earlier.
document.getElementById(buttonName).setAttribute( /* ... */ );
Or if you are trying to set it in the loop instead of in the createButton function, do not add the single quotes
document.getElementById(sampleLetter[i]).setAttribute( /* ... */ );

Categories

Resources