Send #Model variable as parameter to a JavaScript function - javascript

start reading at 'UPDATE'
I have a JavaScript function :
<script type="text/javascript">
function getAmount(AdminFee, TimeAndMatRate, TimeSpent, MinimumCharge) {
var amount = math.Round(AdminFee + TimeAndMatRate * TimeSpent);
if (amount < MinimumCharge) {
amount = math.Round(MinimumCharge);
}
document.getElementById('amount').innerHTML = amount;
}
</script>
And I have the following field that has to be changed when I change another value:
<span id="amount"></span>
When I change a value in this textbox the above field should be updated:
#Html.TextBoxFor(model => model.TimeAndMaterialsRate, new { onkeyup = "getAmount()" })
This code works fine as long as I do not try to send any parameters in getAmount(), but I can't seem to figure out how to get it to work, could anyone please help me?
This is one of the things that I tried
new { onkeyup = "getAmount("
+ #Model.AdminFee + ","
+ #Model.TimeAndMaterialsRate + ","
+ #Model.TotalTimeSpent.Hours + ","
+ #Model.MinimumCharge + ")"
}
I also tried to above without '#'s
UPDATE:
The above code works now although it seems the function doesn't work properly.
<script type="text/javascript">
function getAmount(AdminFee, TimeAndMatRate, TimeSpent, MinimumCharge) {
var amount = math.Round(AdminFee + TimeAndMatRate * TimeSpent);
if (amount < MinimumCharge) {
amount = math.Round(MinimumCharge);
}
document.getElementById('amount').innerHTML = amount;
}
</script>
The values passed into the function are id, id, double, id. Any clue on why this doesn't work?

