Syed Daniyal Shah
Syed Daniyal Shah

Reputation: 303

passing ruby variables to javascript (Ruby on Rails)

I have a list of medicines and a list of vaccinations that I am extracting from tables medicines and vaccinations respectively. The list of medicines is of the format medicine_name and so is the list of vaccinations. I store both of these in vars using this piece of code.

var injections=<%=@injections%>;
var medicines=<%=@medicines%>;

In my view I have select tags for medicines and injections but when I try to append these vars to the respective tags using the following code. I don't get any results please help

$('.addmedicines').click(function()
   $('.medicines').append(medicines);


});
$('.addinjections').click(function(){
   $('.injections').append(injections);
});

Here .injections is the class assigned to select tag for vaccinations. .medicines is the class assigned to select tag for medicines. And .addmedicines and .addinjections are html buttons.

EDITED:

When I try to display both injections and medicines in javascript they display like this:

Medicines:

<option>Med1</option><option>Med2</option><option>Med3</option><option>Med4</option>

Injections:

<option>i1</option><option>i2</option><option>i3</option><option>i4</option>

Upvotes: 9

Views: 21197

Answers (3)

ahnbizcad
ahnbizcad

Reputation: 10807

You're missing a { after the first function

Should be:

$('.addmedicines').click(function(){  // <-- right here :)
   $('.medicines').append(medicines);


});
$('.addinjections').click(function(){
   $('.injections').append(injections);
});

What you have:

$('.addmedicines').click(function()   // <-- right here :)
   $('.medicines').append(medicines);


});
$('.addinjections').click(function(){
   $('.injections').append(injections);
});

Upvotes: -1

Blue Smith
Blue Smith

Reputation: 8820

You can use Rails helper array_or_string_for_javascript, or just simply call to_json:

var injections = <%= array_or_string_for_javascript(@injections) %>;
var medicines = <%= array_or_string_for_javascript(@medicines) %>;

// OR

var injections = <%= @injections.to_json %>;
var medicines = <%= @medicines.to_json %>;

Upvotes: 6

Salil
Salil

Reputation: 47532

var injections= '<%=@injections%>';
var medicines='<%=@medicines%>';

Upvotes: 23

Related Questions