simple task javascript buttons in html - javascript

Can someone please help me make a button which prints thank you when clicked? I know there are lots of ways to do this but in my circumstance, I need to use an if statement and this has me totally stumped. I have not done much because I am totally unsure of what syntax to use. I have made a website for a school project and it has a form on one of the pages. It is a requirement to use javascript to do something with an if statement. I would like to have a button at the bottom of the form which does something to the page when clicked. I don't really mind what happens but I thought a thank you message would be nice.
Cheers :)
<!DOCTYPE html>
<html>
<body>
<button id="sub">Subscribe</button>
</body>
<script>
function button () {
var message = document.getElementById("message");
if (sub.onclicked == true) {
/*Pop up with thank you*/
};
};
button ();
</script>
</html>

If you need if then you can test if button was clicked only once. But first thing is that you need an event that will fire when button is clicked, and document.getElementById value need to match you html id attribute.
function button () {
var message = document.getElementById("sub");
var cliked = false
message.onclick = function() {
if (!cliked) {
cliked = true;
alert('Thank you');
}
};
}
button();
<button id="sub">Subscribe</button>

The key issue here is you're trying to introduce code that has no use. For example here's how you add a message to the page when you click a button:
const button = document.querySelector('#sub');
const message = document.querySelector("#message");
button.addEventListener('click', handleClick, false);
function handleClick(event) {
message.textContent = 'Hallo';
};
<button id="sub">Subscribe</button>
<div id="message" />
There's no room for an if statement here given the basic code example you have in your question. Your assignment may even be marked down if you start adding unnecessary code. That's why I suggested having a look at your requirements and changing them.
For example you might decide you want two buttons that give different messages when you click on them, using an if statement to differentiate between them:
// Because we have two buttons we use a class instead of an id
// and we can pick them up with `querySelectorAll`
const buttons = document.querySelectorAll('.sub');
const message = document.querySelector("#message");
// Instead of attaching one event listener to one element we
// loop over our buttons and attach an event listener to each one
buttons.forEach(button => button.addEventListener('click', handleClick, false));
function handleClick(event) {
// We destructure the dataset id from the button that was clicked
const { target: { dataset: { id } } } = event;
// And we use an if statement to choose between two different messages
if (id === 'msg1') message.textContent = 'Hallo';
if (id === 'msg2') message.textContent = 'Secret message!';
};
<!-- Each button has its own data attribute -->
<button data-id="msg1" class="sub">Button 1</button>
<button data-id="msg2" class="sub">Button 2</button>
<div id="message" />
Further reading:
querySelector and querySelectorAll
Destructuring assignment
Data attributes
addEventListener

<button id="sub">Subscribe</button>
<script>
document.getElementById("sub").addEventListener("click", () =>{
document.write("thank you");
});
</script>
or, if you don't want it to remove all your elements:
<button id="sub">Subscribe</button>
<p id="text"></p>
<script>
document.getElementById("sub").addEventListener("click", () =>{
document.getElementById("text").innerHTML = "thank you!";
});
</script>

<!DOCTYPE html>
<html>
<body>
<button id="sub" onclick="button(event)">Subscribe</button>
<script>
function button(event) {
var message = document.getElementById("message");
if (event) {
/*Pop up with thank you*/
alert("Thank you");
}
};
</script>
</body>
</html>

Related

JavaScript While loop in a onClick function not responding

<body>
<button onclick="yesClick()">Click me for a suprise word!</button>
<script>
function yesClick() {
alert("Are you sure?")
alert("Check again... but first click ok")
let element = document.createElement("div");
element.innerText = clickMe;
let clickMe = "Gigachad"
// Loop
while (true) {
document.body.appendChild(element)
}
}
</script>
</body>
Click on the button, two alerts pop up saying "Are you sure?" and "Check again... but first click ok"). When clicked, the while loop should run infinitely since it's a while true loop, right? Well not for me... When clicked a new div should be added with a text inside stating "Gigachad" (don't judge it's just practice) but it doesn't work.
I reviewed the code, had my group partner check it out but didn't work
Your while loop will run forever because true will always be true and there's nothing in the loop that will change that. In fact, the loop is not even necessary and is probably causing the browser to lock up.
Also, your let statements must precede your use of the let variables.
<button onclick="yesClick()">Click me for a suprise word!</button>
<script>
function yesClick() {
alert("Are you sure?")
alert("Check again... but first click ok")
let element = document.createElement("div");
let clickMe = "Gigachad"
element.innerText = clickMe;
document.body.appendChild(element)
}
</script>
Now, you also really shouldn't be using inline event attributes to set up event handlers as that is a 25+ year old legacy way to work with events. And, instead of an alert when you are asking a question, use a confirm.
<button type="button">Click me for a suprise word!</button>
<script>
document.querySelector("button").addEventListener("click", function() {
if(confirm("Are you sure?")) {
alert("Check again... but first click ok")
let element = document.createElement("div");
element.textContent = "Gigachad";
document.body.appendChild(element);
}
});
</script>

