I have a dynamic form using EJS and Express in which the user can choose to add more images by clicking a button,
The response works, however for data storing purpose, I want each image response to be stored together in a single array. As this is dynamic, how do I iterate through each of the image form response in order to store tham in an array? as users may only put 1 image, making checking for every single request a bit redundant?
var images = [];
function addImage(file) {
images.push(file);
}
function removeImage(file) {
images = images.filter(img => img != file);
}
When a customer clicks submit button, this arrya value (images) would be submitted.
Related
I have a simple Asp.Net MVC app. I have a form, which I'm trying to gather data for, and then submit. However, within that form is a list of selections - each time a selection is made, I go to the server to add that data:
function addSelection(item) {
fetch("/test/selection/" + item,
{
method: "POST"
})
.then(response => {
const name = document.getElementById('Name').value;
localStorage.setItem("name", name);
if (response.ok) {
location.reload();
} else {
console.error("Unable to add");
}
});
}
The server then stores the list in a HttpContext.Session variable.
The target is to keep the name property in place across calls. The code above works great - I set the control on load:
window.onload = function() {
var getName = localStorage.getItem('name');
document.getElementById('Name').setAttribute('value', getName);
}
However, the form itself is eventually submitted, and the entire form, with the selected items, is submitted to the server:
<div>
<input type="submit" value="Submit"
asp-controller="My" asp-action="Create"/>
</div>
The problem that I have is that the local storage still retains the value of name, and so the next time the form is loaded, it's still there. Does anyone have any techniques for achieving the same result without using local storage?
The only solution that I can think of so far is to replace the submit button with a manually coded JS script that resets the value, but that doesn't account for situations where the user just moves away from the form. I feel like I'm heading down a rabbit hole of my own making, and there must be a simpler way to do the same thing.
One solution is to use hidden form fields to persist the data between requests instead of local storage. On each item selection, add the data to a hidden form field on the client-side instead of saving it to local storage. Then, when the form is submitted, the hidden form field value will be included in the form data and can be retrieved on the server-side.
On the server-side, you can retrieve the NameValue from the form data in your action method.
[HttpPost]
public IActionResult Create(string NameValue, ...)
{
...
}
I am storing the values in localStorage and the values are getting stored through input[type:hidden] and input[type:text].
JS:
$('.proceed_btn').on('click', function() {
// Blank to start with
var order = {};
// Loop through all inputs...
$('input[type="text"], input[type="hidden"]').each(function() {
// ...adding their values as properties
order[this.name] = this.value;
});
// Store that object in JSON format
localStorage.setItem("order", JSON.stringify(order));
});
I want to print these value in other page when the user redirects after submitting the form. I am working on ruby currently. There are many products in the website, so the information in the summary page gets rendered according to that. Is there any way to display specific form details in through there id's?
You can create a partial with .js.erb extension eg _order_partial.js.erb and retrieve the order object as thus:
order = JSON.parse(localStorage.getItem("order"));
// Loop through the object and print out
Then you can render the partial in any of the views file you want to use it.
I need to know how I can show the input data of a form after a user presses the back button.
Here is the working jsfiddle
I created a simple asp page.
If I click next after entering some input value, it will go to next page, and again I click back, it doesn't show entered input values.
$("#form").submit(function() {
var inputs=$('.input');
for(i=0;i<inputs.length;i++)validateEmail(inputs[i]);
if($('.invalid').length!==0)return false;
});
I need to show those values. How can I achieve this? Thanks in advance!
Note: In my jsfiddle didn't include next page action.
You have several methods, althought I'm not a big fan of cookies because they are not so smart to manage.
You can either use:
The localStorage API, if you want your values being saved until the user clears the cache, like this:
var myValues = [];
for(i=0;i<inputs.length;i++) {
validateEmail(inputs[i]);
myValues.push(inputs[i].value);
}
// Save them fot later use
localStorage.myValues = JSON.stringify(myValues);
// After clicking the button you can retrieve them back
var oldValues = JSON.parse(localStorage.myValues);
The sessionStorage API, which lives for the current session of the browser (i.e. when the user closes the browser it gets deleted):
var myValues = [];
for(i=0;i<inputs.length;i++) {
validateEmail(inputs[i]);
myValues.push(inputs[i].value);
}
// Save them fot later use
sessionStorage.myValues = JSON.stringify(myValues);
// After clicking the button you can retrieve them back
var oldValues = JSON.parse(sessionStorage.myValues);
NOTE: I'm using JSON.parse and JSON.stringify because both storage objects (local and session) can only store data in string format.
I'm building an image gallery on WordPress and I want to add a save to lightbox or save to collection function so that I can collect images with a click of a button and then download all images as a zip later. It sorta like a shopping cart without actually buying the stuff that you want. I want it just to be a per session kind of thing so that you don't need to register to the site.
So on my images page, I put a Save to lightbox button and I want to save the ID of this image to a cookie and then I keep adding images to it until I'm done and will click a view lightbox button that will list all of my collected images.
I know how to set a cookie but I don't know how to append values to it.
function saveLightbox(ID){
$.cookie('the_cookie', ID, { expires: 7 });
document.getElementById("result").innerHTML = $.cookie('the_cookie');
}
Here's fiddle of roughly how I want it to work.
To append values to the jQuery cookie, first of all you have to enable the storage of objects. Then you initialize a variable holding the content of the cookie. If the cookie is empty then initialize an empty array. Next, you push the ID to the array. Finally, you store this array in the cookie.
The following code illustrates what it is said above:
function saveLightbox(ID){
$.cookie.json = true;
var idContainer = ($.cookie('the_cookie')) || [];
idContainer.indexOf(ID) === -1 && idContainer.push(ID);
$.cookie('the_cookie', idContainer, { expires: 7 });
document.getElementById("result").innerHTML = $.cookie('the_cookie');
}
Another thing to consider, is that once an ID is already stored in the cookie you might want to prevent adding it again, that is the reason for line 4. You can find the working example here: jsfiddle.
save an array and push id's to that array:
var ids = $.cookie('the_cookie') || [ ];
function saveLightbox(ID){
$.cookie('the_cookie', ids.push(ID), { expires: 7 });
console.debug(ids);
console.debug($.cookie('the_cookie'));
document.getElementById("result").innerHTML = JSON.stringify($.cookie('the_cookie'));
}
(can't test or demonstrate atm, jsfiddle is not available (for me).)
I have two list boxes. One is populated on Page_Load and the other remains empty.
The user has buttons for adding users from the first list to the second list and back.
When the form is submitted, the second list is empty, like it was when it was sent to the client. Here is the JS code:
function add() {
$('#AvailableUsers option:selected').appendTo('#SelectedUsers');
}
function addall() {
$('#AvailableUsers option').appendTo('#SelectedUsers');
}
function remove() {
$('#SelectedUsers option:selected').appendTo('#AvailableUsers');
}
function removeall() {
$('#SelectedUsers option').appendTo('#AvailableUsers');
}
How do I bring the client-side changes back to the server side?
Edit: Code for server-side:
bool canDismiss = chkCanDismiss.Checked;
string messageText = tbMessageText.Text;
PaymentsDataContext db = new PaymentsDataContext();
foreach (ListItem li in SelectedUsers.Items)
{
UserMessages newMessage = new UserMessages();
newMessage.userName = li.Text;
newMessage.messageText = messageText;
newMessage.dismissed = false;
newMessage.canDismiss = canDismiss;
db.UserMessages.InsertOnSubmit(newMessage);
}
db.SubmitChanges();
You have to append/store those items in the hidden field as well, then you can get the items from the hidden field on the server side.
This is because the changes you made at client side are not available on the server side.
If I read correctly you are trying to use the Users in "Selected Users" Server side. I would have an on form submit client side event that selects all the users in the SelectedUsers list. This eliminates the need for a hidden variable. NOTE use the following in conjunction with your existing jQuery
$(document).ready(function(){
$(form).submit(function(){
$('#SelectedUsers option').attr("selected","selected");
return true;
});
});
EDIT In response to comment: When the selected users control is originally loaded on the page there are no items and nothing selected. With your current code, options are added to the selected users list, on the client side. Currently when the form is submitted these values are not selected and therefore not posted back to the server. To post the values back to the server they need to be selected first. What the above code should do is select the users options in the SelectedUsers list and post the selected values, with the rest of the form, back to the server when the form is submitted.
Edit 2, Server Side Code: You may need to access the values via the Request.Form object. With multiple controls like multiple select boxes, multiple values are passed as a comma separated string.
string rawSelUsers = Request.Form[SelectedUsers.ClientID];
You can the perform a split on this string to break it into an array if needed.