How to pass model data in javascript - javascript

I need to pass a model value item.ID to one of my javascript function how can I do that ?
I triedfunction("#item.ID") but its not working

It generally works this way, you just have to omit the "" otherwise it gets interpreted as string. So you can write something like that in your JS:
var myinteger = #item.ID;
which renders as
var myinteger = 123; //for example
Edit: This makes sense when you id is an integer, of course, for strings you need to encapsulate it in '' or "". And don't get annoyed by any syntax errors reported by intellisense, it seems to have a problem with that but it works out just nicely.

You can pass the model data into the java script file in these ways
(1). Just set the value in hidden field and access the value of hidden field in java script.
(2). And pass the value using function parameter.
(3).
var LoginResourceKeyCollection = {
UserName_Required: '<%= Model.UserName%>',
Password_Required: '<%= Model.Password%>'
}
</script>

Try this...mind single quotes on parameter value while calling js function
function MyJsFunction(modelvalue)
{
alert("your model value: " + modelvalue);
}
<input type="button" onclick="MyJsFunction('#item.ID')" />
OR
<input type="button" onclick="MyJsFunction('#(item.ID)')" />

The best solution is pass your textbox ID to javascrpit function and then in function retrieve the value form the ID,
#Html.TextBoxFor(model => model.DatemailedStart, new {id = "MailStartDate", placeholder = "MM/DD/YYYY", maxlength = "40", #class = "TextboxDates", #onblur = "isValidDate('MailStartDate');" })
function isValidDate(id) {
var dateString = $('#'+id+'').val();
}

Related

AngularJs pass model value + model name to function in controller

$scope.populateMap=[{name: "ABC", code: "123"}, {name: "XYZ", code: "345"}]
//Want to send model name + value of model Currently sending ngObject.MainObj.specificFormatObj
HTML
<select ng-model="ngObject.MainObj.specificFormatObj" ng-change="ngObject.MainObj.specificFormatObj">
<option></option>
<option ng-repeat="i in populateMap" value="{{i}}">{{i.name}}</option>
JS
// CONTROLLER CODE JSON parse object to get name and code GOT parsedObj
$scope.genericSetLookups=function (Obj) { // want to do something like get the ngmodel string + the value, currently only value comes in
Obj.code=parsedObj.code;
Obj.name=parsedObj.name
};
More Explanation: ngObject.MainObj.specificFormatObj
I want in my model to store value of lookups in a specific way, with name and code. On the UI I populate using ng-repeat , So when I select a particular value I can either take i.name as display and set value as i.code .
But if i do that my ngObject.MainObj.specificFormatObj.name will be null and the value will get set to ngObject.MainObj.specificFormatObj.code by using ng-model ,so that is the reason in value I am taking i, not i.code or i.value ,now in the map i have code and name pair.
I sent it to a function and parse it, and set the value to ngObject.MainObj.specificFormatObj.code=inputTofunc.code respectively for name. In this case in the ng-change i pass on the ngObject.MainObj.specificFormatObj.code ,rather i want to set i from the map to ngObject.MainObj.specificFormatObj send it to function also the model string which in this case would be "ngObject.MainObj.specificFormatObj" .
So for 10 lookups i can write a generic code ,where the model name and model value i can send as parameter to function and set it there, the above way am doing is probably hardcoding values which i want to set to model in a specific format.
Since you need to pass the model name as a parameter, pass it as a string like this from html :
ng-change="genericSetLookups('ngObject.SomeObject.abc',ngObject.SomeObject.abc)"
And in the controller as the model name contains "." we cannot use the name directly as the key. We need to parse the model name. I have cooked something up after searching a bit. Hope it works.
Controller code:
$scope.genericSetLookups(modelName, value){
Object.setValueByString($scope, modelName, value);
}
Object.setValueByString = function(o, s, val) {
s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
s = s.replace(/^\./, ''); // strip a leading dot
var a = s.split('.');
for (var i = 0, n = a.length; i < n; ++i) {
var k = a[i];
if (k in o) {
if(i != n-1){
o = o[k];
}
else{
o[k] = val;
}
} else {
return;
}
}
return o;
}
Credit must also go to #Alnitak for the answer here
I didn't really understand your problem and the comments didn't make it clearer for me. What I tried to do is give you an example of how I would handle a select box and the model.
I would loop over the options with ng-options and show the selected option by putting {{selected.name}} in the template. Ofcourse if you would want to format the selected value in anyway or react to a change you can use ng-change.
Hope it helps.
Here is my JSFiddle
I'm not sure if I understood your question. If you want to save in your model the value code + name, maybe this code can help you:
<select ng-model="ngObject.MainObj.specificFormatObj" ng-options="(ppm.code + '-' + ppm.name) as ppm.name for ppm in populateMap">
</select>
jsfiddle