I keep getting an error Uncaught ReferenceError: nothingButton is not defined

So I keep getting this error nothingButton is not defined. But I defined it. Does anybody know what is happening?
JavaScript:
function nothingButton() {
$("#button-nothing").on('click', function() {
$(this).prop('disabled', true);
const p = document.createElement('p');
p.innerText = "Well, except for this";
document.querySelector('#button').appendChild(p);
})
}
HTML:
<div id="button">
<button id="button-nothing" onclick='nothingButton()'>This button does nothing</button>
</div>
I also have the javascript file source in my html file.
Well, the code above is actually fine.
It might be something else at your code or just some typography errors.
Except the fact that you might get 2 of "Well, except for this" message since every time you click the button, it attach another onclick listener.
Here is what I re-create for you :
<html>
<head>
<!-- Use jquery from cdnjs here -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div id="button">
<button id="button-nothing">This button does nothing</button>
</div>
<script>
function nothingButton() {
$("#button-nothing").on('click', function () {
$(this).prop('disabled', true);
const p = document.createElement('p');
p.innerText = "Well, except for this";
document.querySelector('#button').appendChild(p);
});
}
// Attach the event listener once.
nothingButton();
</script>
</body>
</html>
Initial state :
Button clicked state :

Javascript click function not working

I'm trying to write a simple javascript function that will clone some html input fields when the user clicks a button, but for some reason the button's click function isn't being called when I click it. Any ideas why?
Here's the javascript:
<SCRIPT LANGUAGE="JavaScript">
$(document).ready(
function(){
$("#default-label").hide();
$("#default-element").hide();
var counter = parseInt($("#counter").val());
$("#addProduct").click(
function(){
var product = $('#fieldset-default');
var newProduct = product.clone(true);
newProduct.insertAfter(product);
document.getElementById("addProduct").innerHTML = 'Add More';
$("#counter").val(++counter);
}
);
}
);
</script>
My HTML for the button:
<button id="addProduct" type="button" name="add">Add Product</button>
i think you missed jquery plugin,included latest version of jquery library, if not there.

Javascript: Changing variable on button click

I have a javascript file linked to index.html like below:
<script src='game.js' type='text/javascript'>
</script>
Assume that game.js contains:
var speed = ...;
Along with some other content.
I have 3 buttons on the HTML page that when clicked I want to change the variable speed in the javascript. Once clicked I want all 3 buttons to be disabled or hidden until the reset button is clicked. Any idea how I go about this?
Using pure HTML/JavaScript, here's what I would do:
<form name="form1">
<span id="buttons">
<input type="button" name="button1" value="Speed1"/>
<input type="button" name="button2" value="Speed2"/>
<input type="button" name="button3" value="Speed3"/>
</span>
<input name="reset" type="reset"/>
</form>
<script type="text/javascript">
var speed, buttonsDiv=document.getElementById("buttons");
for (var i=1; i<=3; i++) {
var button = document.form1["button" + i];
button.onclick = function() {
speed = this.value;
alert("OK: speed=" + speed);
buttonsDiv.style.display = 'none';
};
}
document.form1.reset.onclick = function() {
speed = null;
alert("Speed reset!");
buttonsDiv.style.display = 'inline';
return true;
};
</script>
Here is a working example: http://jsfiddle.net/maerics/TnTuD/
Create functions within your javascript files that attach to the click events of each button.
The functions would change the variable you want.
aButtonelement.addEventListener('click',functionToChangeVariable,false)
Include the following in your Javascript file:
function DisableButtons() {
speed = 100;
document.getElementById("btn_1").disabled = true;
document.getElementById("btn_2").disabled = true;
document.getElementById("btn_3").disabled = true;
}
function EnableButtons() {
document.getElementById("btn_1").disabled = false;
document.getElementById("btn_2").disabled = false;
document.getElementById("btn_3").disabled = false;
}
In your HTML, assign the following onClick events:
<button onClick="DisableButtons();">Button 1</button>
<button onClick="DisableButtons();">Button 2</button>
<button onClick="DisableButtons();">Button 3</button>
<button onClick="EnableButtons();">Reset</button>
something like this? http://jsfiddle.net/qMRmn/
Basically, speed is a global variable, and clicking a button with the class set-speed class will set the speed to a new value, and disable all of the set-speed buttons. Clicking the reset button will re-enable them.
The code should be fairly self explanatory.
Easiest way, use jQuery.
$("#idofbutton").click(function () {
// change variables here
});
Or you could register an event:
document.getElementById("idofbutton").addEventListener('click', function () {
// change variables here
}, false);
Source

