Using JSON to permeate hidden fields - javascript

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.

Related

How to serialize just one value of input via jQuery?

I started to do dropdown list instead select bcz it is not possible to stylize but I did not think to future and now I found that if I want to save data from form to db I need to get ids via $_POST instead of names.
For ex. I have dropdown list with status of product:
New
Old
Handmade
If I want to save chosen sattus for chosen product it is better for me to get ID of status option. Bcz my table is like this:
item_id | option_value
1 | 1
If I send name as "old" via $_POST, I need to get its ID from another table before insert it.
I created dropdown list like this:
/* SELECT REPLACED BY DIV JS */
var select = $('.add-item__select').hide(); // Hide original select options
// Replace each select by div
select.each(function() {
var selectVal = $(this).find('.add-item__select-main').text(),
name = $(this).attr('name');
newDropdownDiv = $('<input class="add-item__input-select" name="' + name + '" placeholder="' + selectVal + '" readonly required><i class="arrow down"></i></input>')
.insertAfter($(this))
.css({paddingLeft: '0.3em', cursor: 'pointer'});
});
Each SELECT has addaed INPUT after it.
If I want to show shosen vale from dropdown list I need to show it in this way:
$('.add-item__input-select').val("text copied from list");
After this if I add ID of option to input in this way:
$('.add-item__input-select').attr("value", optionID);
Then If I want to serialize all fields values from form and this is point,
$('.add-item__form').serializeArray()
I get two results for status:
name: "status", value: "text copied from list"
and
name: "status", value: optionID
But I need just optionID.
I have everything optimized for this structure, so I would like to ask you if there is some easy way how to fix it or I need to modify structure.
I am thinking to remove INPUT and just change SELECT opacity to 0 instead of display none and use SELECT for form data serialize. But then I will need to replace all INPUTs by some DIV which will hold text of chosen option and also change everything else connected with it. For ex, if user clicked on INPUT the label was showed above it.
Thanks for advices
I found one solution but I have problem that it is working just if user will not refresh page. In DOM is everything the same after refresh but serializeArray() get just input text value and not value="ID" after page refresh.
I just remove these values which I do not want from FormData.
// Send formData to upload.php
$('.add-item__form').on('submit', function() {
event.preventDefault();
event.stopPropagation();
if ( checkFieldsIfNotEmpty() == true ) {
var formDataFields = $('.add-item__form').serializeArray(), // Get all data from form except of photos
count = Object.keys(data).length; // count fields of object
// Fill formData object by data from form
$.each(formDataFields, function(index, value) {
if ( value.name === 'category' && !$.isNumeric(value.value) || value.name === 'subcategory' && !$.isNumeric(value.value) ) {
// do nothing
} else if ( (value.name.indexOf('filter') >= 0) && !$.isNumeric(value.value) ) {
// do nothing
}
else {
formData.append(value.name, value.value); // add name and value to POST data
}
});
// foreach - fill formData with photos from form
$.each(data, function(index, value) {
formData.append('files[]', value);
});
uploadData(formData); // send data via ajax to upload.php
}
});
Can you advice me what can be problem?

Input text in a form and append a paired value to a search URL -

