I am trying to bind my selected category's guid property to another ko.observable element. I need to hold that data value in order to send it to the server in a correct JSON format.
Jsfiddle
I am stucked at the binding selected category's guid value to SelectedCategoryGuid in order to appear in JSON file like
'SelectedCategoryGuid': 'guid1'
I have tried $data and $root bindings in the HTML but couldn't achieve it.
Step 1: Remove the quotes around your value data-bind. You should pass a reference to an observable here, not the name of a property.
value: Info.SelectedCategoryGuid
Now, you'll see your guid paragraph print: [object Object]. That's because it's storing the whole category, not just the Guid.
Step 2: To only store the Guid property, use the optionsValue binding. This binding works similar to the optionsText binding you've already used:
optionsValue: 'Guid'
Now things start working as intended. You'll notice the initial bla value gets cleared, because it does not appear in your data set.
Here's the two changes in a fiddle: https://jsfiddle.net/40sh1vjj/
Related
I wonder if there is a way to get a certain element of an array, which is stored in a single value. Sounds weird, I know, but this is my problem:
HTML
<select id="select">
<option value='{"array":["a","b"]}'>Option</option>
</select>
<button onClick="getArrayIndex()">Button</button>
--> I got one array with two elements (a and b) stored isnide one value in an option tag.
JS
function getArrayIndex() {
alert(option.value[0]);
}
So what I need is that the alert message displays only one element of the array, I hope this is somehow possible, thanks for answers! As you can see I tried to display only element 0, in this case "a", but it doesn't work.
I also tried these:
alert(option.value.array[0]);
alert(option.value.array(0));
alert(option.value(0));
alert(option.value.[0]);
...and so on. But none of these work.
Your value is a string containing JSON defining an object containing an array property with an array, rather than actually being an array. To use just the first element in that array, you need to parse the JSON into the object and array, then access the array from the object and get its first element:
alert(JSON.parse(option.value).array[0]); // "a"
Note that your getArrayIndex function currently uses an option identifier that doesn't appear to be defined anywhere. If you want to use the currently-selected value in the select, then:
function getArrayIndex() {
const select = document.getElementById("select");
const value = select.value;
if (value) {
alert(JSON.parse(value).array[0]);
}
}
Side note: I would xyz-attribute-style event handlers. Instead, hook up the event handler using modern techniques (such as addEventListener). Also beware that the default type of the button element is "submit", so if that button is in a form, by default it will submit the form.
I am updating a data attribute by jQuery, Like:
jQuery('div').data('hidden', 'true');
alert(jQuery('div').data('hidden'));
Data attribute value got changed and returned new value which is true but DOM is still showing the old value which is false.
When you use .data() to update a data value, it is updating internal object managed by jQuery, so it will not be updated in the data-* attribute
I was beating around the bush so badly :( and able to solve the problem. Seams like we can't do achieve this using the jquery data method if the html is dynamic and the data attribute changed later after accessing the first time.
According to jQuery.data()
The data- attributes are pulled in the first time the data property is
accessed and then are no longer accessed or mutated (all data values
are then stored internally in jQuery).
So what I did is, changed it to attr method which won't give you the parsed value for integer, so you have to use '+' operand to convert like:
+ myElement.attr('data-index');
Note: You have to be careful, it will convert the result to NaN if there is any string in the data attr. BTW it's your choice of implementation of the code.
I have a one span tag with data attribute, data-kr-id. On clicks of different items of the list, I update this span's data-kr-id attributes and it gets updated.
When for the first time I retrieve this(data-kr-id) value using jQuery's data method, I get the correct value. But from the subsequent time, I always get the same value as of the first time. But on using jQuery's attr function, I get the correct value. Can't figure out why.
CODE: Where I set the data-kr-id value:
$_applozicWtLauncherBtn.attr('data-kr-id', seller.UserId);
CODE: Where I retrieve the values:
var topicId = $applozic(this).data("kr-id");
topicId = $applozic(this).attr("data-kr-id");
In the above code where I retrieve values, using data method gives me old value(the value of the first item I retrieved), but using attr method gives me correct value.
UPDATE :
As informed by everyone, I was setting the data attributes with attr method and retrieving the value with data method. After using data method for setting the attribute, When I was retrieving the values, I was getting a getting empty string. After digging a bit deeper, I realized there are two different versions of the jQuery are being used here.
Sorry for the incomplete information and late update.
You set value only using attr, Second time when you set data-kr-id value using attr then data value remains same, so need to set value with data also
// With Attr
$_applozicWtLauncherBtn.attr('data-kr-id', seller.UserId);
// With Data
$_applozicWtLauncherBtn.data('kr-id', seller.UserId);
Actually jquery's .data() fetches value from the property (same as .prop()) not from attributes. Main difference is .attr() fetches data from HTML tag which you can see it will reflect on your HTML when you update it with .attr(). But when you use .prop() or .data() it will not reflect in HTML tag but it will update value in it's property for that HTML tag as per the DOM tree.
You'll find out more about difference property and attribute from here.
Initially this property will set when your element is created. So for the first time your .data() and .attr() will work fine. When you update value from .attr() it will manipulate DOM but property will be remain same.
I have defined my select as below
<select id="selProductType" data-bind="options: productType , value: editProductType , optionsText: 'Name'" />
Below is my code to fill the select in my view model
// Loading combobox with Product Types
$.getJSON("../RestService/Product/AllProductTypes",
function (allData) {
var mappedProductType = $.map(allData, function (item) {
console.log(item.Id + ' ' + item.Name);
return new productType(item);
});
self.productType(mappedProductType);
});
When i initialise page i want to set default value to select. So i tried below
self.editProductType(4);
But it gives me TypeErrror saying object 4 has no method Id.
How to go about it. I have also gone through similar post in stackoverflow but no luck.
Knockout JS binding initial/default value of dropdown (select) list
If you don't specify the :
optionsValue: 'Id'
in data-bind, the binding value in this case must be an object in productType array.
You can select the default object:
self.editProductType(self.productType()[2]);
What is optionsValue?
Similar to optionsText, you can also pass an additional parameter called optionsValue to specify which of the objects’ properties should be used to set the value attribute on the elements that KO generates. You can also specify a JavaScript function to determine this value. This function will receive the selected item as its only argument and should return a string to use for the element’s value attribute.
Typically you’d only want to use optionsValue as a way of ensuring that KO can correctly retain selection when you update the set of available options. For example, if you’re repeatedly getting a list of “car” objects via Ajax calls and want to ensure that the selected car is preserved, you might need to set optionsValue to "carId" or whatever unique identifier each “car” object has, otherwise KO won’t necessarily know which of the previous “car” objects corresponds to which of the new ones.
read more at: http://knockoutjs.com/documentation/options-binding.html
I'm struggling with Knockout.js Options binding, to an Object.
I'm attempting to create a workflow for the user that allows them to add an Item, edit its properties and then save/cancel to propagate those changes.
I've accomplished this type of task before with jquery. However I'd like to avoid the complicated stack calls that jquery would require. (if possible).
I've created an example:
http://jsfiddle.net/nAE2f/
Whats working in the example:
The Add button, creates a new object.
The Save Button will save it to the array.
The Select Dialog will update with a new Option.
Unfortunately, this is where my progress has halted. While the Select Option is created, it doesn't reflect the underlying objects Name. Also Switching between objects doesn't change the forms properties as I would expect.
I've tried assigning the optionValue to the id, but in that case the Select Options isn't created on save.
The problem with the way you binding member name to item. In your case saved item always has empty name that's why select also display empty text. I fixed this by creating selectedMember property within ViewModel to handle selected member and assigning member name to item on Save.
Check fiddle for example