Change onclick action with a Javascript function

I have a button:
<button id="a" onclick="Foo()">Button A</button>
When I click this button the first time, I want it to execute Foo (which it does correctly):
function Foo() {
document.getElementById("a").onclick = Bar();
}
What I want to happen when I click the button the first time is to change the onclick function from Foo() to Bar(). Thus far, I've only been able to achieve an infinite loop or no change at all. Bar() would look something like this:
function Bar() {
document.getElementById("a").onclick = Foo();
}
Thus, clicking this button is just alternating which function gets called. How can I get this to work? Alternatively, what's a better way to show/hide the full text of a post? It originally starts shorted, and I provide a button to "see the full text." But when I click that button I want users to be able to click the button again to have the long version of the text go away.
Here's the full code, if it helps:
function ShowError(id) {
document.getElementById(id).className = document.getElementById(id).className.replace(/\bheight_limited\b/, '');
document.getElementById(id+"Text").className = document.getElementById(id+"Text").className.replace(/\bheight_limited\b/, '');
document.getElementById(id+"Button").innerHTML = "HIDE FULL ERROR";
document.getElementById(id+"Button").onclick = HideError(id);
}
function HideError(id) {
document.getElementById(id).className += " height_limited";
document.getElementById(id+"Text").className += " height_limited";
document.getElementById(id+"Button").innerHTML = "SHOW FULL ERROR";
document.getElementById(id+"Button").onclick = "ShowError(id)";
}
Your code is calling the function and assigning the return value to onClick, also it should be 'onclick'. This is how it should look.
document.getElementById("a").onclick = Bar;
Looking at your other code you probably want to do something like this:
document.getElementById(id+"Button").onclick = function() { HideError(id); }
var Foo = function(){
document.getElementById( "a" ).setAttribute( "onClick", "javascript: Boo();" );
}
var Boo = function(){
alert("test");
}
Do not invoke the method when assigning the new onclick handler.
Simply remove the parenthesis:
document.getElementById("a").onclick = Foo;
UPDATE (due to new information):
document.getElementById("a").onclick = function () { Foo(param); };
Thanks to João Paulo Oliveira, this was my solution which includes a variable (which was my goal).
document.getElementById( "myID" ).setAttribute( "onClick", "myFunction("+VALUE+");" );
I recommend this approach:
Instead of having two click handlers, have only one function with a if-else statement. Let the state of the BUTTON element determine which branch of the if-else statement gets executed:
HTML:
<button id="a" onclick="toggleError(this)">Button A</button>
JavaScript:
function toggleError(button) {
if ( button.className === 'visible' ) {
// HIDE ERROR
button.className = '';
} else {
// SHOW ERROR
button.className = 'visible';
}
}
Live demo: http://jsfiddle.net/simevidas/hPQP9/
You could try changing the button attribute like this:
element.setAttribute( "onClick", "javascript: Boo();" );
What might be easier, is to have two buttons and show/hide them in your functions. (ie. display:none|block;) Each button could then have it's own onclick with whatever code you need.
So, at first button1 would be display:block and button2 would be display:none. Then when you click button1 it would switch button2 to be display:block and button1 to be display:none.
For anyone, like me, trying to set a query string on the action and wondering why it's not working-
You cannot set a query string for a GET form submission, but I have found you can for a POST.
For a GET submission you must set the values in hidden inputs e.g.
an action of: "/handleformsubmission?foo=bar"
would have be added as the hidden field like: <input type="hidden" name="foo" value="bar" />
This can be done add dynamically in JavaScript as (where clickedButton is the submitted button that was clicked:
var form = clickedButton.form;
var hidden = document.createElement("input");
hidden.setAttribute("type", "hidden");
hidden.setAttribute("name", "foo");
hidden.setAttribute("value", "bar");
form.appendChild(hidden);
See this question for more info
submitting a GET form with query string params and hidden params disappear

Categories

Resources