Javascript multiple nested if statements don't work with Rails code - javascript

I have a method inside helper which fires an action which changes value of instance variable. Inside my javascript I've done this:
if(cat_id == 1)
{
<% cat_appointments(1) %>
}
else if(cat_id == 2)
{
<% cat_appointments(2) %>
}
else if(cat_id == 3)
{
<% cat_appointments(3) %>
}
My helper:
module StaticHelper
def cat_appointments(cat_id)
#appointments = Appointment.where(cat_id: cat_id)
end
end
The problems is that appointments are set like every time there is selected cat with id=3. If I put alert in those conditions, alert with selected id is displayed correctly when user selects specific cat.
Any ideas what is wrong with this code? How to change that variable?
When I replace:
else if(cat_id == 2)
{
<% cat_appointments(2) %>
}
with:
else if(cat_id == 3)
{
<% cat_appointments(3) %>
}
Then there are not always displayed appointments with cat_id=3. Now there are always displayed events with cat_id=2. So, the last 'else if' statement is always correct.
Thank you.

Can you try adding =
<%= cat_appointments(1) %>

Related

Rails helper method is called when I do not want to

I am trying to build a 4-choice quiz application using Ruby on Rails and JavaScript.
If you click one of the Choice Buttons at the Question View, a helper method "updateData(bool)" updates database and then you'll see the result without view transition. And if you click the Chart Button after answering, the view transitions to the Chart View.
However, the helper method "updateData" seems to be called not only by Choice Button but by Chart Button. It updates the database and increment the Question Number against my expectation.
According to the outputs from console.log, it is not likely that the Chart Button calls JavaScript function sendAnswer(ans).
I use Rails 5.0.1.
I would appreciate any advice. Thanks!
<head>
<script>
function sendAnswer(ans){
var questionID = getNumber();
var data = readCSV(questionID);
// True if answer number matches correct answer number
if(data[5] == ans ){
console.log("true")
<% updateData(1) %>
}else{
console.log("false")
<% updateData(0) %>
};
// Create Chart Button after answering
$("#bottom").append('<div id="showChart"></div>');
$("#showChart").html('<button id="showChartBtn" onclick="showChart()">Show Chart</button>');
};
</script>
<script>
function showChart(){
window.location.href = "/chart";
};
</script>
</head>
<body>
<% alphabets = ["A", "B", "C", "D"] %>
<!-- For loop to make A-D choices -->
<% for i in 0..3 %>
<button class="choice_btn" id="btn_<%= i %>" onclick="sendAnswer(<%= i %>);">
<%= alphabets[i] %>
</button>
<% end %>
<div id="bottom">
<!-- Chart Button comes here -->
</div>
</body>
# Return user according to remember token
def current_user
if (user_id = session[:user_id])
#current_user ||= User.find_by(id: user_id)
elsif (user_id = cookies.signed[:user_id])
user = User.find_by(id: user_id)
if user && user.authenticated?(:remember, cookies[:remember_token])
log_in user
#current_user = user
end
end
end
# Increment the Question Number, and increment the Correct Answer Number if true
def updateData(bool)
current_user.questionNum += 1
current_user.correctNum += bool
current_user.save
end
In the html code above, embedded Ruby <% updateData %> is executed while generating HTML.
I should instead call Controller Action by Button Click Event, and then call helper method via Action.

Copy contents to Clipboard

