JS onclick only works the first time - javascript

I am new to JS. I am creating a button and I want the button to toggle what it says. I can get it to fire once, but then it won't fire again unless i refresh the page. What am I doing wrong? I'm sure its simple.
JS function:
<script type="text/javascript">
function fullscreen(){
var elem = document.getElementById("button1");
if (elem.value=="Maximize"){
elem.value = "Minimize";
}else {
elem.value = "Maximize";}
}
</script>
in the body of the page is:
<div>
<input type="button" id="button1" value="Minimize" onclick='fullscreen()'>
</div>
What I expect is the text of the button will switch when the variable is passed through the if statement. I can get it to change from "minimize" to "maximize" onclick, but the second click does nothing.

Hey i did put alert and your code is working fine. You can even see this in your developer console. Also you should put === instead of == for comparing to string.
There should be other problem i think.
function fullscreen(){
var elem = document.getElementById("button1");
if (elem.value ==="Maximize"){
alert('hi');
elem.value = "Minimize";
} else {
alert('hello');
elem.value = "Maximize";}
}

Related

Run a function if a button has ever been clicked, even on page reload

I have a button:
<script>
function never(){
alert('This is place holding text');
}
</script>
<button onclick="never()">Understood</button>
I need to use local storage or cookies to remember if the button has ever been clicked, and if it has, to run the function and if it hasn't to not run the function until they click the button, I've had an idea...
Onload Run Function.
Check if button has been clicked, then run function.
Else do not run function.
If button is clicked set cookie or value to run function automatically now.
I have no idea how to actually implement this though, or if this won't work. And yes, I know the real solution would be server side, but I do not have a server.
You can check this implementation
You can just store some value to localStorage when clicked and then read those values later.
HTML
<button id="btn">Click Me</button>
JavaScript
const btn = document.querySelector("#btn");
if(localStorage.getItem('clicked')) btn.innerText = 'clicked once';
btn.addEventListener('click', handleClick);
function handleClick(event) {
if(localStorage.getItem('clicked')) return;
else {
localStorage.setItem('clicked', true);
btn.innerText = 'clicked once';
}
}
do u mean this way :
<button onclick="run()">Click</button>
function run(){
localStorage.setItem('item','value');
}
or something else ??
or try this way
var someData = 'any data.';
localStorage.setItem('myData', '')
function never(){
localStorage.setItem('myData', someData);
alert('This is place holding text');
}
var data = localStorage.getItem('myData');
if (data != ""){
never()
}
localStorage.removeItem('myData')
<button onclick="never()">Understood</button>

Facing problem in JavaScript function execution

I am trying to make a simple Shopping List App in which user can Add, Delete and mark the task done when completed. So far, I am able to add the task but facing problem in executing the done and delete functions. I am getting an error because when I execute it, the done and delete buttons are not there but what should I do to fix it?
var inp = document.getElementById("form");
var button = document.getElementById("click");
//Create List Function with Done and Delete Buttons
function addVal() {
var ul = document.getElementById("list");
var li = document.createElement("li");
var span = document.createElement("span");
var done = document.createElement("button");
var del = document.createElement("button");
li.appendChild(document.createTextNode(""));
span.appendChild(document.createTextNode(inp.value));
done.appendChild(document.createTextNode("Done"));
del.appendChild(document.createTextNode("Delete"));
li.appendChild(span);
li.appendChild(done);
li.appendChild(del);
done.setAttribute("class", "doneBut");
del.setAttribute("class", "delBut");
ul.appendChild(li);
inp.value = "";
}
//Get Input Length
function checkLength() {
return inp.value.length;
}
//Run function on Button Click
function onButtonClick() {
if (checkLength() > 0) {
addVal();
}
}
//Run function on Enter Keypress
function onEnter(event) {
if (checkLength() > 0 && event.which === 13) {
addVal();
}
}
//Trigger Events
button.addEventListener("click", onButtonClick);
inp.addEventListener("keypress", onEnter);
//Done and Delete Button Functions
var doneButton = document.getElementsByClassName("doneBut");
var deleteButton = document.getElementsByClassName("delBut");
function doneTask() {
doneButton.parentNode.classList.add("done");
}
function delTask() {
deleteButton.parentNode.classList.add("delete");
}
doneButton.addEventListener("click", doneTask);
deleteButton.addEventListener("click", delTask);
<input type="text" placeholder="Enter Your Task..." id="form" />
<button id="click">Add Task</button>
<h2>List:</h2>
<ul id="list"></ul>
Please Help.
Your problem is that the code tries to add events before the buttons exist. The buttons don’t exist until the addVal function gets called. Since addVal is not being called before the you try to add your event handlers, the getElementById returns null, and you attempt to add an event listener to null.
Additionally it looks like you’re planning to add multiple done and delete buttons. That wouldn’t normally be a problem, except you’re referencing them by ID, and IDs MUST be unique. You’ll need to switch this to a class or an attribute, since you’ll need one per item in the shopping cart.
You’ll probably want to look into event delegation, so that you can add your events once to the page before any buttons exist. https://javascript.info/event-delegation
It's most likely because your script is running before your code is running. Add the <script> tags just before the closing </body> tag to fix it:
<script>/* Your code here */</script>
</body>
You need to place this in a window.onload function, or run it in a function inside of the body tag's onload. Those elements don't exist yet when the script is run:
window.onload = function() {
var inp = document.getElementById("form");
var button = document.getElementById("click");
button.addEventListener("click", onButtonClick);
inp.addEventListener("keypress", onEnter);
}

FileUpload loses content on button click

