How to serialize just one value of input via jQuery? - javascript

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?

Related

How to store object with files to localstorage

I am trying to find a way how to store form data in local storage to show them even if user refresh page. For whole form it is no problem, but I have object with image files as part of form and I am not able to find the way how to store it.
My data object is for ex. like this:
{file_9wyh8: File, file_cwjg0: File}
My output after get data from localstorage is without files:
{file_9wyh8: {…}, file_cwjg0: {…}}
I need to store data object bcz, there are files ordered as user see them on page. Due to this it is not possible to use directly filereader.
And this is my code:
// The unload event is sent to the window element when the user navigates away from the page for ex. page refresh
$(window).on('unload', function() {
// Save values of form fields to local storage
$(':file, :checkbox, select, textarea, input').each(function() {
// Due to JS added input instead of select, need to get value from input + add to storage just checked items
if ( !$(this).hasClass('add-item__select') && !$(this).is(':checkbox') && !$(this).is(':file') ) {
// Save value of field to local storage
localStorage.setItem($(this).attr('name'), $(this).val());
} else if ( $(this).is(':checked') && !$(this).is(':file') ) {
// Save just name of checkbox which is checked
localStorage.setItem($(this).attr('name'), $(this).val());
} else if ( $(this).is(':file') ) {
dataToString = JSON.stringify(data);
localStorage.setItem('file', dataToString);
}
})
});
// Get values form local storage if page is refreshed
$(window).on('load', function() {
// Save values of form fields to local storage
$(':file, :checkbox, select, textarea, input').each(function() {
// If input has this class then do not save value
if ( !$(this).hasClass('add-item__select') && ( !$(this).is(':checkbox' ) && !$(this).is(':file') ) ) {
// Get value of field
fieldValue = localStorage.getItem($(this).attr('name'));
// Show value of field if fieldValue is not empty
if (fieldValue !== 'null') $(this).val(fieldValue);
$(this).addClass('black-text');
// Done action just for checkbox
} else if ( $(this).is(':checkbox') && !$(this).is(':file') ) {
// Get value of field
fieldValue = localStorage.getItem($(this).attr('name'));
// If chekcbox name is same as saved in local storage then set as checked
if ( fieldValue === $(this).val() ) $(this).prop('checked', true);
// Remove checkbox value in localstorage each time - bcz of change checked checkboxes
localStorage.removeItem(fieldValue);
} else if ( $(this).is(':file') ) {
// Get whole object data from localstorage
var dataStringFromLocalStorage = localStorage.getItem('file');
var dataFromLocalStorage = JSON.parse(dataStringFromLocalStorage);
console.log(dataFromLocalStorage);
$.each(dataFromLocalStorage, function(index, value) {
/*
// create temp url to img object for creating thumbnail and append img with temp src to thumbnail__wraper div
$('.thumbnail__wrapper').append('<div class="thumbnail" id="file_'+ mark +'"><img class="imageThumb" src="' + url + '" title="' + upload.name + '"/><br/><a class="remove">Zmazať</a></div>');
$('.add-item__add-photo-btn-area').find('p').hide();
// set up first image as main image - marked by label
var firstImg = $('.thumbnail__wrapper').children().first();
$('<p class="main-img">Hlavná fotka</p>').appendTo(firstImg);
// Change photo number status
$('#photo-num').text('Fotky ' + count + '/50');
*/
})
}
})
I tried also alternatives found in this question, but it did not help me.
How can I serialize an input File object to JSON?

Saving additional field from dropdown

I m having list of relations, when I select Other, new fields shows AddOther, and when I enter Test into new field, in database i get stored Other, because it takes from the f.select. What should i do to save into database from new field when i choose Other from the list.
= f.select(:relationship, ['Father', 'Mother', "Sibling", "Children", "Friend", "Spouse", "Other"], {}, { :class => 'form-select RelationshipSelect' })
fieldset class="form-group" style="display:none"
input#AddOther.mt-4.form-control[type="text" style="display:none" placeholder="Enter other relationship"]
$('.RelationshipSelect').change(function() {
var v;
v = $(this).val();
if (v == 'Other') {
$('#AddOther').slideDown();
} else {
$('#AddOther').slideUp();
}
});
I tried to add AddOther to f.select but no progress.
Cant figure it out how to save AddOther into list to be able to save it as Father, Mother....
This feels risky, because the relationship will only be valid/available for one use. You will be prone to pick up lots of "dirty" data.
That said, you could add jquery to monitor the 'change' event of AddOther, which would retrieve the value, add a new option to the select, set the value of the select to that value.
$('#AddOther').on('change', function(){
relationship = $(this).val();
$('.RelationshipSelect').append("<option value=\"" + relationship + "\">" + relationship + "</option>").val(relationship);
$(this).slideUp();
});
The best way was to create another column and save data from additional field in that column, and displayed it like that.

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).

Disable Drop-down list item without removing the value from FormCollection

I have a number of the following drop-down lists within this page, each with a list of selectable users. When a user is selected in one list, I don't want them to be selected in any further lists. For this reason I have written a script to disable them.
When the form is submitted, the username of each user selected in a drop-down list should be appended to the Uservalue in the Form Collection.
This works correctly without the disabling of names but when I add seat-selectinto the class description, the names are always returned in the FormCollection as empty strings.
Do you know why this is or what I can do to keep the names populating correctly in the FormCollection?
Drop-Down List:
#Html.DropDownListFor(m => m.User, Model.UserList, "Select User", new { #class = "form-control seat-select", #id = "uniqueID", #onchange = "cleanUsers(this);" })
Java Script:
function cleanUsers(ddl) {
var val = ddl.options[ddl.selectedIndex].value;
var vOldVal = $("#" + ddl.id).attr("data-selected");
$("#" + ddl.id).attr("data-selected", val);
//Remove selected
if (val != 0) { $(".seat-select option[value='" + val + "']").attr("disabled", true); }
if (vOldVal != undefined) { $(".seat-select option[value='" + vOldVal + "']").attr("disabled", false); }
}
UPDATE 06/06/2016:
Apologies to bring back an old post. I have tried the advice listed below and this works to return one of the selected values. Unfortunately, In my solution I have a number of identical drop-down lists and I need to keep track of exactly which result is from which drop-down.
I have posted my new code below. The string is overwritten when each of the drop-down menus is changed so does not currently work for me.
New JavaScript:
function cleanRowers(ddl) {
var val = ddl.options[ddl.selectedIndex].value;
var vOldVal = $("#" + ddl.id).attr("data-selected");
$("#" + ddl.id).attr("data-selected", val);
//Remove selected
if (val != 0) {
$("#SelectedUserText").val(val);
$(".seat-select option[value='" + val + "']").attr("disabled", true);
}
if (vOldVal != undefined) { $(".seat-select option[value='" + vOldVal + "']").attr("disabled", false); }
}
The Hidden value being updated:
#Html.HiddenFor(m => m.SelectedUserText)
I am trying to make the code as re-usable as possible so dont really want a different identifier for each of the drop-downs but it is important that I keep track of which drop-down the information is coming from.
Is there a way in which this can be done?
Disabled attribute do not put value in form submission thats why you are receiving empty string .
Here is a trick you can apply :
Put the selected value in a hidden input field onchnage function then read the hidden value on form submission instead of reading vslue of disabled dropdown.
Hope that helps .

Organizing values of child elements for processing of a draggable form

in my form, the user can click a button to create input fields. Inside each of the created input fields, they can click the "add media links" button to create another input field underneath. They can add as many media links as they please or none at all. The first set of input fields are also sortable. I have the user interface working, I'm just wondering how to go about processing it.
right now, I am basically grabbing all of the values entered from the first set of input fields (aka "thestepvalues" in the code) and then grabbing all of the values entered from the second set of input values (aka "links" in the code) and then URL enconding it and serializing it to send to the my process.php file. The code is below:
$("#new_post").submit(function(e){
e.preventDefault();
//enter each of the values for 'the step' input field into an array
var thestepvalues = $("input[name='thestep\\[\\]']")
.map(function(){return $(this).val();}).get();
//enter each of the values for each 'links' input field into an array
var linkvalues = $("input[name='link\\[\\]']")
.map(function(){return $(this).val();}).get();
//this will basically convert everything entered into the steps as well as the links fields
//into URL appropriate strings to pass on to the process.php file
var i, string="";
for(i=0;i<thestepvalues.length; i++){
string += "thesteps[]=" + encodeURI(thestepvalues[i]) + "&";
}
for(i=0;i<linkvalues.length; i++){
string += "links[]=" + encodeURI(linkvalues[i]) + "&";
}
//send the data from the string (both kinds of input fields) as well as any
//other input fields (that aren't dynamic) from the form
$.post("process.php", string + $("#new_post").serialize(),
function(data){
if(data.email_check == 'invalid'){
$("#message_post").html("<div class='errorMessage'>Sorry " + data.name + ", " + data.email + " is NOT a valid e-mail address. Try again.</div>");
} else {
$("#message_post").html("<div class='successMessage'>" + data.email + " is a valid e-mail address. Thank you, " + data.name + ".</div>");
}
}, "json");
});
For a sample of data entered into the form, how do I go about indicating which link belongs to the parent input field? Baring in mind the parent input fields are sortable jquery ui elements.
here's a sample set of data entered, as you can tell I have no way of knowing which input field the child links belong to:
[thesteps] => Array
(
[0] => This is really the second input field, but dragged up to the first position.
[1] => This is the second input field, but used to be in the first position.
[2] => this is the third input field
)
[links] => Array
(
[0] => this is the first (child) link for the first position.
[1] => this is actually the (child) link for the third field!
)
Any help would be greatly appreciated, thanks in advance
-- 24x7
You could use HTML5 custom data attributes, setting the value of each linked set to be the same number.
For example:
<input id="1" data-newinput-id="1" />
<input id="2" data-newinput-id="1" />
<input id="3" data-newinput-id="2" />
<input id="4" data-newinput-id="2" />
Even if the inputs are re-arranged, you can match them up by getting the attribute values in jQuery like so:
var id = $(this).attr("data-newinput-id"); // 1

Categories