Reputation: 31
I am 16 and I am pretty new to Web Development. I have been writing a bunch of programs for practice and I got stuck on this one.
I made buttons in html with input tags. So now I want to make those buttons do something in a javascript function, and nothing has worked out for me.
I'd really appreciate some sample code that I can learn from.
My html and javascript looks like this:
function selectPrize() {
var butn1 = document.getElementById.onclick();
if (butn1) {
alert("You won a new Car");
}
}
<input type="button" id="btn1" value="ClickMe" onclick="selectPrize()">
Upvotes: 1
Views: 7857
Reputation: 43
Simple example.
Actually just edited and added some little functionality to stimulate your imagination on what could you do.
var flag = 1;
function myFunction() {
if (flag === 1) {
document.getElementById("demo").innerHTML = "Paragraph changed!";
flag=-1;
} else {
document.getElementById("demo").innerHTML = "No result... again";
flag=1;
}
}
.box {
display: block;
}
.button {
background-color: #fff;
border: 1px solid #dbdbdb
}
.button:hover {
background-color: #dbdbdb;
border: 1px solid #f0f
}
<div class="box">
<h3> Example execute javascript on button click </h3>
<div class="elements">
<button class="button" onclick="myFunction()">Click me</button>
<p id="demo">No result</p>
</div>
</div>
Upvotes: 0
Reputation: 1324
Create a function
<script>
function doSomething() {
alert('Did something');
}
</script>
Call the function when an event occurs on your button (in this case click event)
<input type="button" onclick="doSomething()" value="Do Something" />
Upvotes: 1