jQuery - Show variable, not text string - javascript

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.

Related

Update Data Attribute Object Property Value

I've gotten this to work but I would like to know if there is a straightforward way of accomplishing the update. I have a div where a data attribute has been assigned. When the div is clicked, I want one of the properties on the data attribute to be updated.
http://jsfiddle.net/quint/fq7dwsyv/
var originalObj = {
"x": 5,
"y": 58,
"selected": 'no'
};
var originalObjString = JSON.stringify(originalObj); // Convert object to JSON string
$('#test').attr('data-objData', originalObjString); // Attach data attribute to div
$('#test').on('click', function(event) {
var originalData = $(this).attr('data-objData'); // Store data attribute value
var originalDataJSON = JSON.parse(originalData); // Convert string to object
originalDataJSON['selected'] = 'yes'; // Update object property
var updatedData = JSON.stringify(originalDataJSON); // Convert object to string and store
$('#test').attr('data-objData', updatedData); // Update data attribute on div
});
I'd separate the update into its own function
$('[data-example]').click(function() {
function update(object) {
object.foo = 'bar';
return object;
}
var original = this.dataset.example;
original = original && JSON.parse(original) || {};
this.dataset.example = JSON.stringify(update(original));
});
You can store the original object with .data() and mutate it directly without having to store it again with the .data() method:
var originalObj = {
"x": 5,
"y": 58,
"selected": 'no'
};
$('#test').data('objData', originalObj);
$('#test').on('click', function(event) {
$(this).data('objData')['selected'] = 'yes';
console.log($(this).data('objData'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="test">test me</button>
Remarks
The above solution assumes you are willing to change the way the object is stored with the element. If on the other hand the value must be stored on an element attribute, then there is not much that can be improved in your code. The steps you take are then all necessary (convert from/to JSON, read from attribute, write to attribute, ...etc).
Note however that writing to element attributes is not considered best practice. If anything, you should use .prop() in favour of .attr(): it will result in faster code. But you'll not see the change when consulting the element attributes. In other words, you cannot mix .prop() with .attr().
If there is no room for change in that either, then I would suggest that you ask this question on CodeReview.

Assign variable value as variable name

the problem is i want to shorten my code by calling a variable using other variable's value
long working version:
var russia = new Array('15')
var switzerland = new Array('5')
$('.country').mouseover(function(){
switch(this.id){
case 'russia':
active_country_lift(this.id,russia[0])
break
case 'switzerland':
active_country_lift(this.id,switzerland[0])
break
}
})
it will get the id of mouseovered then check if it matched one of the variable by using switch
what i want to obtain is something like this:
var russia = new Array('15')
var switzerland = new Array('5')
$('.country').mouseover(function(){
active_country_lift(this.id,this.id[0])
})
of course the above code wouldn't work but is there a workaround for this?
UPDATE: Arun's answer worked and ill accept it soon and as for the comments requesting for the full code, here's a chunk of it after i applied Arun's
var countries = {
russia: ['-15px'],
switzerland: ['-5px']
}
$('.country_inactive').mouseover(function(){
active_country_lift(this.id, countries[this.id][0])
})
function active_country_lift(country, country_top){
if(!$('#'+country+'_active').hasClass('active')){
$('#'+country+'_active').stop().fadeIn(100).animate({
'top' : country_top
}, 200)
$('#'+country).stop().fadeOut(100)
}
}
it will be used for a world map, feel free to make any suggestions for making it more dynamic
You can store the country info in an object like a key value pair, then use bracket notation to access it dynamically
var countries = {
russia: new Array('-15px'),
switzerland: new Array('-5px')
}
$('.country').mouseover(function() {
active_country_lift(this.id, countries[this.id][0])
})
If you don't have multiple values then
var countries = {
russia: '-15px',
switzerland: '-5px'
}
$('.country').mouseover(function() {
active_country_lift(this.id, countries[this.id])
})
try using eval() function
var russia = new Array('-15px')
var switzerland = new Array('-5px')
$('.country').mouseover(function(){
active_country_lift(this.id,eval(this.id)[0])
})

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

Creating Select Box from options stored in a variable

I want to create a select box from options stored in a variable (the values will change based on the user).
For now, I'm just trying to get it to work with this variable in my javascript file:
var resp = {"streams": [ {"sweet":"cookies"}, {"savory":"pizza"}]}
In the html file, I have a select id "selectedStream"
How do I invoke, both the select id from html and the variable from javascript to create the select box?
I've seen examples such as the one below, but I don't understand how to link the id and the variable to the box.
$("option:selected", myVar).text()
I hope this was coherent! Thanks
I think what you are trying to do is append option html nodes to an existing select element on your screen with an id of 'selectedStream'. You want to use the data from the 'resp' variable to populate the text and value of the option nodes that you are appending. If this is correct, I have implemented that functionality with this jsfiddle. The javascript is also below:
$(function(){
var resp = {"streams": [ {"sweet":"cookies", "savory":"pizza"}]};
var streamData = resp.streams[0];
var optionTemplate = "<option value=\"{0}\">{1}</option>";
for(var key in streamData){
var value = streamData[key];
var currentOptionTemplate = optionTemplate;
currentOptionTemplate = currentOptionTemplate.replace("{0}", key);
currentOptionTemplate = currentOptionTemplate.replace("{1}", value);
$("#selectedStream").append($(currentOptionTemplate));
}
});
Is that array necessary? If you're just trying to display the keys within that object I'd create a for loop:
var resp = { "streams": {"sweet": "cookies", "savory": "pizza"} }
for (property in resp.streams) {
$('#selectStream').append($('<option/>', {text: property, value: property}));
}
JSFiddle: http://jsfiddle.net/pWFNb/

Fill observable-fields-object by same fields-names object

I have object that all of its fields are observable (knockout.observable).
I have other regular object too, that its fields have the same names like the first-object-fields.
I want to insert into each field of the first object, the value of the match-field at the second object.
For example:
var first = {
a:ko.observable(),
b:ko.observable()
};
var second= {
a:'my'
b:'fields';
};
I want the first object to look like:
first = {
a:ko.observable('my'),
b:ko.observable('fields')
};
Yes, of course, I can do it by 'each' loop.
But, my question is:
Is there any build-in function that does it?
You can use the ko.mapping plugin:
var results = ko.mapping.fromJS(second, first);
See Documentation

Categories

Resources