Convert MVC ViewBag property to lowercase [duplicate] - javascript

This question already has answers here:
Using Razor, how do I render a Boolean to a JavaScript variable?
(7 answers)
Closed 7 years ago.
I'm trying to use a Boolean MVC ViewBag property that is being set in a controller inside of a javascript if statement. However, there is a problem being introduced because the property value gets converted to Pascal case. For example, "true" becomes "True" and "false" becomes "False".
<script type="text/javascript">
var error = #ViewBag.Dropped;
if ( error ) {
$( '#alert-message' ).addClass('alert-success alert-dismissable');
}
</script>
How can I ensure that the property gets converted to lowercase. I've tried to use javascript function .toLowerCase() and was unsuccessful.

One way would be:
<script type="text/javascript">
var error = #(ViewBag.Dropped ? "true" : "false");
if ( error ) {
$( '#alert-message' ).addClass('alert-success alert-dismissable');
}
</script>

var error = #ViewBag.Dropped.ToString().ToLower();

I don't think the above answer will work since all strings are true in Javascript,.. you might want
<script type="text/javascript">
var error = #(ViewBag.Dropped ? true : false);
if ( error ) {
$( '#alert-message' ).addClass('alert-success alert-dismissable');
}
</script>
note if you quote true and false they become strings and true is NOT the same as "true".

I use this method all the time because the longer version (value.ToString().ToLowerInvariant()) is too tedious to type all the time:
Add a class to your project or library:
public static class ExtensionMethods
{
public static string ToJS(this bool value)
{
return value.ToString().ToLowerInvariant();
}
}
then in your js:
<script type="text/javascript">
var error = #ViewBag.Dropped.ToJS();
if ( error ) {
$( '#alert-message' ).addClass('alert-success alert-dismissable');
}
</script>

Related

IF condition using string

I am programming in Polymer 1.0 and am trying to create an IF function to change the value of a property. My function is the following:
_searchButton: function(selectednamedropdown, selectedtypedropdown){
if (selectednamedropdown=="no_name_selected" && selectedtypedropdown=="no_type_selected"){
this.searchUsagesBtn = true
} else{
this.searchUsagesBtn = false
}
}
In my mind when selectednamedropdown is equal to "no_name_selected" and selectedtypedropdown is equal to "no_type_selected" the function should set searchUsagesBtn to true and when they are not these values, false.
However, the function does not ever seem to be returning true even when these conditions are met. Any ideas why this might be? Thanks for all help
When I run your function like this:
let searchUsagesBtn;
function search(selectednamedropdown, selectedtypedropdown) {
if (
selectednamedropdown === "no_name_selected" &&
selectedtypedropdown === "no_type_selected"
) {
searchUsagesBtn = true;
} else {
searchUsagesBtn = false;
}
}
search("no_name_selected", "no_type_selected");
console.log("button: ", searchUsagesBtn);
I get button: true in console log. So maybe your inputs in this function are not a strings.
The issue was around how JavaScript treats properties within functions. The function was storing the new value and old value of the first property and not any values of the second property. The solution involved making 2 functions to test the strings in each property. Thanks for all assistance

How can I pass object as a parameter using a string of its name in JavaScript?

I have an object
bigRow = {size:'long', color:'pink'};
Let's say I have another object table, which has row property, e.g.
table = {
row: 'bigRow',
column: 'smallColumn'
};
Can I pass the object 'bigRow' as a parameter to a function using table's property value as a reference?
Can I write something like
function ( table.row )
that would work like
function ( bigRow )
Even though both turn out to be function( bigRow ), the former comes out as a string without any connection to the object
I don't think it's possible that way. However, you could put bigRow inside another object like so:
var rowTypes = {
bigRow : {size:'long', color:'pink'},
//other rows if necessary...
}
And then access that member of the rowTypes object using the string as an identifier:
function ( rowTypes[table.row] )
Yes, you can but you should set your object as property of current document using "this" keyword.
<!DOCTYPE html>
<html>
<body>
<div id="demo"></div>
</body>
</html>
<script>
this.bigRow = {size:'long', color:'pink'};
this.table = {
row: 'bigRow',
column: 'smallColumn'
};
function myFunction(myRow){
document.getElementById('demo').innerHTML = myRow.size;
console.log(myRow);
}
myFunction(this[table.row]);
</script>
https://jsfiddle.net/0p5afpj9/
I came across an answer to a similar question. Apparently, this will work if both objects are global:
function ( this[ table.row ] )