I am a very rudimentary user of JavaScript and jQuery.
I have a form that builds a simple search URL based on user input, and uses the GET method to send the user to a set of filtered search results on a site at another domain. There is a base URL, and the form inputs are appended to it, as in
http://www.othersite.com/search.asp?q=input1&id=input2
My problem is that the other site uses an item ID in the search URL that is different than the item name. The users are going to know the item name, but the item ID is just a sequential key value.
I want to have the user enter the item name (along with some other input terms), and have the corresponding key value appended to the URL when it is submitted.
I have all the pairs of item names and IDs in a JSON file that I can format as needed. There are about 15,000 pairs.
So for example, the item named abc123 has an ID of 54321.
I want the user to enter abc123 in a text field, and to have itemID=54321 appended to the base search URL.
I do not find any close examples I can borrow from.
Sorry if this is too long of an answer. The below method uses the datalist element along with an input list element that gets populated with an xhr request. Also, don't forget that Safari doesn't do datalists :(... User beware this hasn't been tested.
<form id='search-form' method='GET'>
<input list='search-data'
name='item-title'
id='search-input'
value=''
placeholder='Search Titles'>
<datalist id='search-data'>
</datalist>
<input type='submit' name='submit-search' />
</form>
// Encapsulate a function
// Load JSON using XHR and than append
// an options node element to the list input.
(function searchFormScoped(){
var _form = document.getElementById("search-form"),
_listNode = document.getElementById("search-data");
var xhr = new XMLHttpRequest();
xhr.open("GET", "/the_request_url.json");
xhr.responseType = "json";
xhr.onload = function loadHtmlFormList(e) {
var _data = this.response,
_datakeys = Object.keys(_data);
// loop through key id's and populate the option with
// the correct values and data attributes
for(var c=0; c < _datakeys.length; c++) {
var _opt = document.createElement("options");
// store the key values from the json as the options value
_opt.value = _data[_datakeys[c]];
// I use the data-id attribute to store key values of the json
_opt.setAttribute('data-id', _datakeys[c]);
}
// Set an event to be executed when the list value changes
_listNode.addEventListener("change", function searchOptionChanged(e) {
var _infoNode = _listNode.querySelector('option[value="' + e.target.value + '"]');
// Set the data-item attribute of the target event element of the
// string you need for your search string url to use for when the form is
// submitted, or from here you could set the action attribute, I believe.
e.target.setAttribute('data-item', 'itemID=' +_infoNode.getAttribute('data-id'));
});
}
xhr.send();
})();
So look up the id from the object and set a hidden field.
var items = {
"abc123" : 123456,
"foo": 2345
}
document.getElementById("item").addEventListener("change", function () {
var val = this.value;
var id = items[val];
if (!id) {
alert("unknown product");
}
document.getElementById("itemID").value = id ? id : '';
})
<form method="GET">
<input type="hidden" name="itemID" id="itemID" />
<label for="item">Item: <label><input type="text" id="item" />
<button>Submit</button>
</form>

How can I capture checkboxes that I'm creating programmatically?

In my code below, I'm pulling in data from SharePoint (basically an excel spreadsheet) and displaying on my page. Checkboxes are pushed to my page using .innerHTML and are given an ID programmatically.
My question: How can I determine whether those checkboxes are checked (being that they could be different each time my app loads) ?
(Once I know what is checked, I'll display more metadata on the next page based on the checks - that part I have figured out)
$.ajax({
url: "myWebsite",
type: "GET",
headers: { "ACCEPT": "application/json;odata=verbose" },
success: function(data){
$.each(data.d.results, function(index) {
var $this = $(this);
var courseName = $this.attr('Title');
var courseNumber = $this.attr('Course_x0020_Number');
var courseUrl = $this.attr('URL');
var trainingGroup = $this.attr('Training_x0020_Group');
var recurrence = $this.attr('Recurrence');
if (trainingGroup == 'Group1') {
if (recurrence == "Don't Specify") {recurrence = '';
} else recurrence = " ("+recurrence+")";
document.getElementById('officeListSpan').innerHTML += '<ul class="courseLists"><li><input type="checkbox" id="'+courseName.replace(/\s+/g, '')+'"/>'+courseName+recurrence+'</li></ul>';
}
if (trainingGroup == 'Group2') {
if (recurrence == "Don't Specify") {recurrence = '';
} else recurrence = " ("+recurrence+")";
document.getElementById('labListSpan').innerHTML += '<ul class="courseLists"><li><input type="checkbox" id="'+courseName.replace(/\s+/g, '')+'"/>'+courseName+recurrence+'</li></ul>';
}
});
},
error: function(){
alert("Failed to query SharePoint list data. Please refresh (F5).");
}
});
You will need a way to know how many checkboxes has been created. When creating the checkboxes, them id must have a generic name and a number, for example id="checkbox0", id="checkbox1 and so on, then write the ammount of checkboxes in some part of the html code and put it some hidden tag. Then when reading the checkboxes data read the ammount of checkboxes and do a for
function getCheckboxes(){
var ammount = parseInt(document.getElementById("checkBoxesAmmount"));
var checkbox;
for(var i = 0; i<ammount; i++){
checkbox = document.getElementById("checkbox"+i);
//do staff
}
return;
I hope this works for you c:
This bit of jQuery returns all the checked input boxes that are in a ul with the class courseList:
jQuery('ul.courseList input:checked')
If your question is asked because the course name might change (your checkbox IDs are based on the course name), I suggest switching to the course number instead (or an appropriate mix of the two).
If you want to know if your dynamically created checkboxes were checked and want to do this via Javascript before the form is submitted, then add a class to your checkboxes (say dynamicCourse) and look for get the checked checkboxes via jQuery('input.dynamicCourse:checked').
Also, your checkboxes in your example don't have a value attribute set. If you're submitting it to a backend, you'll probably want it to have some value (course number would be my suggestion from the looks of it).

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.

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

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

Categories