Reputation: 281
I have an HTML button:
<button>
<img id = "click-me" src="https:..." alt="Add to List" style="width: 50px"/>
</button>
Which, when clicked, should execute this JQuery code:
$(function () {
$("#click-me").click(function () {
document.getElementById('list').style.backgroundColor = "red";
});
});
But, instead of doing what I want it to do, clicking the button sends me to another page of my website. How do I stop this? Thanks
EDIT:
here is the full html of the page:
<div class="form">
<h1>Create A Meeting</h1>
<%= form_for(@newevent) do |f| %>
<%= f.text_field :name, :placeholder => "Title" %>
<!--< f.collection_select :location, Location.all, :id, :locName %> FOR WHEN LOCATIONS ARE A THING-->
<%= f.text_field :description, :placeholder => "Short Description" %>
<div>
<h2>Who's involved?</h2>
<p>select a colleague to compare their calendar with yours</p>
<%= f.collection_select :id,
Customer.where(business_id: current_customer.business_id),
:id,
:full_name,
{ prompt: 'Select' },
{ id: "colleage-select", onChange: "renderColCal(this)" } %>
<button id="click-me" type="button">
<img src="https://cdn4.iconfinder.com/data/icons/basic-ui-elements/700/07_plus-128.png" alt="Add to Event" style="width: 50px"/>
</button>
<div class = 'row'>
<div class = 'col-md-6' id = 'left-calendar-wrapper'>
<h3>Your calendar:</h3>
<%= render partial: '/calendars/show', locals: {} %>
</div>
<div class="col-md-6" id="calendar-wrapper">
<h3>Your colleague's calendar:</h3>
</div>
<div>
<p>Meeting Participants:</p>
<ol id ="list">
<li>list</li>
</ol>
</div>
</div>
</div>
<div>
<h2>when do you want it to start?</h2>
<%= f.datetime_select :starts_at, :placeholder => "when do you want it?" %>
</div>
<div>
<h2>when do you want it to end?</h2>
<%= f.datetime_select :ends_at, :placeholder => "when should it end?" %>
</div>
<%= f.submit "Create Meeting", class: "btn-submit" %>
<% end %>
</div>
</div>
</div>
The JQuery remains the same
Upvotes: 3
Views: 17762
Reputation: 167182
Add the id="click-me"
to the button
and not img
. And also, please add type="button"
for the button
.
Either add e.preventDefault()
or return false
:
$(function () {
$("#click-me").click(function () {
document.getElementById('list').style.backgroundColor = "red";
return false;
});
});
Or:
$(function () {
$("#click-me").click(function (e) {
e.preventDefault();
document.getElementById('list').style.backgroundColor = "red";
});
});
Upvotes: 12
Reputation: 5577
Button itself wouldn't do anything. I guess it is in form and when clicked it submits form. So You should prevent that:
$('#click-me').parents('form').on('submit', function(e){
e.preventDefault();
});
Or just add type="button"
to button. If no type is provided button is handled as submit button (type="submit"
).
<button type="button">
<img id = "click-me" src="https:..." alt="Add to List" style="width: 50px"/>
</button>
Paste more of Your HTML/JS, because looking at this code button shouldn't do anything
Upvotes: 1