Sharing data between two input fields by ngModel - javascript

I have 2 input fileds lets say input1 and input2. I have event such that everything I type in input1 it shows in input2.
Now the condition is if i manually change or type something in input2 , the event i had created above should not work.
I guess need to use count loop but I am confused.
html code:
<input placeholder="Organization Name" [(ngModel)] = "orgName" (ngModelChange)="setdomain($event)">
<input placeholder="Business + Sub Domain" [(ngModel)] = "subdomain">
fragment of TypeScript file:
subdomain : string;
setdomain(name) {
this.subdomain = name.toLowerCase().replace(/ /g ,'');
}

I guess that the simplest way is creating temporary variable, which will store unique subdomain name and create method, which will be passing to the variable appropriate value. For example:
in *.component.ts :
defaultSubdomain: string;
uniqueSubdomain: string;
setdomain(name) {
let expectedResult = name.toLowerCase().replace(/ /g ,'');
this.defaultSubdomain = expectedResult;
}
setUniqueDomain(name) {
this.uniqueSubdomain = expectedResult;
}
and in *.component.html :
<input type="text" placeholder="Organization Name" [ngModel] = "orgName" (ngModelChange)="setdomain($event)">
<input type="text" placeholder="Business + Sub Domain" [ngModel] = "uniqueSubdomain || defaultSubdomain" (ngModelChange)="setUniqueDomain($event)">
I created Plunker for you. Tell me if that's what you meant.

cant you just the defaut value of input2 to that of input1. I think it should work.
<input placeholder="Organization Name" #input1>
<input value=input1.value placeholder="Business + Sub Domain">

Related

HTML FORM - Change Parts Of Readonly String Field Using onchange()

