Add new key value pair in Angular Dynamic Form - javascript

I have a requirement in Angular Dynamic Form to add key-value pair on click of add button.Both key and value should be editable
a)- Key either we can select from master list or it can be a free textbox(if value is not available in master list then autocomplete should be replaced by textbox).
b)- Value should be a textbox.
Also, There should be a nearby save button and delete button along with above fields to either submit it or delete it.
As per current implementation in our project,'key' is always hardcoded and 'value' is editable inside form group.
What should be the best approach to add a new key-value pair in dynamic form?
1- Should we need to create a new form group for adding new row?
2- Utilize the current approach and extend the functionality on it in same form group
Any approach/leads will be most welcome.

1 .On button click create a function that create form group and add to form array in your parent FormGroup
For put key values like this
let r=this.fb.group({mvl:"keey",sec:"val"});
Mark your input readonly to make it non edible
foo:FormGroup
constructor(public fb:FormBuilder) {
this.foo=this.fb.group({
string :"",
number:0,
common1:this.common,
common2:this.common,
multi:this.fb.array([])
});
}
add()
{
let r=this.fb.group({mvl:"keey",sec:"val"});
(this.foo.get("multi") as FormArray).push(r);
}
Inside your form put html like this
<div formArrayName="multi">
<div *ngFor="let el of multiForm;let i=index" [formGroupName]="i">
<input type="text" matInput placeholder="mvl{{i}}" formControlName="mvl">
<input type="text" matInput placeholder="sec{{i}}" formControlName="sec">
</div>
<div (click)="add()">add</div>
</div>

Related

How to submit data from input fields generated using ng-repeat and get the value of all the input fields?

I am new to Angular js and I need to create a form where the input fields will be dynamically generated based on a loop and I need to send all the field's data to an API.
This is the string that I get from the backend
"Earth:planet,life,solar,global$##data_col.signal:gateway ox,gw ox,gateway all ox,all sig,,gw signal gain,gateway"
This is my part of the html below where I process the string
<div class="container-fluid synBox">
<span><b>Enter synonyms:</b></span>
<form enctype='application/json'>
<div class="form-group" name="syn" ng-repeat="n in message.expert_advice.split('$##')">
<span class="fonts" style="color:#487baa;"><b>{{n.split(":")[0]}}</b></span>
<input class="form-control" id="expert_advice_input" type="text" ng-model={{n.split(":")[1]}} placeholder="" name={{n.split(":")[0]}} value={{n.split(":")[1]}}>
</div>
<button type="submit" class="btn btn-primary center-block" ng-click="submit_synonyms()">Submit</button>
</form>
</div>
Here is my js for the function in onclick submit_synonyms()
$scope.submit_synonyms = function() {
var variable = document.getElementById('expert_advice_input').value;
console.log(variable)
}
Here is what it looks like in the UI
I was hoping that I would get the value for all input fields but when I click the button I only get the value of the first input field (as seen in the console).
planet,life,solar,global
I also followed other similar questions in stackoverflow like Ng-repeat submit form with generated fields but couldn't figure out how to apply it in my situtation. What am I doing wrong?
Do note that the number of input fields can be dynamic based on the string supplied to me.
ADDITIONAL INFO
Just for the sake of clarity, the reason I am doing the splits on the string is to get the heading and the remaining comma separated strings in the input fields to which a user can add more string and hit the submit button.
write the following in your controller
const param = <input> //"Earth:planet,life,solar,global$##data_col.signal:gateway ox,gw ox,gateway all ox,all sig,,gw signal gain,gateway";
$scope.param = param.split('$##').reduce((acc,val)=> {
const spl = val.split(':');
acc[spl[0]] = spl[1];
return acc;
},{});
and following in your template or html
<ul >
<li data-ng-repeat="(key,value) in param"><label for={{key}}>{{key}}</label><input type='text' value='{{value}}'</li>
</ul>
add styles and optimize code style.

angular2 capture info from dynamically generated inputs - possible?