I have a need where in my application, I need to copy the URL that is rendered to the user. I am using the JS from this JSFiddle.
My code is slightly different from the HTML part of the Fiddle. I use mscConfirm for the JS message box.
My show.js.erb file,
<% if #exists == true %>
mscConfirm("Hold on", 'The file has been shared already, <%= #display %>', function(){
clipboard(this);
});
<% end %>
The function in the above code, is executed on clicking OK to the Message that appears. On doing Ctrl + C to the #display value in the screen, I still get 'undefined' when I try to paste it elsewhere.
My textfield output after pasting,
Any help is appreciated. Thanks in advance.
The provided clipboard() function accepts a DOM element. You will have to modify the function to suit your requirements.
function clipboard(el, txt) {
// deselect all
var selected = document.getElementsByClassName("selected");
for (var i = 0; i < selected.length; i++) {
selected[i].className = '';
};
el.className = 'selected';
clip.setValue(txt);
}
Here, you will have to explicitly pass the text to be copied. In mscConfirm's okCallback, this does not refer to any element.
So according to me, your function call should look like this:
<% if #exists == true %>
mscConfirm("Hold on", 'The file has been shared already, <%= #display %>', function(){
clipboard(document.getElementById("DOMnodeID"), #display);
});
<% end %>
Or you can remove the DOMnode altogether and just pass the text to be copied:
function clipboard(txt) {
// deselect all
var selected = document.getElementsByClassName("selected");
for (var i = 0; i < selected.length; i++) {
selected[i].className = '';
};
clip.setValue(txt);
}
Then your function call should look like this:
<% if #exists == true %>
mscConfirm("Hold on", 'The file has been shared already, <%= #display %>', function(){
clipboard(#display);
});
<% end %>

Interaction between ruby and js in rails - interesting moment

So, there is method in conroller:
def create
email=params[:email]
email=email.downcase
user = User.find_by_email(email)
if user && user.authenticate(params[:password])&& user.confirmed
if session[:was_going]
#url=session[:was_going]
session[:was_going]=nil
end
#status=true
cookies[:auth_token] = {:value => user.auth_token, :expires => Time.now + 30.days }
elsif user && !user.confirmed
#status=false
#unconfirmed=true
else
##unconfirmed=false commented line
#status=false
end
respond_to do |format|
format.js{[#status, #url]}
end
end
It responds to format.js. On any case of authentication process I have boolean variable, which I pass to JS - #status (authenticated or not), #unconfirmed - special message, and just invalid input (if both #status and #unconfirmed are false). Pay attention to commented line.
Here is js template:
if(<%=#status %>) {
window.location.replace("<%= #url %>")
}
else {
if (<%=#unconfirmed %>) {
$('.sign_in').replaceWith("<%= j render :file=> 'signs/index.html.erb' %>")
$('.signs_form').prepend("<div id='errors_of_sign'> Check your mailbox on <br /> confirmation letter </div> ")
$('.signs_form').css({"margin-top":"30px"})
$('.facebook_sign').css({"margin-top":"80px"})
$('.sign_in').fadeIn('fast')
}
else{
$('.sign_in').replaceWith("<%= j render :file=> 'signs/index.html.erb' %>")
$('.signs_form').prepend("<div id='errors_of_sign'> Email or password are incorrect </div> ")
$('.signs_form').css({"margin-top":"30px"})
$('.facebook_sign').css({"margin-top":"80px"})
$('.sign_in').fadeIn('fast')
}
}
And there was trouble - when there was no commented line, the code for else statement didn't work at all.
Then I added that line, and now everything works.
Can you please explain this behaviour of JS? I mean, if there is no variable #unconfirmed, than ruby should return nil, which equal to false in boolean functions of any language I know, including JS.
You are right about ruby that it will return nil , if not declared but JS doesn't know what nil is .
Js knows 'true' or 'false'
'nil' is not defined in JS.
Try it yourself on console

How do I call a jq function from vb.net code behind?

I need to call this from the code behind if there is a certain value read in from a
query string variable ie
x as string = request.querysting("Var")
if x = 'Hide" then
function guestHide()
{
$(".panel").hide("slow");
}
end if
in your aspx page do this
<%
if (Request.QueryString["var"].ToString() == "Hide") {
%>
function guestHide() { $(".panel").hide("slow"); }
<%
}
%>
The above is C#, it should be easily translatable to VB.

How can I return javascript from a Ruby on Rails helper method?

I have a Note model, which can contain have either an image link attachment (linktype = "image" or some text (linktype = "text). When I display the notes, the method of display changes depending on the linktype. An example is:
<% #notes.each do |q| %>
<h2 class="title"><%= q.name %></h2>
<% if q.linktype == "other"%>
<script type="text/javascript">some javascript</script>
<% elsif q.linktype == "text"%>
<%= q.text %>
<% elsif q.linktype == "image"%>
<img src="<%= q.link %>" />
<% end %>
<% end %>
I have to display the notes in a few different views in my site, so rather than have to repeat the viewing code multiple times, I want to have it in one place and refer to it from different views.
My initial thought was to put the display code in a helper, something like this:
<% #notes.each do |q| %>
note_display(q.linktype, q.link)
<% end %>
But some of the displaying involves javascript (line 4 in first code block). Can I still use a helper method, even though I would need it to return javascript? If so, how do I do it? Thanks for reading.
There's nothing special about javascript, you can return it from helpers as you would return other html content. The only thing I would suggest is to use helpers for tags like
image_tag(q.link)
javascript_tag("some javascript")
content_tag("h2", q.name, :class => "title")
As far as ERB is concerned, JavaScript is just string content like anything else rendered by a template. So your helper method can just construct and return a string:
def note_display(note)
content = ''
content << content_tag('h2', h(note.name), :class => 'title')
if note.linktype == 'other'
content << javascript_tag("some javascript")
elsif note.linktype == 'text'
content << h(note.text)
elsif note.linktype == 'image'
content << image_tag(note.link)
end
content
end
You can use this helper method using:
<% #notes.each do |n| %>
<%= note_display(n) %>
<% end %>

Categories