I am working on an angularjs project and i have a problem with the ngModel not binding within the select.But the same concept is working in another select tag and in the same html page.
Below is the code.
<select ng-model="selectedFont"
ng-options="font.title for font in fonts"
ng-change="onFontChange()">
</select>
onFontChange() function is placed in the controller.
Anyone help is highly appreciable...Thanks in advance.
Based on Tony the Pony's fiddle :
<div ng-app ng-controller="MyCtrl">
<select ng-model="opt"
ng-options="font.title for font in fonts"
ng-change="change(opt)">
</select>
<p>{{opt}}</p>
</div>
With a controller:
function MyCtrl($scope) {
$scope.fonts = [
{title: "Arial" , text: 'Url for Arial' },
{title: "Helvetica" , text: 'Url for Helvetica' }
];
$scope.change= function(option){
alert(option.title);
}
}
http://jsfiddle.net/basarat/3y5Pw/43/
First create data (can be local or from server) in Controller. And initialize the default value, which force the default item selected in HTML form.
// supported languages
$scope.languages = ['ENGLISH', 'SPANISH', 'RUSSIAN', 'HINDI', 'NEPALI'];
// init default language
$scope.language = 'ENGLISH';
Now in your HTML form
<select class="form-control" ng-model="language">
<option ng-repeat="language in languages">{{language}}</option>
</select>
The screenshot is here (note bootstrap CSS is used and not included here).
You can do a test in controller, whether the change is working
$scope.$watch('language', function (newVal, oldVal) {
console.log(oldVal + " -> " + newVal);
});
ENGLISH -> RUSSIAN
RUSSIAN -> SPANISH
SPANISH -> RUSSIAN
Hope this is helpful. Thanks!
Related
I am using a date picker somewhat similar to this example
File: datepicker.vue
<template>
<v-menu
v-model="dateMenu"
:close-on-content-click="false"
:nudge-right="40"
:return-value.sync="dateValue"
transition="scale-transition"
offset-y
>
<template v-slot:activator="{ on }">
<v-text-field
:label="dateLabel"
prepend-icon="fa-calendar"
readonly
v-model="dateValue"
v-on="on"
clearable
></v-text-field>
</template>
<v-date-picker
locale="en-in"
v-model="dateValue"
no-title
#input="dateMenu = false"
>
<v-spacer></v-spacer>
<v-btn
text
color="primary"
#click="dateMenu = false"
>Cancel</v-btn>
<v-btn
text
color="primary"
#click="$refs.dialog.save(dateValue)"
>OK</v-btn>
</v-date-picker>
</v-menu>
</template>
<script>
export default {
props: ['dateLabel','dateModel'],
data() {
return {
dateMenu: false,
dateValue: this.dateModel,
};
},
watch: {
dateValue(){
$nuxt.$emit('update',this.dateValue);
}
},
};
</script>
File: projects-subform.vue
...
<DatePicker
dateLabel="Project Start Date"
:dateModel="project.start_date"
#update="(v) => (project.start_date = v)"/>
...
(I exported DatePicker as a component from the projects form. )
When I select the date from picker UI, the display text on the v-text-field does not reflect the selected date. Also, the model project.start_date does not seem to update after I select the date from my datepicker. It becomes very tricky to debug when event errors like this don't show up on the dev tools console.
First of all, it is not recommended to change the model passed in as a prop directly. We don't want any unwanted breaks in the parent component. Rely on events. Somehow even this style of passing also didn't work quite well for me.
I did some workaround like this. (I know it is a very dirty way). But for some reason $emit with input/update/change just fails to be detected in the parent component. I am very sure there's a better way of doing this. But for now, moving on with life. :-(
File: datepicker.vue
<template>
...
<v-date-picker
locale="en-in"
v-model="dateValue"
no-title
#input="dateMenu = false;"
#change="saveDate" //change here
>
</v-date-picker>
...
</template>
<script>
...
methods(){
saveDate(val){
this.dateValue = val;
//changed here...emitting a custom event.
$nuxt.$emit("datePicked",{
project_number:this.project_number,
selectedDate: selDateVal
});
this.$refs.dateMenu.save(selDateVal);
}
...
</script>
File: project-subform.vue
...
<script>
...
created:{
this.$nuxt.$on('datePicked',this.updateDate);
}
...
methods:{
updateDate(v){
//do my stuff
this.projects[v.project_number].startDate = v.selectedDate
}
}
</script>
I am running laravel backpack 3.4 and created a custom select2 fieldtype from the standard one, I am now trying to based on an onchange event change the value selected on another select options but no change is happening
This is the field declararion
<select onchange="updateunit(this, '{{$field['name']}}' )" id="{{$field['name']}}_<% $index %>" data-index="<% $index %>"
ng-model="item.{{ $field['name'] }}"
[ngValue]="value"
#include('crud::inc.field_attributes', ['default_class' => 'form-control select2'])
>
<option value="">-</option>
#if (isset($field['model']))
#foreach ($field['model']::all() as $connected_entity_entry)
<option value="{{ $connected_entity_entry->getKey() }}"
>{{ $connected_entity_entry->{$field['attribute']} }}</option>
#endforeach
#endif
</select>
And this is the way I am trying to modify the select field selected option
function updateunit(object,name){
var fieldname;
fieldname = object.id;
fieldname = fieldname.replace('product_id','order_unit');
/* data:'_token = <?php echo csrf_token() ?>', */
$.ajax({
type:'POST',
url:'/getmsg',
data: {id:object.value},
async: false,
success:function(data) {
alert(fieldname);
alert(data.msg);
document.getElementById(fieldname).value = data.msg;
},
error:function(){alert('Unidade de Compra não está definida')},
});
This is not working, but I have not enough knowledge either on JS neither Angular to understand why this won't bind.
The elements that are created by your field configurations use the jquery select2 plugin to create a fancy select box. It does this by hiding the plain select element then displaying an html structure that builds the fancy dropdown etc in its place.
document.getElementById(fieldname).value = data.msg; will set the value of the hidden select field, but will not update the value shown by the plugin's fancy html dropdown.
To make the value that's display by the plugin change, we have to call .trigger('change') so the select element tells any listening javascript (ie the select2 plugin) that it's internal value has changed and the plugin should now update its display to match. ie, run this:
$('#'+fieldname).val(data.msg).trigger('change')
See more detailed documentation here
I'm trying to use a custom Input component on a Typeahead with the multiple option set. I see in the docs it says to "handle the refs" correctly, but I see no examples of how this is done. I'm not sure what to pass into referenceElementRef. Everything I've tried so far just doesn't render the options as I type. I see them in the DOM, but the opacity of the .rbt-menu is set to 0, so they're basically hidden.
Here's my code so far:
const divRef = React.useRef(null);
return (
<Col>
<div ref={divRef}>
<span className="uppercase">
<FormattedMessage id="d.customer" defaultMessage="Customer" tagName="h4" />
</span>
<AsyncTypeahead
multiple
id="customer-filter-input"
inputProps={{
'aria-label': 'Customer search',
style: { fontSize: '14px' },
}}
key={'customer-input'}
minLength={4}
isLoading={props.isLoadingcustomersSuggestions}
delay={300}
onSearch={(term: string) => handleFilterInputs(term, 'customers')}
size={'lg'}
options={dataSource}
labelKey={'defaultMessage'}
placeholder={intl.formatMessage({
id: 'companyName',
defaultMessage: 'Company name',
})}
onChange={(filterItem: any) => handleAutocompleteUpdate(filterItem, 'customer')}
renderInput={({ inputRef, referenceElementRef, ...inputProps }: any) => (
<Input
{...inputProps}
style={{ position: 'relative' }}
ref={(input: any) => {
inputRef(input);
referenceElementRef(divRef); // What do I put here?
}}
/>
)}
/>
</div>
</Col>
);
And this is what renders in the DOM after I type in the Typeahead and get results:
Any ideas or working examples of Typeahead using multiple and renderInput together?
EDIT:
Here's a codesandbox of what I'm seeing. I also see that the problem is also happening when multiple is NOT set. It seems to be an issue with using renderInput. Is it required that I also use renderMenu?
https://codesandbox.io/s/react-bootstrap-typeahead-async-pagination-example-forked-3kz3z
If you upgrade the typeahead version in your sandbox to the latest version (v5.1.1) and pass the input element to referenceElementRef, it works (note that you need to type some characters into the input for the menu to appear):
// v5.0 or later
renderInput={({ inputRef, referenceElementRef, ...inputProps }) => (
<Input
{...inputProps}
ref={(input) => {
inputRef(input);
referenceElementRef(input);
}}
/>
)}
The menu is rendered in relation to the referenceElementRef node by react-popper. In most common cases, the reference node will be the input itself. The reason there's both an inputRef and a referenceElementRef is for more complex cases (like multi-selection) where the menu needs to be rendered in relation to a container element around the input.
If using v4 of the component, the approach is similar, but the ref to use is simply called ref:
// v4
renderInput={({ inputRef, ref, ...inputProps }) => (
<Input
{...inputProps}
ref={(input) => {
inputRef(input);
ref(input);
}}
/>
)}
I am stuck here and would very much appreciate help. I have a form in a razor view with a input field for current city which looks like this:
#Html.LabelFor(x => x.UserModel.CurrentCity)
#Html.TextBoxFor(x => x.UserModel.CurrentCity, new { #data_bind = "value: UserModel.CurrentCity ", #class = "city", #data_val = "true", #data_val_required="City is required" })
#Html.ValidationMessageFor(x => x.UserModel.CurrentCity)
I want autocomplete for this field and am using jquery token input plugin for this like:
$(".city").tokenInput('#Url.Action("AutocompleteCity", "Settings")',{ minChars: 2, tokenLimit: 1, hintText: "Type in a city" });
$(".city").tokenInput("add", {name: viewModel.UserModel.CurrentCity()});
Everything works fine except the clientside unobtrusive validation. The form gets posted even if CurrentCity is empty.
I also tried to change the MVC helpers to plain html:
<input data-val="true" data-val-required="City is required" type="text" class="city" data-bind = "value: UserModel.CurrentCity, attr: { name: 'UserModel.CurrentCity', id: 'UserModel.CurrentCity'}" />
<span class="field-validation-valid" data-valmsg-for="UserModel.CurrentCity" data-valmsg-replace="true"></span>
This approach prevents the form from being submitted but the validation-error class is not injected into the span and the error message does not show up.
Any suggestions?
The original input element you created is hidden. You will likely need to enable validation of hidden elements: jquery.validate v. 1.9 ignores some hidden inputs or https://stackoverflow.com/a/13295938/173225.
I have a strange behaviour with the code below:
function update(txt, _)
{
#text = <>{txt}</>
#data = <>{txt}</>
}
command = <a onclick={update("test1", _)}> change text1 </a> <+>
<a onclick={update("test2", _)}> change text2 </a>
content = <textarea style="width:30%;" rows=1 id=#text > filename </textarea>
<textarea style="width:100%;" rows=30 id=#data > This is a text area </textarea>
Server.start(
Server.http,
[
{page: function() {command <+> content}, title: "test" }
]
)
When I clik on the links "change text1" or "change text2", the text is updated in the two textareas, but as soon as I edit the value of one of these textareas, the update failed when I clik on the links.
Why ?
i think this is because once you have edited a textarea, the browser considers the "value" attribute of the textarea, and not the HTML content inside the textarea.
So in order to work, you should :
function update(txt, _)
{
Dom.set_value(#text, txt)
Dom.set_value(#data, txt)
}