Working on an update form which I would like to generate and capture inputs for a variable sized array
The current unhappy version only supports the first three statically defined elements in the constituency array. So the inputs look like this...
<input #newConstituency1 class="form-control" value={{legislatorToDisplay?.constituency[0]}}>
<input #newConstituency2 class="form-control" value={{legislatorToDisplay?.constituency[1]}}>
<input #newConstituency3 class="form-control" value={{legislatorToDisplay?.constituency[2]}}>
and the function to update pulls the values of the form using the static octothorpe tags.
updateLegislator(newConstituency1.value, newConstituency2.value, newConstituency3.value)
But this doesn't allow for a variable sized Constituency array.
I am able to use *ngFor directive to dynamically create input fields for a theoretically infinitely sized constituency array:
<div *ngfor constit of legislatorToDisplay?.constituency>
<input value={{constit}}>
</div>
but have not successfully been able to capture that information thereafter. Any kind assistance would be greatly appreciated.
You just have to have a form object in your component that matches the HTML input components that were created.
Template
<div *ngfor constit of legislatorToDisplay?.constituency>
<input value={{constit}} formControlName="{{constit}}">
</div>
Component
/* create an empty form then loop through values and add control
fb is a FormBuilder object. */
let form = this.fb.group({});
for(let const of legislatorToDisplay.constituency) {
form.addControl(new FormControl(const))
}
Use two-way data binding:
<div *ngFor="constit of legislatorToDisplay?.constituency; let i = index">
<input [(ngModel)]="legislatorToDisplay?.constituency[i]">
</div>

How rails do nested form in one form?

The scenario is that, I want to design a Post form which is used to record what fruit I eat in one meal, include picture, content, many kind of fruit.
The model relationship is that,
Post has_many fruits
Fruit belong_to post
I usee Jquery-ui to make autocomplete in order to help user type their fruit. After they type there fruit tag, it will create a tag under the input field.
Like this
However how to I create this in form? I thought about dynamic nested form, but I don't want there're a lots of form, I wish there would be only one input and do the same thing with dynamic nested form.
Here is the github, please let me know if I need to provide more information.
$(document).on('click','#add_fruit',function(e){
e.preventDefault();
addFruitTag();
});
function addFruitTag(){
var content = $('#content').val().trim();
var fruit = $('#fruit').val().trim();
if(content.length <1 || fruit.length < 1){
alert("Please fill content and fruit");
}else{
$('#fruit_tags').append(
$('<input>')
.attr('type','checkbox')
.attr('name','fruits[]')
.attr('value',$('#fruit').val())
.prop('checked','true')
)
.append(
$('<label>')
.text($('#fruit').val())
)
.append($('<br>'));
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="GET">
Content : <input type="text" id="content" name="content"><br/>
Fruit : <input type="text" id="fruit">
<button id="add_fruit">Add Fruit</button><br/>
<div id="fruit_tags">
</div>
<input type="submit" value="Create Post">
</form>
Note: I don't have much idea about auto complete plugin, so I have created the function addFruitTag(), call it where you are calling your function of adding hash tags of fruits.
And when you will submit the form to the server, you can retrieve the added fruits by accessing the fruits[] variable , which will be an array containing the selected fruits tags.

show submit <a href> link onchange and pass the value of the input box changed

I am not a JavaScript person really, I write in ASP and use a SQL database in the backend. But our marketing director requested a change that will use JavaScript.
On our view cart page, we're currently displaying an input box with a modify button to allow customers to change the quantity of the listed item (in that row... there could be multiple products in their cart, each having their own quantity input).
<form method="post" action="updateitem.asp">
<input type="hidden" name="product_id" value="<%= PRODUCT_ID %>">
Quantity: <input type"text" name="quantity">
<input type="image" name="Submit" src="/graphics/modify.gif" align="middle" border="0" alt="Continue">
</form>
What I'd like to make work is something like this. Hrm, assuming I need to do my form/div name differently for each product? I can easily write the product_id into the id tags but then assuming I'd also need to loop through my function for each one. I've gotten this far in writing the replacement code:
Get Dataset from Database (items in cart) and loop through:
<form method="post" action="updateitem.asp" id="updateitems<%= PRODUCT_ID %>">
Quantity: <input type="text" name="qty<%= PRODUCT_ID %>" OnChange="Javascript:UpdateQty()")
<div id="showlink<%= PRODUCT_ID %>">
<br /><span class="BodyTiny">update</span>
</div>
</form>
END LOOP
So if the quantity changes, it displays the word "update" where they can click and it passes whatever quantity that is in the quantity field to the updateitem.asp (in a way I can then update it in the database in ASP/SQL). In the code above, if we could just insert the new # in the a href statement after quantity=, then I could fix it in the updateitems.asp page without a problem.
I'm not sure where to even begin honestly, I have this so far:
LOOP through dataset so each product has its own function
<script Language="JavaScript">
<!--
function UpdateQty(updateitems<%= PRODUCT_ID %>) {
Show div updateitems<%= PRODUCT_ID %>
Replace NEWQUANT within that div with the value in the input field qty<%= PRODUCT_ID %>
}
//-->
</script>
END LOOP
I'm having a few problems...
I am not sure how to write the function UpdateQty. It should A) display the stuff in div id=showlink, and B) add the # from the input named quantity quantity to the href so I can update it in the database on the next page
If they have JavaScript turned off, they should be able to enter a new quantity and just hit enter for it to submit the form. I believe this will work as its a form with 1 text input and 1 hidden one, so just hitting enter in the text input should submit it. But that should still work with whatever JavaScript is added to make the showlink div show if it changes.
Do I need to add a class to my CSS for showlink? If so, what do I need to put in it?
Any help would be greatly appreciated!
Mahalo!
so what you can do for updateQty is have one function that will be correct for all products in a list just by making a function that finds all the necessary elements by relative paths.
//in this function the context is the element, so the
//`this` variable can be used rather than a param
//for the product id
function updateQty() {
//show the update link
var parent = this.parentNode;
//assumes only the update text uses the class bodyTiny, and that there
//is only one element using it. obviously making this invariant true
//would be trivial by adding a different class name
var updateText = parent.getElementsByClassName("bodyTiny")[0];
updateText.style.display = 'block';
var updateLink = updateText.parentNode
, updateHref = updateLink.href;
//next we find the current quantity and replace it with the input
updateHref = updateHref.replace(/qty=(\d*)/, 'qty='+this.value);
//then we set the link element's attribute
updateLink.href = updateHref;
//now when you mouse over the link you should see the url has changed
}
You can also set your form to POST the equivalent data, and then I guess on the server side you will have your OnGetPage and OnPostback both delegate to the same method with the parameters either parsed out of the query string or out of the post data.
You can see it running on jsfiddle. Hopefully this helps!

