how to set value in input field using angular js.? - javascript

I am making a view from json. I am able to that when I take json in a variable. But same thing when i read from file my view is not display. when comment the code which is working when I take json string in a variable.
Second issue
<div ng-switch-when="text" class="form-group">
<input type="text" value='login name' ng-model="outputs[input.name]"/>
<p ng-show="myfrm.input.$error.email && !myfrm.input.$pristine">Please enter a valid textl</p>
<p ng-show="myfrm.input.$error.required && !myfrm.input.$pristine">Please enter the text</p>
</div>
When I am using static value of input field like that(value='login name').it doesn't display that field value in input field.actually there is parameter value in my json I want to show value in input field (it there is any value it should display with filled value).
I take value like that
"value":value.value,
plunker: http://plnkr.co/edit/f3ZNtPbKeFkXnOOc3PNM?p=preview
actually why i am ready from file because there mat 1000 json object .i need to make 1000 form using one method
can I used this function
function changeData(data) {
var map = { NUMBER: "number", TEXT: "text", SWITCH: "select" };
// data is an object - use for .. in to enumerate
for (var key in data.input) {
var e = data.input[key]; // alias for efficient structure dereferencing
e.label = e.displayName;
e.title = e.displayDetail;
e.type = map[e.inputType];
delete e.displayName;
delete e.displayDetail;
delete e.inputType;
}
};
or I used this plugin
https://github.com/danhunsaker/angular-dynamic-forms

Related

How to implement ControlValueAccessor in Angular in a interdepend form

I have two dropdown fields that are separate components using ControlValueAccess. I want to change the data in the second field based on the selection of the first. For example, if field type has a value of honda then I'd like to change the data for the second field model to include an array of honda models. If the type has a selected field of toyota, I'd like to change the data in the model dropdown to include toyota models.
Here is the Stackblitz
https://stackblitz.com/edit/angular-ivy-7ry6vf?file=src/app/app.component.html
I've tried setting this.value to the appropriate array according to the value passed in, but I don't think this is the correct approach.
model.component.ts
writeValue(value: any): void {
if (value === 'honda') {
this.value = this.honda_models;
} else {
this.value = this.toyota_models;
}
// this.value = value;
}
Also, I'm having a hard time trying to get the value out of the app-type component
app.component.html
<form [formGroup]="form">
<app-type
formControlName="type"
(onChange)="onChange($event.target.value)"
></app-type>
<app-model formControlName="model"></app-model>
</form>

How do I pass a dataset attribute dynamically using user input?

I have a text input box where a user inputs what data-* they want to look for in the DOM. I get this user input on a button click then do a little bit of parsing. How would I get the value of the entered text to be the final part of the HTMLElement.dataset selector?
//HTML for text input
<div class="form-group">
<label for="specificSelector">Specific Selector</label>
<input type="text" class="form-control" id="specificSelector" placeholder="Enter the specific selector here">
</div>
<p id="a"></p>
//JavaScript
var specificSelector = document.getElementById("specificSelector").value;
var a = document.getElementById("a"); // Test element
var parsedSelector = specificSelector.match(/data-(.*)/)[1];
console.log("Parsed selector: ", parsedSelector);
//I need to pass the value of the parsedSelector to the below line
var aData = a.dataset.parsedSelector;
console.log("aData: ", aData);
I have read this from MDN Developers but can't figure it out. It looks like you have to pass the data attribute in camel case but might not be able to do it via a variable?
Thanks in advance.
When you need to access an object property via a variable, you need to use array-bracket syntax.
In the example below, type "data-test" into the text box and then hit TAB.
// Get a reference to the input
var specificSelector = document.getElementById("specificSelector");
var a = document.getElementById("a"); // Test element
// Set up an event handler for when the data is changed and the
// input loses focus
specificSelector.addEventListener("change", function(){
// Extract the custom name portion of the data- attribute
var parsedSelector = specificSelector.value.match(/data-(.*)/)[1];
console.log("Parsed selector: ", parsedSelector);
// Pass the string (stored in the variable) into the dataset object
// of another element to look up the object key.
var aData = a.dataset[parsedSelector];
console.log("aData: ", aData);
});
<div class="form-group">
<label for="specificSelector">Specific Selector</label>
<input type="text" class="form-control" id="specificSelector" placeholder="Enter the specific selector here">
</div>
<div id="a" data-test="test2"></div>

