S Craig
S Craig

Reputation: 281

HTML image 'onclick' redirects to another page when calling javascript function (unwanted)

I have an HTML image which I want to click, which will trigger a javascript function to be called, which will make some changes to the page based on a ruby-generated collection_select. But whenever I try to call the function it redirects to another page (pages\main.html.erb), which is not what I want.

html image (and related code):

<%= f.collection_select :id,
    Customer.where(business_id: current_customer.business_id),
    :id,
    :full_name,
     { prompt: 'Select' },
     { id: "colleage-select", onChange: "renderColCal(this)" } %>

<input type="image" src="http://..." onclick="addParticipant()">

 ....

<p>Meeting Participants:</p>
 <ol id ="list">

 </ol>

javascript:

//application.js

var List = document.getElementById('list'); //found in events\new.html.erb

function addParticipant(){

    var name = document.getElementById('colleague-select').textContent; //gets :full_name of selected Customer
    var entry = document.createElement('li'); //creates new list element within ordered list 'list'
    entry.appendChild(document.createTextNode(name)); //adds :full_name to list element
    List.appendChild(entry); //adds list element to ordered list

}

I have substituted the code within 'addParticipant()' for alert('hello') and it worked fine without redirection, so what in my javascript code is causing the problem? Any help will be much appreciated, thanks.

Upvotes: 2

Views: 958

Answers (1)

Ho Man
Ho Man

Reputation: 2345

an alert dialog popup stops default click behaviour, but your code does not.

You will need to do that explicitly:

function addParticipant(e) {
  ...
  e.preventDefault();
}

Upvotes: 1

Related Questions