I am having some trouble when printing javascript code that is created on the server side. The code must be placed in my html, but asp always escapes the string in such a way that my javscript doesn't execute. Here is my code:
//file "generateCode.ascx"
<%
if (Model.Overrides != null) {
if (Model.Overrides.JavascriptAposTabela != null) {
%>
<%: Model.Overrides.JavascriptAposTabela; %>
<%
}
}
%>
Am example of the result of the code above is:
function getGreenToRed(percent){
r = percent<50 ? 255 : Math.floor(255-(percent*2-100)*255/100);
g = percent>50 ? 255 : Math.floor((percent*2)*255/100);
return "rgb("+r+","+g+",0)";
}
$(".colormeter").css("background-color", getGreenToRed($(this).text()));
This is not the expected result.
I tried the solution proposed in these threads, but it did not work for me:
How do I prevent MVC3 html escaping my validation messages?
Stop the tag builder escaping single quotes ASP.NET MVC 2
I am using asp.net mvc 2
Well. Unfortunately, it was only ignorance of my part.
The solution is pretty simple:
//file "generateCode.ascx"
<%
if (Model.Overrides != null) {
if (Model.Overrides.JavascriptAposTabela != null) {
%>
<%= Model.Overrides.JavascriptAposTabela; %>
<%
}
}
%>
Related
In my registration form I have some validation logic which works perfectly fine in Chrome but in Safari error message don't disappear below form after filling empty fields. It looks like show() and hide() doesn't work and I don't now why because based on this https://www.quirksmode.org/dom/events/index.html it should worked.
if (registrationsForm.length > 0) {
var emailField = $('#users-registrations-email');
var emailConfirmationField = $('#users-registrations-email-confirmation');
var emailInvalidMsg = $('.bank-employees-users-registration__registrations__not-identical-email');
var obligatoryInvalidMsg = $('.bank-employees-users-registration__registrations__email--invalid');
submit.on('click', function(e) {
e.preventDefault();
if (emailField.val() !== emailConfirmationField.val() && emailField.length > 0) {
emailInvalidMsg.show();
emailField.addClass("invalid");
emailConfirmationField.addClass("invalid");
emailConfirmationField[0].setCustomValidity('Incorrect confirmation email');
if (emailField.val() !== '') obligatoryInvalidMsg.hide();
} else {
emailConfirmationField[0].setCustomValidity('');
}
validateEmail();
var invalidInput = $('input:invalid');
if (invalidInput.length === 0 && !fileInput.hasClass('invalid')) {
form.submit();
} else {
invalidInput.addClass('invalid');
validateInput();
}
});
}
Function which is responsible for input validation:
function validateInput() {
$('input').change(function() {
if ($(this).is(':valid')) {
$(this).removeClass('invalid');
}
});
}
Edit
This is a code snippet from view
new.html.erb
<div class="floating-label bank-employees-users-registration__registrations-input--wrapper">
<%= f.email_field :email, class: "bank-employees-users-registration__registrations-input floating-field", id: "users-registrations-email", placeholder: t('.email'), required: true, aria_required: true %>
<%= f.label :email, t('.email'), class: "floating-label-placeholder" %>
<span class="bank-employees-users-registration__registrations__not-identical-email">
<%= t('.email_not_identical') %>
</span>
<span
class="bank-employees-users-registration__registrations-input--invalid-msg bank-employees-users-registration__registrations__email--invalid"
id="bank-employees-users-registration__registrations__email--invalid">
<%= t'.obligatory' %></span>
<% if #registration_form.errors.full_messages_for(:email).first %>
<div class="alert alert-danger">
<div class="error-explanation">
<%= t('activerecord.errors.models.user.attributes.email.taken') %>
</div>
</div>
<% end %>
</div>
Edit2
Maybe this will be helpful - as you see there are some email validations where two email address has to be equal. When I provide different email address it shows me error message that they are not equal but if I correct them, the error will be changed to - this field is required. I was trying to implement this solution jquery .show() and .hide() not working in safari - adding spinner to <a href but without any positive results.
Why not get rid of all that and use HTML5 fields? They have client-side validations that work across browsers and you can validate input on the server side using model validations, let Rails deal with all that.
I know it may be a bit of upfront investment into refactoring all that but otherwise things will only get worse in the long term if you keep doing what you're doing.
Also look at the Bootstrap form gem in case you're using Bootstrap.
Guys i'm trying to render MongoDB record in my .ejs file, however, i console.log the variable prior the end of my route and i get the expected value, however, if becomes undefined in the .ejs file
below is the code:
router.get("/new",function(req,res){
var selectedMake;
console.log("Welcome to new make route!");
Make.find({},function(err,result){
if(err){
console.log("an error occured while fetching the data");
}else{
if(req.query.id){
Make.findById(req.query.id,function(err,foundMake){
console.log("found the query string");
selectedMake = foundMake;
console.log(selectedMake); // renders expected value when passing valid ID in the query string
})
}
res.render("vehicles/newvehiclemake",{selectedMake: selectedMake, makes:result,modelId: req.query.id});
}
})
});
and here is the .ejs excerpt where the variable selectedMake is being used:
<% if (!typeof selectedMake == undefined) { %>
<% selectedMake.models.forEach(function(model){ %>
<tr><td><%= model.name %></td></tr>
<% }) %>
<% }else { %>
<tr><td>No Models available for the selected Make</td></tr>
<% } %>
appreciate your input and thanks in advance.
typeof on any variable returns a string so you have to check for 'undefined' in your ejs
<% if (typeof selectedMake !== 'undefined') { %>
I'm not sure but you make mistake at first line in your .ejs file.
Try this:
<% if (typeof selectedMake !== 'undefined') { %>
I'm using Backbone with Underscore templates. I have a JavaScript if() condition in my code that looks something like this:
<div class='faces'>
<% if(somevalue === true) { %>
your face
<% } else { %>
my face
<% } %>
</div>
However I find this syntax awkward and I really would like to use something like the following, even though it doesn't actually work (replaces entire document with the text):
<div class='faces'>
<% if(somevalue === true) {
document.write("your face");
} else {
document.write("my face");
}
</div>
I want the string to be output in the template exactly where it is called. For outputting a simple variable EJS (and underscore) have a great syntax of
<%= somevalue %>
Where the = is the critical part that document.write()s it out into the template. Is what I'm trying to accomplish possible? Can JavaScript output inline?
There are a few options, you could use <%= %> and a ternary:
<%= somevalue == true ? 'your face' : 'my face' %>
or you could use print:
You can also use print from within JavaScript code. This is sometimes more convenient than using <%= ... %>.
var compiled = _.template("<% print('Hello ' + epithet); %>");
compiled({epithet: "stooge"});
=> "Hello stooge."
so you could do this:
<% if(somevalue == true) {
print("your face");
} else {
print("my face");
} %>
I'm assuming that if(somevalue = true) is a typo and should be if(somevalue == true).
I am trying to call a javascript function from my form page in a Rails 3 project. I need to send the function the ID of a particular element. Unfortunately I can't get the ID easily since it is automatically generated by a plugin.
I tried doing it this way:
<%= t.select :number_type, #id_types, {}, {:onchange => "has_other_field(' + the_value.id.to_s + "');"} %>
<% if (!the_value.nil?) && (!the_value.number_type.nil?) && !#id_types_sm.include? the_value.number_type) %>
<script type="text/javascript">
setup_other_field("<%= the_value.number_type %>", ###ID WOULD GO HERE###);
</script>
<% end %>
.. But since I don't know the ID of the element, I can't call it from the function.
So now I'm trying to do it this way, by calling the function from an "onload" when the input element loads:
<% if (!the_value.nil?) && (!the_value.number_type.nil?) && (!#id_types_sm.include? the_value.number_type) %>
<%# Call the function from the form helper only if the conditions are met %>
<%= t.select :number_type, #id_types, {}, {:onchange => "has_other_field(this.id);", :onload => "setup_other_field('" + the_value.number_type + "', this.id);"} %>
<% else %>
<%# Use the form helper without calling the function %>
<%= t.select :number_type, #id_types, {}, {:onchange => "has_other_field(this.id);"} %>
<% end %>
BUT I realize that onload does not work for this situation. Is there any workaround for this? How can I either
A) get the element ID from the field to the function in the first option, or
B) call this function from this input element whenever it loads?
... or C) an alternative way to do this?
Thanks in advance and let me know if more details would help.
If you have ID saved in the model, get it with <%= model.id %>
Exception to this rule is when you create object, and it is before it is written to database. If you go to edit or anywhere else it will be ok.
If you have it somewhere on the page :/ then you can use jQuery to get it for you.
< div id="id_of_the_element" attr_with_my_id="15" >ABC< /div >
$("#id_of_the_element").attr('attr_with_my_id')
< input id="id_of_the_element ... >< /input >
$("#id_of_the_element").value
Using Rails 3: In my update.js.erb file I found I was repeating a lot of stuff. So I tried to put it all into a helper. But I'm having trouble getting the helper to give back clean javascript. It puts in \" everywhere instead of "
Here's what I started with:
<% if #list.show_today %>
$("#show_today_check_<%= #list.id %>").removeClass("gray").addClass("orange").attr("value","0");
<% else %>
$("#show_today_check_<%= #list.id %>").removeClass("orange").addClass("gray").attr("value","1");
<% end %>
<% if #list.show_inventory %>
$("#show_inventory_check_<%= #list.id %>").removeClass("gray").addClass("white").attr("value","0");
<% else %>
$("#show_inventory_check_<%= #list.id %>").removeClass("white").addClass("gray").attr("value","1");
<% end %>
etc.
Here's the helper I wrote to generate the above javascript:
def toggelButtonState( object, name, color)
if object.send(name)
#add_col = color
#rem_col = 'gray'
#value = "0"
else
#add_col = 'gray'
#rem_col = color
#value = "1"
end
js = '$("#'
js += "#{name}_check_#{#list.id}"
js += '").removeClass("'
js += #rem_col
js += '").addClass("'
js += #add_col
js += '").attr("value","'
js += #value
js += '");'
end
I call it with:
<%= toggelButtonState( #list , 'show_today', 'orange' ) %>
And here's what I get in the response:
$(\"#show_today_check_2\").removeClass(\"orange\").addClass(\"gray\").attr(\"value\",\"1\");
Now I did notice a similar problem with straight html in helpers. It wouldn't let me return stuff in angle brackets. But then I found out about content_tag. Is there something similar for javascript? How can I get rid of the \"s?
Add
js.html_safe
as last line of toggelButtonState function