Using JSON to permeate hidden fields

Using Laravel 5.2.* and plain JavaScript.
TL;DR
I need help in accessing JSON parameters to fill in the value attribute in some hidden fields
AND a way to take the "usefulInformation" value from the JSON and permeate a modal to provide users with information.
Not really interested in jQuery packages, because the project is already filled with over 20 packages.
I'm fairly new to both Laravel and JSON usage, so I've been running into a problem.
I have a page with a form that I have several parameters to fill out, but the most important ones are the hidden fields I set up to automatically fill up, because those are parameters that the user is, in a way, unaware of.
When the user submits the form, the parameters are inserted in the table "jobsCreated" that I have in my DB, the table is basically a way to keep track of every single little thing that the enterprise is doing (buying, selling, asking for new equipment, hiring, creating accounts to enter the system, etc.). The table is a mess in a way (the table has a bit over 20 columns and 11 of those are foreign keys)and it uses a composite key to generate the "createdJobID".
Most of the foreign keys in this table comes from another table called "jobsList". I've created a JSON file that has all the parameters and elements of this table. Like this:
jobs.json
{
"enterpriseID":2,
"sectionID":1,
"jobID":7,
"jobDescription":"Purchase - New Mouse for Deskjob",
"usefulInformation":"Please specify the value of the equipment",
"urgencyLevel":"normal",
"atendantID":0,
"isPublic":1,
"searchEqualFiles":0,
"formType":21
},
{
"enterpriseID":2,
"sectionID":1,
"jobID":8,
"jobDescription":"Purchase - New Laptop/Desktop to Deskjob",
"usefulInformation":"Inform the type of equipment and value",
"urgencyLevel":"normal",
"atendantID":0,
"isPublic":1,
"searchEqualFiles":0,
"formType":21
},
[ it goes on for another 260++ entries, following this model]
Another thing the system asks in the form, is an autocomplete-ish field that lists all of the jobs in the JSON. I've come up with a JavaScript code to permeate a datalist with several option fields, like this:
completeForm.js
// hidden inputs
var sectionId = document.getElementById('sectionId');
var jobId = document.getElementById('jobId');
var jobTypeId = document.getElementById('typeId');
var categoryId = document.getElementById('categoryId');
var selectionOption = document.getElementsByName('selectJob');
// input autocomplete e dataList
var input = document.getElementById('selectionAutocomplete');
var dataList = document.getElementById('jobsList');
var request = new XMLHttpRequest();
request.onreadystatechange = function(response)
{
if(request.readyState === 4)
{
if(request.status === 200)
{
// important bit, bolding it
var jsonOptions = JSON.parse(request.responseText);
for(var i = 0; i < jsonOptions.length; i++)
{
var option = document.createElement('option');
option.value = jsonOptions[i].jobDescription;
dataList.appendChild(option);
}
input.placeholder = "Type the name of a job";
}
else
{
input.placeholder = "No jobs found";
}
}
};
input.placeholder = "Loading jobs";
request.open('GET', '{{{ url('storage/app/jobs.json') }}}', true);
request.send();
Which works, the JSON is being parsed. If I do console.log(jsonOptions[i].jobDescription), for example, the right parameters are returned.
For my auto-complete field and hidden fields, I used the datalist element with the option element created in JavaScript.
// opening form, label and stuff
<input type="text" name="selectionAutocomplete" id="selectionAutocomplete" list="jobsList">
<datalist name="jobsList">
// options appended here
// elements look like this
// <option value="Purchase - New Mouse for Deskjob"></option>
</datalist>
<input type="hidden" name="sectionId" id="sectionId">
<input type="hidden" name="jobId" id="jobId">
<input type="hidden" name="typeId" id="typeId">
<input type="hidden" name="categoryId" id="categoryId">
In the hidden fields, I want to set up the value attribute to the same one that exists (if it exists) in the JSON.
So, for example, if I check the option "Purchase - New Mouse for Deskjob", I want to access the JSON position for this particular choice and permeate the value attribute in the hidden fields AND trigger a modal containing the "usefulInformation" string.
Any type of help is welcome. Thank you in advance.

Store checkbox values in JSON with true or false