I think your problem is a slight syntax error with the end of your string. The last plus sign is in the wrong place. It should be like this:
new { onkeyup = "getAmount("+#Model.AdminFee+","+#Model.TimeAndMaterialsRate+","+#Model.TotalTimeSpent+","+#Model.MinimumCharge+")" })

I'd say to use eval, but it's preety bad practice because it can be really injected & stuff.
Look at this article http://www.sitepoint.com/call-javascript-function-string-without-using-eval/
What you need is :
// function name and parameters to pass
var fnstring = "runMe";
var fnparams = [1, 2, 3];
// find object
var fn = window[fnstring];
// is object a function?
if (typeof fn === "function") fn.apply(null, fnparams);
Your params will look like :
var fnparams = {
minimumCharge : '#Model.MinimumCharge',
... // and so on
};
And you will get them in this way :
parseInt(fnparams.minimumCharge);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

Related

Node js merge values basic implemenation

I am trying to do something like the below but merge function has a problem with the line
content = content.replace( content, "Hi" + values.first_name + "! Thanks for completing this code challenge :)" );
Filename : app.js
var utilities = require("./utilities");
var mailValues = {};
mailValues.first_name = "Janet";
var emailTemplate = "Hi %first_name%! Thanks for completing this code challenge :)";
var mergedContent = utilities.merge(emailTemplate, mailValues);
//mergedContent === "Hi Janet! Thanks for completing this code challenge :)";
Filename : utilities.js
function merge(content, values) {
content = content.replace( content, "Hi" + values.first_name + "! Thanks for completing this code challenge :)" );
return content;
}
module.exports.merge = merge;
Your merge function is not good, it does a weird thing and will surely returns a weird string if you pass another template. You're replacing the entire input string by the "Hi...." string but with first_name inserted so in the end, your function is too specific and can't handle extra parameters or another template/string.
function merge(content, values) {
// loop over all the keys in the values object
Object.keys(values).forEach(function(key) {
// look for the key surrounded by % in the string
// and replace it by the value from values
content = content.replace('%' + key + '%', values[key]);
});
return content;
}
var mailValues = {};
mailValues.first_name = "Janet";
mailValues.last_name = "Doe";
var emailTemplate = "Hi %first_name% %last_name%! Thanks for completing this code challenge :)";
var mergedContent = merge(emailTemplate, mailValues);
document.write(mergedContent);
Try the "run code snippet" button.
for ... in version, for information, better to use the previous version.
function merge(content, values) {
// loop over all the keys in the values object
for (var key in values) {
// look for the key surrounded by % in the string
// and replace it by the value from values
content = content.replace('%' + key + '%', values[key]);
}
return content;
}
var mailValues = {};
mailValues.first_name = "Janet";
mailValues.last_name = "Doe";
var emailTemplate = "Hi %first_name% %last_name%! Thanks for completing this code challenge :)";
var mergedContent = merge(emailTemplate, mailValues);
document.write(mergedContent);

Javascript Eval to work for both function and plain string

I want to display a list of items, now sometimes these items' title will just be a plain string, and sometimes it might be a value returned by a function.
How can I make both events work using eval() ?
Here is an example code:
var a1 = "formatDate('" + startTime + "') + ' - ' + formatDate('" + endTime + "')"
var a2 = "#america"
var result1 = eval(a1) // works well!
var result2 = eval(a2) // doesn't work, need to use eval('a2') but then first one doesn't work
Only thing I can think of is when creating the string for example "#america" have it saved like "'#america'" instead, but I would rather avoid it
[edit]
Eventually I will have something like this:
arr.push("formatDate('" + startTime + "') + ' - ' + formatDate('" + endTime + "')");
arr.push("#america");
for(var i = 0; i < arr.length; i++) {
var ev = eval(arr[i]);
console.log(ev);
}
What I would suggest is wrapping the eval in a try catch block, if the eval succeeds then return the value otherwise return the value originally passed to function. There are many cases where eval can fail as it is simply trying to parse the string as valid JavaScript so any invalid JS not just a simple string can cause it to fail so its better to be safe and catch any error that comes out of it.
var evaluate = function(value) {
try {
return eval(value);
}
catch(err)
{
return value;
}
}
var ev = eval(a2) would be equivalent to var ev = eval('#america') which doesn't make any real sense.
When you say eval('a2') works, I assume that ev = '#america' is the desired outcome. The 'a2' expression is evaluated as simply accessing the value of the variable of that name.
You're basically just having a series of strings that may be valid javascript code, or may not, and there's no way to tell which is which. In that case, the best you can do is something like
try {
ev = eval(arr[i]);
} catch(ex) {
ev = arr[i];
}
... which obviously looks terrible. Can you control the content of the entries in arr?
arr.push(function() {
return formatDate(startTime) - formatDate(endTime);
});
arr.push("#america");
In that case, you could check for the type of each entry, and act on it accordingly:
for(var i = 0; i < arr.length; i++) {
var ev = typeof arr[i] == 'function' ? arr[i]() : arr[i];
console.log(ev);
}
this is that i should do:
var a1 = function(){
return formatDate(startTime) + formatDate(endTime)
}
var a2 = "#america"
var result1 = a1();
var result2 = a2;
Yo can check with typeof(a1) if the var is a function or an object or anyting else.
if(typeof(a1)=='function'){
result = a1();
}else{
result=a1;
}

Select Part of a Attribute - JQuery

I need to get the number only from an attribute (The number is dynamic). The button/anchor looks like this:
Delete Dish
The part I need to dissect is this bit 'bc_inventorybundle_menu_product_0' I only want the number, for use in another function (Delete a LI with an ID of menuitem0_dish)
The code I use for selecting ID's elsewhere is:
function getNum(element, attrPrefix) {
//set prefix, get number
var prefix = attrPrefix;
var num = element.attr("id").substring((prefix.length));
return num;
}
It works great on ID's but I cant seem to get it to work for Attributes instead of ID's
So User clicks delete button bc_inventorybundle_menu_product_0 then jQuery removes the < li id="menuitem0_dish">
I can't add an ID to the button so I have to use the attribute of the button. As I'm sure you can tell I'm a complete noob when it comes to JS/JQuery.
EDIT
Having read all the answers I feel I may need to elaborate a little.
I think the biggest issue is registering when the Button/Anchor is clicked.
What I currently have is this, which I know must be wrong:
$(document).on('click', 'data("field")', function(event) {
deleteDish(this);
});
function getbutNum(element, attrPrefix) {
//set prefix, get number
var prefix = attrPrefix;
var butnum = element.data("field").substring(prefix.length); //Changed as per suggestions
return butnum;
}
function deleteDish(field) {
var numbut = getbutNum();
//Delete the UL/LI
console.log("Num But" + numbut);
}
Asides from all else this gives me an error of 'unrecognized expression: data("field")'
Have you tried selecting your actual data attribute:
var num = element.attr("data-field").substring(prefix.length);
Or:
var num = element.data("field").substring(prefix.length);
EDIT
First add a class to your anchor element (I'm going under the assumption that you have more than one of these):
Delete Dish
Then:
$(".delete-dish").on("click", function (e) {
e.preventDefault();
var fieldData = $(this).data("field"),
num = fieldData.substring(fieldData.lastIndexOf("_") + 1);
console.log("Num But" + num);
});
Here is a fiddle to demonstrate
Using the attribute name that contains your input should work:
function getNum(element, attrPrefix) {
//set prefix, get number
var prefix = attrPrefix;
var num = element.attr("data-field").substring((prefix.length));
return num;
}
http://jsfiddle.net/zf3hmo4q/
Considering you want to parse attributes with "data-*" name:
function getNum(element, dataName, dataPrefix) {
var num = element.data(dataName).replace(dataPrefix, "");
return num;
}
console.log(getNum($(".btn"), "field", "bc_inventorybundle_menu_product_"));
Maybe something like this?
var getNumberFromAttribute = function(id, field) {
var field = $(id).data(field);
var parts = field.split("_");
return parts[parts.length - 1]
}
Here's a jsfiddle http://jsfiddle.net/o6go79cL/
UPDATE
You could just pass in the element. The only purpose of the id was to select the object. So you could also just do:
var getNumberFromAttribute = function(elm, field) {
var field = $(elm).data(field);
var parts = field.split("_");
return parts[parts.length - 1]
}
number = getNumberFromAttribute(anchorTag, "field");

Can't capitalize first letter, element not updated

I am getting my string from a textBox like this (in a loop where index is incremented):
var name = document.getElementById("TextBox" + index).value;
And I have a function in my script that looks like this meant to uppercase first letter:
function capital(string)
{
return string.charAt(0).toUpperCase() + string.slice(1);
}
And try to use it like this:
var name = document.getElementById("TextBox" + index).value;
capital(name);
They are in different functions in the same script tag. Where am I going wrong?
Make sure you assign the modified value back to the control:
var element = document.getElementById("TextBox" + index);
var name = element.value;
element.value = capital(name);
Are you trying to getElementById using the input type, or do you have actual IDs on your textbox called 'TextBox'? The below works fine, see fiddle
var index = 1;
var name = document.getElementById("test" + index).value;
function capital(str)
{
return str.charAt(0).toUpperCase() + str.slice(1);
}
alert(capital(name));
String are immutable in js, you need to reassign.
var name = capital(document.getElementById("TextBox" + index).value);
Plus strings are passed by value, so they are copied over to the new function. So whatever you do in the function won't cause any effects in your name variable.

Javascript getting Cookie won't do on certain value

I have this function in my PHP :
setcookie("UserPusser", $user, time() + 604800, "/pusser/beta/");
setcookie("PassPusser", $pass, time() + 604800, "/pusser/beta/");
setcookie("NotifPusser", $notif, time() + 604800, "/pusser/beta/");
And I have this function in my javascript
function getThisCookie(name){
var value;
var singleCookie = document.cookie.split(";")
for(var x in singleCookie){
var y = singleCookie[x].split("=");
if(y[0] == name) {
value = y[1];
}
}
return value;
}
When I type alert(getThisCookie('UserPusser')) the result is what I want. But when I tried to write alert(getThisCookie('NotifPusser')); or alert(getThisCookie('PassPusser')); the result is : undefined.
Anyone can help me?
What I'm trying to do is make the browser remember the value of checkbox each time the page reload.
Just for completeness a full answer here instead of only the hint within the comments:
Cookie values are separated by ; (semicolon + whitespace)
This leaves you with something like this:
cookie = 'a=123; b=456; c=678'
In order to separate them you have to split them by the same delimiter.
With modern browsers (JS 1.6+ I guess, not quite sure right now) or libraries like underscore.js you could as well put them into an object.
// if your browser supports 'reduce'
var cookieObject = document.cookie.split('; ').reduce(function(o, kvp) {
var split_kvp = kvp.split('=');
o[split_kvp[0]] = split_kvp[1];
return o;
}, {});
// underscore.js version
var cookieObject = _.reduce(document.cookie.split('; '), function(o, kvp) {
var split_kvp = kvp.split('=');
o[split_kvp[0]] = split_kvp[1];
return o;
}, {});
Anyway after performing any of those you can easily access the values you are looking for:
cookieObject.a == 123
cookieObject.b == 456
Just remember that those are readOnly. In order to modify them you'd have to write the object back to the document.cookie
// again, modern browser version
document.cookie = Object.keys(cookieObject).map(function(key) {
return key + '=' + cookieObject[key];
}).join('; ');
// with underscore.js
document.cookie = _.chain(cookieObject).keys().map(function(key) {
return key + '=' + cookieObject[key];
}).value().join('; ')

Categories

Resources