Saghir A. Khatri Saghir A. Khatri - 10 months ago 49
jQuery Question

Using Ruby on Rails tag in JavaScript

I have an html button in

file. This button generates html controls and appends in table. It was working fine when there was no ruby on rails script involved. But now i have
of RoR. This submits my page. My complete code as asked in comments is as follows:

<script type="text/javascript">

$(document).ready(function() {
$("#AddSch").click(function() {
var hidval = $('#valEdu').val();
if(hidval == 0)
hidval = 1;

var rownum=$("#Controls > tbody > tr").length;
var updated_row_num;
if (rownum == 0)
else {
var newRow = "<tr><td align='center' style='font-size: x-large; color: #212121;' height='35px'>" + input1 + " <%= select_tag('university', options_from_collection_for_select(@Universites, 'id', 'University'),{:prompt => 'University'}) %></td></tr>";
var control = "<tr><td align='center'><button type='button' class='btn_rmv'>Remove</button></td></tr>";

return false;

$('#Controls').on('click', '.btn_rmv', function() {
var index = $(this).closest('tr').index() + 2
$('#Controls tr:nth-child(n+' + (index - 3) + ')').remove();
return false;


<h2 class = "subtitle">
<%= form_for (:Educations) do |f| %>
<table width="100%">
<tr style = "text-align:center;">
<%= :chapter,options_from_collection_for_select(@Chapters, "id", "Chapter"), :include_blank => "Chapter",:id => "DDL_Students",:style => "margin-top: 10px" %>

<%= :University,options_from_collection_for_select(@Universites, "id", "University"), :include_blank => "University",:id => "DDL_Students",:style => "margin-top: 10px" %>
<td align="center">
<table id="Controls">

<div><input id="AddSch" value="Add" type="button" /></div>
<input id="valEdu" type="hidden" value="0" />

<table width="92%">
<td align="center">
<div class="button" style="margin-left:60px;">
<%= f.submit "Next", { :class => "buttonSearch"} %>
<% end %>

changes it to textbox and if I use
it never calls that javascript. How can I make it work?

Answer Source

there's two pointers that I can give you, I can't really reproduce as I dont have your model and controller action setup.

1. You do not want to randomly up or downcase your variables as in: :University,options_from_collection_for_select(@Universites, "id", "University"), :include_blank => "University",:id => "DDL_Students",:style => "margin-top: 10px"

Instead you want: :university, options_from_collection_for_select(@universities, "id", "university_name"), :include_blank => "University",:id => "DDL_Students",:style => "margin-top: 10px"

Ideally you wouldn't want the inline styles too, but we'll let that slip for now ;-)

2. I could the variable "input1" is not defined, have a look into your devtools console (F12) and check if there are any JS errors over there.

Hope that helps, Jan