Get name of field being passed - javascript

I have two sets of lists (state lists)
One called state_o and one called state_d and I have a function I do on them
function selectCountry(sel) {
document.getElementById("country_o").selectedIndex = states[sel.value];
}
Now what I want to do is determine if the "sel" is state_o or state_d and change the getElementById("country_o") to either _o or _d depending on what state is selected, so state_o would do country_o and state_d would do country_d
How can I determine the select field name?
Thanks!

You can access the name property through javascript:
function selectCountry(sel) {
var od = sel.name == "state_o" ? "o" : "d";
document.getElementById("country_"+od).selectedIndex = states[sel.value];
}
Or if you want to be a bit fancier and keep it on one line, slice the o/d straight from the name string:
function selectCountry(sel) {
document.getElementById("country_"+sel.name.slice(-1)).selectedIndex = states[sel.value];
}

If I've understood your question right, it's just:
var field;
if (sel.value == 'state_o')
field = 'country_o';
else
field = 'country_d';
document.getElementById(field).selectedIndex = states[sel.value];

If sel is the select element, sel.id or sel.name should give you what you want.

Keep another parameter in this function to see if its _o or _d and set this value in calling function.
then in your javascript method you can call country by -
document.getElementById("country" + param2)
Assuming param2 is that additional parameter and it will contain string "_o" or "_d"

Use sel.attr('name') if you're using jQuery or sel.name if just using plain old Javascript
Assuming you have:
<SELECT name='state_o'>
<OPTION value='blah'>BLAH</OPTION>
</SELECT>
<SELECT name='state_d'>
<OPTION value='blah'>BLAH</OPTION>
</SELECT>

Related

How to filter array of items with multiple dropdowns on single angularjs custom filter function?

I am facing a problem with the filter function in Angularjs, here I used a common function ng-change for multiple a dropdown. But when I select All(default options) I am getting an empty array of filtered items.
Here is my code
Javascript:
function customFilters() {
vm.filteredItems = $filter('filter')(vm.claimsResData, {
status: vm.status,
member: vm.member,
treatment: vm.treatment
});
}
Html:
<select ng-model="vm.member" class="form-control"
ng-options="names for names in vm.memberNames"
ng-change="vm.customFilters()">
<option value="">All Members</option>
</select>
Any help would be appreciated.
Thanks.
Update your function as below, because when you want to exclude a key from filter you've to pass undefined to its value, but in your code you are passing blank string i.e., ""
function customFilters() {
vm.filteredItems = $filter('filter')(vm.claimsResData, {
status: vm.status,
member: vm.member || undefined,
treatment: vm.treatment
});
}
Only add the selection to the pattern object if the selection is truthy:
function customFilters() {
var patternObj = {}
vm.status && patternObj.status = vm.status;
vm.member && patternObj.member = vm.member;
vm.treatment && patternObj.treatment = vm.treatment;
vm.filteredItems = $filter('filter')(vm.claimsResData, patternObj);
}
A pattern object is used to filter specific properties on objects contained by the array. When that property exists on the pattern object, the objects in the array must have that property.
For more information, see
AngularJS filter Filter API Reference

Apply ng-blur functions return to ng-modal

i have 2 input fields named data1 and data2. I have assigned a ng-blur function to it. ITs a common function for both input fields. Now i need to use this function and use it for the 2 input fields.
<input ng-model="data1" ng-blur="checkAndApplySign(data1, false);">
<input ng-model="data2" ng-blur"checkAndApplySign(data2, true);">
I am using the below function. if toNegative is set to false at the HTML, we should get all positve values returned. if it is set to true, all negative values
$scope.checkAndApplySign = function (value, toNegative) {
return (toNegative ? -1 : 1) * Math.abs(value);
};
The problem with this is that the return function doesnot assign the values back to the input field. how do i assign it back to input field ? any ideas ?
I haven't tested this, but my best guess is that, assuming your models are objects, they will be passed to the function as references. Knowing this, you should just be able to assign the value directly to the input value and its relationship with the input via ng-model should update the input value.
$scope.checkAndApplySign = function (value, toNegative) {
value = (toNegative ? -1 : 1) * Math.abs(value);
};

assign a object to select value - ng-options