How to select form input based on label inner HTML?

I have multiple forms that are dynamically created with different input names and id's. The only thing unique they will have is the inner HTML of the label. Is it possible to select the input via the label inner HTML with jQuery? Here is an example of one of my patient date of birth blocks, there are many and all unique except for innerHTML.
<div class="iphorm-element-spacer iphorm-element-spacer-text iphorm_1_8-element-spacer">
<label for="iphorm_081a9e2e6b9c83d70496906bb4671904150cf4b43c0cb1_8">events=Object { mouseover=[1], mouseout=[1]}handle=function()data=Object { InFieldLabels={...}}
Patient DOB
<span class="iphorm-required">*</span>
</label>
<div class="iphorm-input-wrap iphorm-input-wrap-text iphorm_1_8-input-wrap">
<input id="iphorm_081a9e2e6b9c83d70496906bb4671904150cf4b43c0cb1_8" class="iphorm-element-text iphorm_1_8" type="text" value="" name="iphorm_1_8">events=Object { focus=[1], blur=[1], keydown=[1], more...}handle=function()
</div>
<div class="iphorm-errors-wrap iphorm-hidden"> </div>
This is in a Wordpress Plugin and because we are building to allow employees to edit their sites (this is actually a Wordpress Network), we do not want to alter the plugin if possible.
Note that the label "for" and the input "id" share the same dynamic key, so this might be a way to maybe get the id, but wanted to see if there is a shorter way of doing this.
Here I cleaned up what is likely not used...
<div>
<label for="iphorm_081a9e2e6b9c83d70496906bb4671904150cf4b43c0cb1_8">
Patient DOB
<span class="iphorm-required">*</span>
</label>
<div>
<input id="iphorm_081a9e2e6b9c83d70496906bb4671904150cf4b43c0cb1_8">
</div>
You can use the contains selector to select the Patient DOB labels, then find the related input.
$('label:contains("Patient DOB")').parent('div').find('input');
This assumes that the label and input are wrapped in the same div and may not work if more than one pair is in the same div. At least the first part will get you the labels that contain Patient DOB, then you can adjust the later parts to find the correct input element.
For more help on jquery selectors, see the API.
Here is a fiddle demonstrating this.
var getForm = function(labelInnerHtml) {
var $labels = jQuery('label');
$labels.each(function() {
if (jQuery(this).html() == labelInnerHtml) {
var for_id = jQuery(this).attr('for');
return jQuery('#'+for_id);
}
});
return [];
};​​
The class iphorm_1_8 on the input is unique for each form element. So it's simple.
$('.iphorm_1_8');

Categories

Resources