I'm getting the values of checkboxes when a user submits the form and storing their values as an array, so the form looks like this:
<!-- gym_create.html - I have removed the other inputs in the form for brevity -->
<form class="create-gym" role="form">
<input type="checkbox" name="gymTags" value="Bodybuilding" id="tagBodybuilding" class="tag-checkbox"/>
<input type="checkbox" name="gymTags" value="Powerlifting" id="tagPowerlifting" class="tag-checkbox"/>
<button type="submit" class="btn create-form-submit">Save gym</button>
</form>
And then I collect that information in my JS file associated with the form:
// gym_create.js - I have removed the other values I collect apart from the gymName value for brevity
Template.gymCreate.events({
"submit .create-gym": function (e) {
e.preventDefault();
var tagOutput = JSON.stringify({
tagOutput: $(':checkbox[name=gymTags]:checked').map(function() {
return $(this).val();
}).get()
});
// Collect values from form when submitted
var gymDetails = {
gymName: $(e.target).find('[name=gymName]').val(),
gymTags: tagOutput,
}
// Call method here
}
});
I can then output these in my template using {{gymDetails.gymTags}} but this produces the following in the browser:
"{"TAGOUTPUT":["BODYBUILDING","POWERLIFTING"]}"
What I want is a way to store the values as JSON so they are like so:
{"gymTags": {
"bodybuilding": "true",
"powerlifting": "false"
}}
So that I can output each tag on it's own and also access only tags which are 'true' (that were checked) later on.
Does anyone know how I go about this? I wrangled with it all yesterday and the best I could come up with was the =JSON.stringify
I don't want to pass the entire form to JSON, just the checkboxes, is JSON.stringify what I want to be doing or am I barking up the wrong tree.
I think this should do it. You were just returning the just the value of the inputs. You want to return a json object, where the value is the "index" and the checked property is the "value" of the object.
var tagOutput = JSON.stringify({
tagOutput: $(':checkbox[name=gymTags]').map(function() {
var op = {};
op[this.value] = this.checked;
return op;
}).get()
});
Edit: as noted by Da Rod, to use both checked and unchecked checkboxes, you must remove the ":checked" selector.
Since your selector is only grabbing items that are checked, they are all "true". That being the case, you need to change the way you are using "map" to add properties to tagOutput.
var tagOutput = {}
$(':checkbox[name=gymTags]').map(function() {
tagOutput[this.value] = this.checked;
})
});

MVC4: Show validation error on the form or summary instead of an input?

I'm trying to leverage some form validation to do something it really wasn't designed to do. I have a table in my form and each row has a checkbox. I want to ensure that at least one of a specific type of checkbox is selected, if not I want to show a validation error. I am doing something similar with a text box with logic that looks like this:
function ValidateName() {
var $nameTextbox = $("#Name");
var $originalName = $("#OriginalName");
var nameText = $nameTextbox.val().toLowerCase();
var originalNameText = $originalName.val().toLowerCase();
//check to see if original name and group name match
if (nameText != originalNameText) {
//This isn't the same name we started with
if (uniqueNames.indexOf(nameText) > -1) {
//name isn't unique, throw validation error
var currentForm = $nameTextbox.closest("form");
//trigger validation
var errorArray = {};
errorArray["Name"] = 'Name must be unique';
currentForm.validate().showErrors(errorArray);
}
}
}
I've written something similar for the table and it works as long as I point the errorArray's index to the id of an input. However, I want to display the error somewhere more generic like the validation summary at the top of the form. How do I set up the error array to show on the form or the validation summary instead of a specific input? Is that even possible?
One way you could do this is you set a hidden input that is false when none are check and true if 1 or more are checked. You then listen to all the checkboxes by giving them all a class. I have an example shown below
http://jsfiddle.net/95acw2m9/
Html
<input type="hidden" id="IsCheckValue" name="IsCheckedValue" value="false"/>
<input type="checkbox" class="someCheckbox"/>
<input type="checkbox" class="someCheckbox"/>
<input type="checkbox" class="someCheckbox"/>
Jquery
$(document).ready(function(){
$(".someCheckbox").change(function(){
if($(".someCheckbox:checked ").length > 0){
$("#IsCheckValue").val("True")
}else{
$("#IsCheckValue").val("False")
}
})
})
Then pass that bool value in your model. In your controller method you can check the value of the bool. If the bool is false set the model to false like this
ModelState.AddModelError("Checkbox", "Must select one checkbox");
You can use the #Html.ValidationSummary() to display the error in your view.

Categories