set option value in dropdown - javascript

I am attempting to set an option in a dropdown/select. I have done this before, but for some reason I am getting an error and I am not sure why.
Code
var _loc = {
ALL_BUYS: [{ Text: "All Buys", Value: "AAA"}],
NETWORK_BREAK: [{ Text: "Network Break", Value: "NTN"}],
SYNDICATED_BREAK: [{ Text: "Syndicated Break", Value: "STA"}],
LOCAL_BREAK: [{ Text: "Local Break", Value: "LTA"}],
NATIONAL_LOCAL: [{ Text: "National/Local", Value: "LTN"}],
LOCAL_LOCAL: [{ Text: "Local/Local", Value: "LTL"}]//,
};
lstOptions = $("<select></select>");
$.each(_loc, function (i, item)
{
$("<option></option>")
.appendTo(lstOptions)
.html(item.Text)
.val(item.Value) // receive error: Object has no method 'val'
});

You're not grabbing the values from the object correctly.
The format is like so:
{key1:[{0, 1}], key2:[{0, 1}], key3:[{0, 1}]}
When you use $.each, it selects each one in this state:
[{0, 1}]
On the first iteration, it would select the value associated with key1, on the second, key2, etc.
Since you have arrays nested in each key's value, you need to specify that it locate the first array in the matched value:
var _loc = {
ALL_BUYS: [{ Text: "All Buys", Value: "AAA"}],
NETWORK_BREAK: [{ Text: "Network Break", Value: "NTN"}],
SYNDICATED_BREAK: [{ Text: "Syndicated Break", Value: "STA"}],
LOCAL_BREAK: [{ Text: "Local Break", Value: "LTA"}],
NATIONAL_LOCAL: [{ Text: "National/Local", Value: "LTN"}],
LOCAL_LOCAL: [{ Text: "Local/Local", Value: "LTL"}]
};
lstOptions = $("select");
$.each(_loc, function(i, item){
$("<option></option>")
.appendTo(lstOptions)
.html(item[0].Text)
.attr("value", item[0].Value);
});​
Demo.
Note the item[0]. What this does is select the array with the index 0 in the value that it grabbed. Since there is only one, that single array's index is 0, so it's selecting that specific one. Then you find and set its text and value.
Also note that I changed val() to attr(), because option elements don't support val() (you could, however, use it on a select element to set the option whose value is equal to the one specified in this function to make it selected).
TIP: You could also get rid of the literal array indicators around each nested object and use the original method. Demo.

<option> elements do not support val(). I think you want to use attr()
.attr("value", item.Value)

.val() is used to get the value of form elements. It is not a short-cut to setting the value attribute of an element. To do this, you can use:
.attr("value", item.Value)

Figured it out. I want my items in the loop to be in the following format
Item: "All Buys"
Value: "AAA"
Instead they were in this format
[0]Option
Item: "All Buys"
Value: "AAA"
If I change my loop to this it works
$.each(_loc, function (i, item)
{
$("<option></option>")
.appendTo(lstOptions)
.html(item[0].Text)
.val(item[0].Value);
});

Related

Can't push array item to array data property - Vue Js

I a getting data from the laravel using this response :
$unserialize = unserialize($import->field_names);
return response()->json( $unserialize, 200 ) ;
Now on the Vue JS I can console the response using this :
console.log(response);
and It's showing the data in array (Check the red arrow mark):
Now, I have a options empty array property like this:
options : []
I want to push object data to this array with a key value and text. This key's value will be that response data single item. So, To do this, I am using this:
response.data.forEach((item, index) => {
this.options.push({
value: item,
text: index
});
});
but If I console
console.log(this.options);
I can not see the array of object to this options propery. I can see this:
can you tell me why? I want this options should store the item like this:
options: [
{ value: null, text: 'Please select some item' },
{ value: 'a', text: 'This is First option' },
{ value: 'b', text: 'Default Selected Option' },
{ value: 'c', text: 'This is another option' },
{ value: 'd', text: 'This one is disabled', disabled: true },
]
Update:
Console.log(response);
I think that the problem could be in this keyword
you can modify your code in this way
this.options = [...this.options,
...response.data.map((item, index) =>
({
value: item,
text: index
})
)]

JavaScript: Take an index of an item in an array, and figure out what the index of the same item would be if the array were reversed?

The Setup
I have an array of objects called Elements. They are visually laid out like layers in a photoshop document. I have stripped out most of the data from each element for brevity. But the data changes for each element, because they are all different.
elements = [
{
name: 'First Piece',
},
{
name: 'Second',
},
{
name: 'Third',
},
{
name: 'Fourth', // is selected
},
{
name: 'Fifth',
},
]
I keep track of which element is selected in an object using the index of the selected item. I use the index because it is always available to me at any given time or place the elements are represented. The object looks like this, sans the non relevant data:
selected = {
element: 3,
}
This all works great.
The Problem
The problem lies in what could be considered my Layers panel. When the elements are on the 'canvas', they are in the correct order with each element having a higher z-index. But in the layers panel, I have to reverse the array so that it visually makes sense. So the 'Fifth' element is on top.
The problem is when I need to take the value of selected, and apply it to the reversed elements array.
elementsReversed = [
{
name: 'Fifth',
},
{
name: 'Fourth', // this should be selected
},
{
name: 'Third',
},
{
name: 'Second', // would be selected
},
{
name: 'First Piece',
},
]
I can't use .findIndex() because the names could be set to the same value (for a reason) and there aren't really other attributes I could use to search through a reversed array and find the index that way. I am trying to avoid adding another key/value pair to my objects like an ID.
Is there a way to do this? Am I just being a dum dum?
Thank you.