I want to assign the values - value and value 2 into the DATAID and DEPNUM when clicking the drop-down and using onchange() function in the following HTML FORM
The places that are being assigned are parts of a readonly field which contains string.
My goal is to create a readonly string which will contain the values that I've chosen from the dropdown fields, all combined in 1 string and separated by underscore.
I've been trying to use onChange method "myFunction()"
<input name="_1_1_2_1" tabindex="-1" class="valueEditable" id="myInput" onchange="myFunction()" type="text" size="32" value="...">
which will look like :
function myFunction()
{
var x = document.getElementById("myInput").value;
document.getElementById("demo").innerHTML = x;
}
eventually I run it on the paragraph :
<p id="demo" value="DATAID_DOCTYPE_DEPNUM_NTA">DATAID_DOCTYPE_DEPNUM_NTA</p>
The problem is that the value at is not changing instant as i change value2 or value.
You can bind two event-listener for both two input fields and updated the readonly textfield value by below approach.
$(document).ready(function(){
$('#field1').keyup(function() {
updatedReadonlyFieldVal($(this), 0);
});
$('#field2').keyup(function() {
updatedReadonlyFieldVal($(this), 2);
});
function updatedReadonlyFieldVal(elem, index) {
let val = elem.val();
let destVal = $('#destination').val();
let splittedDestVal = destVal.split('_');
splittedDestVal[index] = val;
$('#destination').val(splittedDestVal.join('_'));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="field1" name="field1">
<input type="text" id="field2" name="field2">
<input value="DATAID_DOCTYPE_DATANUM" readonly id="destination">
Please don't hesitate to let me know if you have any query.

How to concatenate values using Reactive Forms?

I want to concatenate 2 values into 1 label using Reactive Forms.
In this case i'm not using ngModel binding.
<label
id="identificationCode"
name="identificationCode"
formControlName="lblIdCode">______</label>
<input type="text"
id="reference"
name="reference"
formControlName="txtReference"
maxlength="250"
(change)="handleIdCode($event)">
<input type="text"
id="publicacion"
name="publicacion"
formControlName="txtPublicacion"
maxlength="250"
(change)="handleIdCode($event)">
I want to concatenate those 2 input text when user is writing and automatically reflect the value into the label. Is there any way like we do it with model binding without change event??
Use label to display the information. The label is not meant to bind with Reactive Form. If you need concatenate values to pass to API or for any use then try on TS. User cannot change the value of Label so there is no point to bind it, but just display the concatenated value.
Remove formControlName="lblIdCode" from your label and add for attribute.
<label>{{form.get('txtReference').value}} - {{form.get('txtPublicacion').value}}</label>
And concatenate on TS:
const lblIdCode = this.form.get('txtReference').value + this.form.get('txtPublicacion').value
The definition of label:
The HTML element represents a caption for an item in a user interface.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label
Although given answers work fine. There could be another declarative approach which will take advantage of valueChanges observables of the input text. We can combine the input texts' valuechanges observables and map to the desired output i.e. concatenate the Reference + Publicacion like this:
Component.ts:
export class FormreactiveComponent implements OnInit {
lblIdCode$: Observable<string>;
form = new FormGroup({
txtReference: new FormControl(''),
txtPublicacion: new FormControl('')
});
constructor() { }
ngOnInit() {
const refCtrl = this.form.get('txtReference');
const pubCtrl = this.form.get('txtPublicacion');
this.lblIdCode$ = combineLatest(refCtrl.valueChanges.pipe(startWith(refCtrl.value)),
pubCtrl.valueChanges.pipe(startWith(pubCtrl.value)))
.pipe(map(([firstName, lastName]) => {
return `${firstName} ${lastName}`;
}));
}
}
Template:
<form name="form" [formGroup]="form">
<div class="form-group">
<label for="txtReference">Reference</label>
<input type="text" class="form-control" formControlName="txtReference"/>
</div>
<div class="form-group">
<label for="txtPublicacion">Publicacion</label>
<input type="text" class="form-control" formControlName="txtPublicacion"/>
</div>
<div class="form-group">
<label for="lblIdCode">{{lblIdCode$ | async}}</label>
</div>
</form>
Working example
One approach is that you can use reference variables to refer to controls within the template. Like so
<label
id="identificationCode"
name="identificationCode">{{reference.value + " - " + publicacion.value}}</label>
<input type="text"
id="reference"
name="reference"
formControlName="txtReference"
maxlength="250"
#reference>
<input type="text"
id="publicacion"
name="publicacion"
formControlName="txtPublicacion"
maxlength="250"
#publicacion>
The important parts are the #reference and #publicacion on each of the inputs. This links the controls to the variables.
You can then use these variables within an Angular interpolation block like {{reference.value + " - " + publicacion.value}}. You can combine the values however you want inside this block.
Try using the form values, just like you'd use in the .ts file.
<label
id="identificationCode"
name="identificationCode"
formControlName="lblIdCode">
{{form.value.reference + ' ' + form.value.publicacion}}
</label>
you can create a get property base of these values like in
componenpe ts
get referencePublicacionValues() : string {
return `${this.form.get(txtReference).value} ${this.form.get('txtPublicacion').value}`
}
template
<label
id="identificationCode"
name="identificationCode">
{{referencePublicacionValues}}
</label>
now you have the value in reference Publicacion Values property any change the value will reflect to the ui
you can't use formControlName directive on labels if you want to set
the formcontrol lblIdCode you can use form valueChanges
this.form.valueChanges.subscribe( () => {
this.form.get('lblIdCode').setValue(this.referencePublicacionValues,{emitEvent: false})
})
demo 🔥🔥

How to have unique suggestion on input in SAPUI5

I am trying to get suggestions from input box, but if model has multiple values in wheelName like "wheel1", "wheel1", "wheel2", and with this, when I enter "wheel1" in inputbox, i get 2 suggestions as wheel1, wheel1, but i want unique suggestion i.e. wheel1 to be shown only once.
Input declaration looks like below:-
<Input
id="wheelInput"
type="Text"
placeholder="Enter Wheel..."
showSuggestion="true"
maxLength="40"
startSuggestion="3"
suggestionItems="{wheel>/results}" >
<suggestionItems>
<core:Item text="{wheel>wheelName}"/>
</suggestionItems>
</Input>
Assuming your results list differs with every character you type into your input, you can attach a function to the liveChange of the Input field.
You can then put your custom logic (e.g. no double names) into a separate model property. I haven't tested the code but Ii should work (provided I didn't make a typo).
View:
<Input
id="wheelInput"
type="Text"
placeholder="Enter Wheel..."
showSuggestion="true"
maxLength="40"
liveChange="filterWheelList"
startSuggestion="3"
suggestionItems="{wheel>/filteredWheelList}" >
<suggestionItems>
<core:Item text="{wheel>wheelName}"/>
</suggestionItems>
</Input>
Controller:
filterWheelList: function(){
var wheelModel = sap.ui.getCore().getModel("wheelModel");
var wheelList = wheelModel.getProperty("/results");
var uniqueNames = [];
var filteredWheelList = wheelList.filter(function(wheel){
if (uniqueNames.indexOf(wheel.wheelName) === -1){
uniqueNames.push(wheel.wheelName);
return true;
} else {
return false;
}
});
wheelModel.setProperty("/filteredWheelList", filteredWheelList);
}

Initialize input text field value using $rootScope in Angular Js

I have defined $rootScope variable by using following code:
$rootScope.userDetails = function () {
$http.post($account + '/feedbackdiv')
.success(function (res) {
$rootScope.userData = res.userData;
});
};
$rootScope.userDetails();
Now, userData is accessible from everywhere. Now I tried to assign the userData.FirstName value to text field like this:
<input type="text" class="form-control museo_sans300" id="fName"
placeholder="First Name" name="fName" minlength="1" ng-model="fName"
ng-init="fName = userData.FirstName" required="required">
But this didn't initial value in the text field. I also checked that when I give static value to ng-init it works correctly, like, ng-init ="fName = 'test'" Furthermore I also verified that I am getting value of userData.FirstName. Please provide a solution to initialize this input text field.
There is no reference between fName and userData.FirstName after initial assignment fName = userData.FirstName. Also ngInit is not going to be run again on every digest loop. So when later userData.FirstName is populated primitive fName is not going to be updated. This is expected javacript behavior not related to Angular.
So you either use userData.FirstName directly as model:
<input type="text" class="form-control museo_sans300"
id="fName" placeholder="First Name" name="fName" minlength="1"
ng-model="userData.FirstName"
required="required">
Or you will need to manually set fName in controller once userData is loaded.

Reading form field data in Javascript

I just can't get this to work.
HTML:
<form action="index.php?page=n0402" method="post" Name="AddPolish" >
<div id="frmBrandInput">
<label for="frmBrand">Brand name:</label>
<input type="text" name="frmBrand" size="50" onkeypress="BrandCheck();" maxlength="100" id="frmBrand" value="Enter existing or new brand" />
<span id="frmBrand_Status"></span>
</div>
</form>
Javascript:
function BrandCheck()
{
var jsBrandName = document.forms["AddPolish"]["frmBrand"].value;
alert(jsBrandName);
}
Why can't I get the value of frmBrand into jsBrandName? If I use Firebug to debug, I get the following in my Watch list:
Watch Expression:
document.forms["AddPolish"]["frmBrand"];
Result:
NodeList[input#frmBrand property value = "G" attribute value = "Enter existing or new brand", input#frmBrand attribute value = ""]
I can see the value "G" which is what I entered in the input field. What am I doing wrong in passing it into the jsBrandName?
The output you got implies that there are two inputs with name="frmBrand" in the form. You need to index them, e.g.
var jsBrandName = document.forms["AddPolish"]["frmBrand"][0].value;
to get the value of the first one.

Categories