I have a object like this
var myObject = {'123':'something','345':'something else'}
I need to render it as:
<option value={'123':'something'}>something</option>
Here is what i have tried:
ng-options="someObj as label for (id,label) in myObject
Doesn't work!
The model gets the 'label' and not the whole object. Is it even possible to assign a object to value attribute of a SELECT element?
EDIT
Filter for object of the form: {'123':'something','345':'something else'}
.filter('putKeysandValues',function(){
return function(options){
var arr = [];
angular.forEach(options,function(value,key){
arr.push({'key':key,'label':value})
});
return arr;
}
});
You will need to provide an object with key & value attributes to ngOptions. For this you will need to modify the structure of your object to actually have this attributes.
One way is using a filter that returns a valid array for ngOptions:
ng-options="option.label for option in data.availableOptions | putKeyAndValue"
You can check out this plunker with a working filter.
If input is:
[{'123':'something'}, {'345':'something else'}]
Then output is:
[{"123":"something","id":123,"label":"something","$$hashKey":"object:3"},{"345":"something else","id":345,"label":"something else","$$hashKey":"object:4"}]
If you want to remove the obsolete id attribute, then use this filter.
With input the same input, it will return this:
[{"id":123,"label":"something","$$hashKey":"object:3"},{"id":345,"label":"something else","$$hashKey":"object:4"}]
If you still need to return a new array, then do not do it on the filter. In that case you can process the data before passing it to the view, all in the controller like this.
With input:
{'123':'something', '345':'something else'}
Output this:
[{"id":123,"label":"something"},{"id":345,"label":"something else"}]
Using select as something for a (key,value) in set of Values
ng-options="key as value for (key,value) in myObject"
This will put key into the option value and value into label. With that you need to also use ng-model and ngChange. Since you can't pass objects into values, idea is to do that in your controller.
<select ng-model="val" ng-change="changeVal(val)" ng-options="key as value for (key,value) in ops">
In your controller you already have myObject you are gonna add selected item and changeVal function
<script>
var selectedObject;
$scope.changeVal = function(val){
selectedObject = {};
selectedObject[val] = myObject[val];
}
</script>
It's a workaround without putting object into value attr since it is a string.

Updating multiple dropdowns with json data

What is good practice when storing an HTML select dropdown into a JavaScript variable. I also need to capture the value which they selected and pass that through.
I originally tried to use jQuery to create the option and hold it in a variable but it would error out.
var keyNamesList = $('<option></option>').val('').html('Select a Key');
I then used an HTML string and appended the options list in a loop with with more HTML represented as a string. See JSFIDDLE link for a mock up.
var keyNamesList = "<option value = ''> Select an item</option>"
keyNamesList += "<option value = '"+data.key+"'>" + data.value + "</option>";
JSFIDDLE
$('<option></option>')...
Should just be $('option').
PS: What are you trying to do?
It's unlikely that using an append per option and setting the value and content via the DOM API is going to cause a big performance hit, but just as general rule it's considered good practice to avoid multiple append and DOM mutation calls if you can, so I would normally build a single HTML string:
function getOptions(data, blank) {
var optTpl = '<option value="%key%">%label%</option>',
options = [];
if (blank) {
// if blank is truthy then append an option - if bool true then
// a default label, otherwise use the value of blank as label
options.push(optTpl
.replace('%key%','')
.replace('%label%', (blank === true ? 'Select one...' : blank))
);
}
$.each(data, function (i, datum){
options.push(optTpl
.replace('%key%',datum.key)
.replace('%label%', datum.value)
);
});
return options.join('');
}
// usage:
$('theSelectElement').append(getOptions(data, 'Select something!'));
I like to use a kind of template and call string replacements but you could build the strings on each iteration like you proposed in your question:
options.push("<option value = '"+data.key+"'>" + data.value + "</option>");
Example un-integrated with yours: http://jsfiddle.net/8tjwL6u5/

code to set a select box option value as an object

in an html page i have got, i have a select box like this with values.
<select onChange="return filler(this.value);">
<option value="{'name':'rajiv',age:'40'}">a</option>
<option value="{'name':'mithun',age:'22'}">f</option>
</select>
i want to pass a javascript array or object as the option value.
right now it is treating the option value as a string.
i want it to be an array so that i can access it by
this.value.name,this.value.age in the filler function.
is this possible?
You will not be able to store objects/arrays in the value attribute, however an option would be to use data-* attributes which supports json automatically with jQuery 1.4.3+
<select>
<option data-value='{"name":"rajiv","age":"40"}'>a</option>
<option data-value='{"name":"mithun","age":"22"}'>f</option>
</select>
And using .change()
$("select").change(function(){
alert($(this).find(":selected").data("value").age);
});
Example on jsfiddle
No, not just like that. Values have to be strings. I'd strongly recommend to use something like jQuerys .data() method to hold Arrays or Objects in an expando property.
If it must be in the value, you just need to JSON decode (.parse) it:
var myValue = JSON.parse(this.value);
myValue.age; // 40
myValue.name // rajiv
But again, I don't think this is a good solution. Have a look at http://api.jquery.com/jQuery.data/
Also, jQuery will automatically convert Arrays and Objects if you put the JSON strings in any data- HTML5 attribute. For instance:
<option value="A" data-info="{'name':'rajiv',age:'40'}">something</option>
If you access that node with jQuery now, we automatically got that object in it's data expando
$('option').data('info').name; // === rajiv
You can use parseJSON to convert the string to an object when using it, but the value needs to be a string.
var option = $('select').val();
var selected = $.parseJSON(option);
alert( selected.name + ': ' + selected.age );
React solution
const myObjects = [
{
text: 'a',
value: 1
},
{
text: 'b',
value: 2
},
];
const handleSelectChange = (myStringifyObject) => {
const myObject = JSON.parse(myStringifyObject);
// logic with myObject
}
<input type='select' onChange={(evt) => handleSelectChange(evt.target.value)}>
{myObjects.map((myObject) => (
<option
value={JSON.stringify(myObject)}
key={myObject.value}
>
{myObject.text}
</option>
))}
</input>

Categories

Resources