1

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()">
1
  • 4
    please share your code Commented Jun 14, 2020 at 9:56

2 Answers 2

1

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" />
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you this worked. Is there a way I can add if-else conditions to check if the button was clicked.
The function will only be called if the click event is triggered on the button so you might not need the if-else to check for that. Maybe if you shed more light on what you are trying to do, I can give you suggestions?
I got it working now. Thanks for this, I should probably take a break though, Been 5 hours in front of the computer now.
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.