Run function passed from data attribute [duplicate]

This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 7 years ago.
I want to be able to run a function that is passed by name from a data attribute on the HTML side. I've tried the following below.
HTML:
<div class="generic-select" data-help-on-shown="genericFunction" >
</div>
Javascript:
function genericFunction() {
console.log("generic function called");
}
Other Javascript (separate file):
//stepEl is correct divider from above
var genFunction = typeof (stepEl.data("helpOnShown")) === "undefined"
? null
: stepEl.data("helpOnShown");
//this prints "genericFunction" as expected
console.log("genFunction = " + genFunction);
if (genFunction) {
genFunction(); //gives error!
}
However, this gives me an error. Is there a way to call a function by a string name?
If the function is "global", it exists as a property of window:
window[functionname]()

jquery string interpolation causing problems

I'm using the jquery tokeninput plugin, and I want the json token input data to be dependent upon a value that can be found somewhere in the form.
My code looks like this:
jQuery(function() {
var bparam;
if ($('#tokens')) {
bparam = $('#select_menu').val();
return $('#tokens').tokenInput(("/tokens.json?b=" + bparam)({
theme: 'facebook',
}));
}
});
So the plugin should make a request such as /tokens.json?b=124 if that value from the select_menu div was 124.
Somehow this just doesn't work and I don't know why. I'm still kindof a javascript newbie.
Any help appreciated!
if ($('#tokens')) will return an empty array ([]), so no matter what that will always evaluate to true. I'm guessing you want if ($('#tokens').length). If there is an item in the array it will evaluate to true, if it's empty it evaluates to false.
What's tripping you up is when the variable is being set. bparam is being set on page load. I would bind it to be set when whatever is triggering the event occurs.
Apart from the length > 0 call I had to make (thanks for pointing that out Stuart Nelson and Shusl!), it turned out that the string interpolation in coffeescript somehow wasn't working as I wanted. The same code translated into javascript did actually work.
Coffeescript was being translated into:
jQuery(function() {
var bparam;
if ($('#tokens').length > 0) {
bparam = $('#select_menu').val();
return $('#tokens').tokenInput(("/tokens.json?b=" + bparam)({
theme: 'facebook',
}));
}
});
Now, the working code is, directly written in javascript/jquery ,is:
jQuery(function() {
if ($("#tokens").length > 0) {
var bparam
bparam = $('#select_menu').val();
return $('#tokens').tokenInput("/tokens.json?b=" + bparam, {
theme: 'facebook',
});
}
});
Note these extra parenthesis in
(("/tokens.json?b=" + bparam)
whereas
("/tokens.json?b=" + bparam
is the working solution.

Why my JQuery doesn't load on IE?

I did this javascript quiz : http://utbm.trunat.fr/CIP/quiz/
It works on normal browser but doesn't even load with Internet Explorer.
It seams that it doesn't recognize the initQuiz() function.
Do you have any idea of how I can fix this ?
Internet Explorer doesn't accept the trailing comma:
question = {'texte': $(this).attr("texte"),
'sound': $(this).attr("sound"),}
Apparently, another error comes from this line:
$('title').html(QUIZ_TITLE[lang]);
Turns out you can't set the title like that in IE. Use document.title = QUIZ_TITLE[lang] instead.
A third error is that you're introducing a new variable, question without the var keyword, which is an error in IE. You're doing it again, later on, in response. Update your loadXML as such:
function loadXML(xml) {
$(xml).find("question").each(function() {
var question = {'texte': $(this).attr("texte"), 'sound': $(this).attr("sound")};
reponses = [];
$(this).find('carre').find('reponse').each(function() {
var reponse = {'texte': $(this).text(), 'sound': $(this).attr("sound"), 'bonne': false};
if($(this).attr('bonne') == "vrai") reponse['bonne'] = true;
reponses.push(reponse);
});
question['reponses'] = reponses;
questions.push(question);
});
startGame(questions);
}
A fourth error is in the way you're verifying that an answer is correct.
if($(this).attr('data-type') == 'true')
You compare the value of the data-type attribute to the string value "true", but when you assign the value, you set it to the boolean value true:
$('#r'+(i+1)+'input').attr('data-type', r.bonne);
To make sure that you're always comparing string values, for instance, you could set the value as such:
$('#r'+(i+1)+'input').attr('data-type', r.bonne.toString());

Categories

Resources