Return true if an array within an array contains specific key

I have the following the object:
items: [
{
object_a {
id: "1",
value: "somevalue1"
}
},
{
object_b {
id: "2"
value: "somevalue2"
items:[
{
nested_object_a {
id: "3"
value: "somevalue3"
},
nested_object_b {
id: "4"
value: "somevalue4"
},
}
]
}
},
]
I can check if the value key exists in the initial items array:
items.some(item => item.hasOwnProperty("value"));
To see if the value key exists in the nested object_b item array I can do the following:
items[1].object_b.items.some(item => item.hasOwnProperty("value"));
Instead of specifying which number in the array to look in I need to make the final expression dynamic. I'm certain I need to do a find or a filter on the top level items, but I've had no luck with it so far.
I found that using an every function on the items allowed me to return the boolean value I required form the array. The problem this created is any array item that didn't have the object_b key on was returning null and breaking my app. It turns out I needed to use an optional chaining operator to get around this (.?).
Thanks to #ikhvjs for linking that stackedoverflow article.
Working code:
items.every(item => {
item.object_b?.items.some(item => item.hasOwnProperty("value"));
});

How to determine binding type for items in a sap.m.Select?

When using a sap.m.Input, I can configure the element like in the example below, in order to set the type of the item that is binded to the Input:
<mvc:View>
<Input value="{
path:'/company/revenue',
type: 'sap.ui.model.type.Float'
}"/>
</mvc:View>
this way, when I retrieve the property inside '/company/revenue', its type will always be a JavaScript number. However, is it possible to apply a similar "typing" to a sap.m.Select? The property "selectedKey" inside a sap.m.Select always returns a JavaScript String, but I would like to type it to a number like I did with the sap.m.Input above. How can I do it? Thanks in advance!
Yes, you can do that. It's just a normal property binding.
But beware that the keys of your items inside the Select control have to be compatible with the Float type. The sap.ui.model.type.Float without any formatOptions generates locale dependant strings. So in germany f.e. you get a , as decimal separator and in the US it would be ..
A good idea would be to use a aggregation binding to create the items and configure the keys of the items with the same type as the selectedKey property of your select. See example on JSbin.
<Select
selectedKey="{path:'/selectedKey',type: 'sap.ui.model.type.Float'}"
items="{/items}">
<c:ListItem
key="{path: 'key', type: 'sap.ui.model.type.Float'}"
text="{text}"/>
</Select>
onInit:function(){
var data = {
selectedKey:3,
items: [
{ key: -1, text: "Item 1" },
{ key: 1.234, text: "Item 2" },
{ key: 3, text: "Item 3" },
{ key: 1234, text: "Item 4" }
]
};
var model = new sap.ui.model.json.JSONModel(data);
this.getView().setModel(model);
}

AngularJS : How to concat two arrays?

I have following arrays with values (i am generating the values on go)
$scope.objectName = [{ Name: '' }];
$scope.propertiesElement = [{ Key: '', Value: '' }];
I want to concatenate these two objects to get the following result
[{Name:''},{ Key: '', Value: '' }]
Plunker link , somehow that's not working either
when I click on the add row button it will add another row for key and value text boxes only not for name, I can add n no of rows and when I click on Submit it should show the kev value pair as
[{Name:''},{ Key: '', Value: '' },{ Key: '', Value: '' },{ Key: '', Value: '' }.....so on]
Thanks
Not sure why you want to build an array of mismatched objects. That seems to me to be asking for trouble. I would suggest possibly doing the following:
$scope.objects = [{Name: '', Elements: []}];
Then you can easily manage multiple objects who have elements:
(I use underscore http://underscorejs.org/)
$scope.addElementToObject = function(objName, element){
_.where($scope.mergedArray, {Name: objName}).Elements.push(element);
};
Then you can add to the list of elements for that object without having to eval the object in the elements array on each use.
If you still want/need to merge arrays of mismatched objects, it would be the following:
$scope.objectName = [{ Name: '' }];
$scope.propertiesElement = [{ Key: '', Value: '' }];
$scope.mergedArray = $scope.objectName.contact($scope.propertiesElement);
$scope.addElement = function(element){
$scope.mergedArray.push(element);
};
Then, in your click event code:
$scope.addElement({ Key: 'someKey', Value: 'Some Value' });
I hope this helps.

Categories

Resources