How to replace ' / ' with '-' inside ObservableArray ? Knockout js

Well i am trying to pass an observable array via ajax call to my controller but i get every value there except date . i get something like '01-01-01' etc .
I found the issue but unable to fix that as i dont know how to replace / with - .
My ObservableArray have around 10 list items each list item holds a many properties out of those startDate holds the date like ("23/10/2014") . i just need something like ("23-10-2014") .
Tought of posting my function's and more i hope thats not required in this case i believe .
Let me explain with bit of code and sample data :
function myarray()
{
var self=this;
self.startDate=ko.observable("");
self.name=ko.observable("");
self.place=ko.observable("");
}
MyObservableArray :
self.Main= ko.observableArray();
In between i do some stuff to load Data into self.Main and i am sending self.Main to controller having data like below :
self.Main[0] holds :
startDate() -->gives you "23/10/2014" //individual observables inside onservable array
name() --> "jhon"
place()--> "croatia"
Likely
self.Main[9] holds :
startDate() --> "29/05/2012"
name() --> "pop"
place()--> "usa"
I am trying like i want to alter the self.Main() and replace the startDate and use the same self.Main to send to my controller . Once after replacing in self.Main when i check date the / should be replaced with - .
Possible solution : i can use a different observable array and push all the VM's of Main into it but i am trying to do on self.Main without using other .
If someone can show some light it is much appreciated .
What I got that you are facing problem in escaping / in replace.
Try this
"(23/10/2014)".replace(/\//g,"-") //returns "(23-10-2014)"
I tried something for you using simple JS
var arr = [{date:"(23/10/2014)"},{date:"(23/10/2014)"},{date:"(23/10/2014)"},{date:"(23/10/2014)"}];
arr.forEach(function(obj){obj.date = obj.date.replace(/\//g,"-")});
console.log(arr) //will print date field as "(23-10-2014)" for all objects.
One solution would be to add a computed value that returns the array with the right values.
self.Main = ko.observableArray([...values here...]);
self.MainComputed = ko.computed(function() {
var computedArray = [];
self.Main().forEach(function(item) {
var newItem = myarray(); //Create a new item.
newItem.name(item.name());
newItem.place(item.place());
newItem.startDate(item.startDate().replace(/\//g,"-"));
computedArray.push(newItem);
});
return computedArray;
});
Then use the computed value in the places where you need the values with -.
I can think of two other ways to solve your issue, when taken into account that you want to use self.Main:
Replace the / with - before setting startDate on your item.
Change startDate to a computed value while storing the original value in another variable.
The first solution should be pretty straight forward (provided that it is a valid solution).
The second solution would look something like this:
function myarray()
{
var self=this;
self.originalStartDate = ko.observable("");
self.name = ko.observable("");
self.place = ko.observable("");
self.startDate = ko.computed(function() {
if(self.originalStartDate()) {
//We can only replace if the value is set.
return self.originalStartDate().replace(/\//g,"-");
}
else {
//If replace was not possible, we return the value as is.
return self.originalStartDate();
}
});
}
Now when you set the values you do something like:
var item = myarray();
item.originalStartDate = "01/01/2014";
Then when you get the value of startDate you would get "01-01-2014".
I haven't used Knockout.js but you can do this with a Javascript replace:
var str = [your array value] ;
var res = str.replace("/", "-");
For more information:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

jQuery - Show variable, not text string

I have a variable being set as the .html(); of a <div />
The variable is the name of another variable. I want it to display the contents of the other variable, however it simply displays the name of the other variable.
How can I force it to show the variable contents rather than just a literal text string?
var clothing = 'dogeshop cryptoshop doge_clothing fyrstikken the_molly_machine peace_and_love moolah_market shibe_swag undieguys urban_graff kravshop got_doge mean_elephant the_dogedoor_store';
setInterval( function() {
var term = $("input").val();
$("#results").html(term);
}, 100);
When the user types 'clothing' into $("input"); the contents of the 'clothing' variable should be displayed in the $("#results"); <div />. Instead it just says 'clothing'.
Another way is to use object properties, like this
var obj = {};
obj.clothing = 'dogeshop cryptoshop doge_clothing fyrstikken the_molly_machine peace_and_love moolah_market shibe_swag undieguys urban_graff kravshop got_doge mean_elephant the_dogedoor_store';
setInterval( function() {
var term = $("input").val();
$("#results").html(obj[term]);
}, 100);
Here's the fiddle: http://jsfiddle.net/ZL7EQ/
The only way I know how to solve this is using eval:
$("#results").html(eval(term))
But you really shouldn't want to do that. :)
Use a dictionary.
// store strings in an object so you can look them up by key
var dict = {
clothing: 'dogeshop ...',
anotherKey: '...'
};
// update the result when the input changes
$('input').on('change', function() {
var result = dict[this.value]; // make sure the key exists
if (result) {
$('#results').val(result); // update the results
}
});
I use to make this mistake myself when working with jQuery.
Try instead:
$("#results").text(term);
Not sure what you have the interval for. You could just change the #results with a change event.

Use variable with ViewData Instead of literal string

Is it possible to use a variable in place of the string literal for ViewData? What I have is this ...
var listsource = <% = ViewData["dtYears"] %>;
And what I'd like to do is something like this ...
var datasource = "dtYears";
var listsource = <% = ViewData[datasource] %>;
The reason I'd like do this so so I can have a generic function in my javascript that loads the list I specify with the datasource I specify (both via a parameter). Then I can have a generic LoadList function like so ...
function LoadList(datasource, target) {
// generic list population code goes here
}
You can try this approach:
//On your server code(controller) where you set the ViewData
// Convert the datasource List/object to a json string and add the string to ViewData
ViewData["dtYears"] = JsonConvert.SerializeObject(lstYears);
//On your Client html code (view)
//convert it to equavalent json object/objects, using one of the following two methods
var datasource = eval("(" + '<%=ViewData["dtYears"].ToString() %>' + ")");
//OR use jquery method
var datasource =jQuery.parseJSON('<%=ViewData["dtYears"].ToString() %>');
//you should be good to go
alert(datasource.length+ " objects in "+ datasource );
Yes, as far as I know that should work. Have you tried it and not gotten results you'd like?

Getting value of multiple input fields with same class and adding into javascript object

I am faced with a issue as follows:
<input title="1" type="text" class="email">
<input title="2" type="text" class="email">
<input title="3" type="text" class="email">
Above is my html where I am trying to grab the emails of each input box and store it in an object with the title as key.
Here is what my JavaScript currently looks like
var emailObj = {};
$("input[class=email]").each(function() {
var id = $(this).attr("title");
var email = $(this).val()
emailObj[id] = email;
});
Currently console.log displays only the last value added to the object as shown below.
Object { 3="a#a.com"}
Where my expected result should be as show below
Object { 1="a#a.com", 2="b#b.com", 3="c#c.com"}
Could someone shed some light on this issue for me please?
Thank you for reading,
Regards.
There is no problem with your Code. And I would suggest you to write it as utility method
function getValues(selector){
var tempValues = {};
$(selector).each(function(){
var th= $(this);
tempValues[th.attr('title')] = th.val();
});
return tempValues;
}
var values = getValues('.email');
or If you want values into an array
$('.email').map( function(){return $(this).val(); }).get();
.get() will convert it to a regular array.
The code you have written is absolutely correct. But when I have loaded it was returning me null, because at the time of execution, there were no values in textboxes.
Your taskArray is actually an object, not an array.
Replacing var taskArray = {} with this should fix the problem:
var taskArray = new Array();
Edit: on second thoughts, what you have already is perfectly valid!
I'm editing my answer to echo what I've said in the comments: you'll need to debug using the console:
Within the .each(), put: console.log(id); - the expected result would be "1", "2", "3" - if it's just "3", it probably means that your other inputs aren't being picked up for whatever reason. If that is the result, print out the object after you've assigned the value: console.log(emailObj[id]);.

Categories

Resources