I have a fileupload which loses its content on button click. I have a confirm button to freeze the page from user making any further changes. Once the changes are finalized, the button shall be renamed from Apply to Submit. But during this transition (Autopostback), fileupload loses its content.
To avoid this autopostback, I tried to fix this using javascript by freezing the textboxes and other controls but the button name doesn't change.
if (document.getElementById('<%=Submit.ClientID%>').value == "Apply") {
....
document.getElementById('<%=Remarks.ClientID%>').disabled = false;
document.getElementById('<%=Submit.ClientID%>').value == "Submit";
return false;
}
return true;
I also tried to use the below code snippet but dint work either. In both the cases, the text boxes were disabled but the button name dint change.
if (document.getElementById('<%=Submit.ClientID%>').value == "Apply") {
....
document.getElementById('<%=Remarks.ClientID%>').disabled = false;
document.getElementById('<%=Submit.ClientID%>').innerHTML == "Submit";
return false;
}
return true;
Have referred few sites but most of them suggest to use value or innerHTML. Not sure why it dint work here. Anything else am I missing?
Please suggest how to fix this.
Its not an if you dont have to put == just one and you want to change the value.
change
document.getElementById('<%=Submit.ClientID%>').innerHTML == "Submit";
to
document.getElementById('<%=Submit.ClientID%>').value = "Submit";
the easiest solution is to make sure that you load your JavaScript code after your button definition, or at the end of the file.
this is the correct form :
<button id="test"></button>
<script>
var b = document.getElementById("test");
b.innerHTML = "test" ;
</script>
not this :
<script>
var b = document.getElementById("test");
b.innerHTML = "test" ;
</script>
<button id="test"></button>
you can also use jQuery:
<button id="test"></button>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.4.min.js"></script>
<script>
$("#test").text("test");
</script>

How can I figure out what button was clicked on last?

How can I figure out what button was clicked on last? For example I have:
<input type="button" name= "zoomer" value="State View" id= 'States View' onclick="zoomout()"/>
<input type="button" name= "zoomer" value="County View" id= 'Counties View' onclick="countyView()"/>
But whenever I change a RADIO button, I want it to take into account which button was clicked last (County View or State View). Is it possible to do this?
You could keep a global JavaScript variable var last_clicked which is updated in the functions zoomout() and countyView(), and then check the value of last_clicked when you change the radio button. Alternatively, you can terminate the calls to the functions within the onclick event with a semicolon, then assign the value to last_clicked inside the onclick event string (although I wouldn't recommend it as it can make your code messy).
var lastClicked = "none";
function zoomout()
{
// your code
lastClicked = "states";
}
function countyView()
{
//your code
lastClicked = "county";
}
if(lastClicked == "county")
{
}
else if(lastClicked == "states")
{
}
it's possible by using an external variable such as
var clickedLast = "";
function zoomout() {
clickedLast = "stateview";
... your code ...
}
function countyView() {
clickedLast = "countyview";
... your code ...
}

How to tell if a button is clicked

I have this code:
<script type="text/javascript">
function changestate()
{
var StateTextBox = document.getElementById("State");
var IgnoreTextBox = document.getElementById("Ignore");
var PlayButton = document.getElementById("Play");
if(document.getElementById("Play").onclick == true)
{
StateTextBox.value = "Happy";
}
}
</script>
<input TYPE="button" VALUE="Play with Pogo" id="Play" onClick="changestate();"/>
I'm trying to know when the button is clicked, and have that if button is clicked in the if statement. I want to know this so I can change the value that is inside the text box. The problem is, I do not know how to tell when the button is clicked. If you could help me out that would be great.
The onclick attribute identifies what should happen when the user clicks this particular element. In your case, you're asking that a function be ran; when the function runs, you can rest assured that the button was clicked - that is after all how the function itself got put into motion (unless you invoked it some other way).
Your code is a bit confusing, but suppose you had two buttons and you wanted to know which one was clicked, informing the user via the stateTextBox value:
(function () {
// Enables stricter rules for JavaScript
"use strict";
// Reference two buttons, and a textbox
var playButton = document.getElementById("play"),
stateTextBox = document.getElementById("state"),
ignoreButton = document.getElementById("ignore");
// Function that changes the value of our stateTextBox
function changeState(event) {
stateTextBox.value = event.target.id + " was clicked";
}
// Event handlers for when we click on a button
playButton.addEventListener("click", changeState, false);
ignoreButton.addEventListener("click", changeState, false);
}());
You can test this code live at http://jsfiddle.net/Y53LA/.
Note how we add event-listeners on our playButton and ignoreButton. This permits us to keep our HTML clean (no need for an onclick attribute). Both of these will fire off the changeState function anytime the user clicks on them.
Within the changeState function we have access to an event object. This gives us some details about the particular event that took place (in this case, the click event). Part of this object is the target, which is the element that was clicked. We can grab the id property from that element, and place it into the value of the stateTextBox.
Here is the adjusted HTML:
<input type="button" value="Play with Pogo" id="play" />
<input type="text" id="state" />
<input type="button" value="Ignore with Pogo" id="ignore" />​
You can know if button clicked by using a flag (true or false).
var flag = false;
window.addEventListener("load", changestate, false);
function changestate() {
var StateTextBox = document.getElementById("State");
var PlayButton = document.getElementById("Play");
PlayButton.addEventListener("click", function () {
flag = true;
})
PlayButton.addEventListener("click", change)
function change() {
if (flag) {
StateTextBox.value = "Happy";
}
}
}
Looking back on this, many years later, you could simply do:
<script type="text/javascript">
function changestate(action)
{
var StateTextBox = document.getElementById("State");
var IgnoreTextBox = document.getElementById("Ignore");
var PlayButton = document.getElementById("Play");
if(action == "Play")
{
StateTextBox.value = "Happy";
}
}
</script>
<input TYPE="button" VALUE="Play with Pogo" id="Play" onClick='changestate("Play");'/>

Categories