How change the querystring for a submited form - asp.net-mvc-5

I have a form with many dropdownlist and i want to exclude the none selected ones from appearing in the querystring when the form is submitted.
So can i use some module or filter to change this behavior.
Ex:
When i search for test the url will be
/someaction?q=test&select1=&select2=
The required url is :
/someaction?q=test
<form action="/search" action="Get">
<label>Search term <input name="q"></label>
<select id="select1" name="select1">
<option value="1">option 1</option>
</select>
<select id="select2" name="select2">
<option value="1">option 1</option>
</select>
<input type="submit">
</form>

Since you're using GET method for form action, you can handle submit event to prevent normal submit and strip out empty values using replace() function with regex, then use location.href to redirect into target URL:
$('form').submit(function (e) {
e.preventDefault();
var queryString = $(this).serialize().replace(/&?[\w\-\d_]+=&|&?[\w\-\d_]+=$/gi, "");
url = this.getAttribute('action') + (queryString.length > 0 ? "?" + queryString : "");
// returns URL /search?q=something when both select elements are empty
location.href = url;
});
Or disable the select elements without values on-the-fly using attr() or prop() to prevent them used in query string, using normal form submit event:
$('form').submit(function () {
$('select').each(function () {
if ($(this).val() == '') {
$(this).prop('disabled', 'disabled'); // or prop('disabled', true)
});
});

Related

how to get single value from input name field instead of array in NodeJS

I am trying to delete elements from the note list. when I try to match a single name to a list title, it shows an array of items.
i want to match
const input name ===day
and output should be "home" from input name field
but it show ["home","home","home","home"]
here is my delete form code:
<form action="/delete" method="POST">
<% for (let i=0; i<newListItems.length; i++) { %>
<div class="item">
<input type="checkbox" onChange="this.form.submit()" name="checkboxname" value="<%=newListItems[i]._id%>">
<p><%= newListItems[i].name %></p>
</div>
<input type="hidden" name="listName" value="<%= listTitle %>"></input>
<% } %>
</form>
app.js code:
app.post("/delete", function (req, res) {
const deleteItem = req.body.checkboxname
const listName = req.body.listName
console.log(listName)
if (listName === day) {
console.log("hello")
} else {
console.log("custome list value")
}
})
There is 4 hidden inputs rendered with same name listName.
So your request payload will be fulfilled with array of values from all of these inputs.
Move hidden input outside of PHP loop.
The point is to make one input with name='listName' instead of four

Express: POST does not send data - var is not defined

In a view, i am trying to get the data that a user sent, via a form, from another view.
This is the view with the form (i have omitted some EJS stuff to avoid confusion):
<form action="/renderer" method="POST" id="sc-form">
<label for="model">Choose a model:</label>
<select name="model" id="model">
<% data.forEach(function(dat) { %>
<option value="<%= dat %>"> <%= dat %> </option>
<% }); %>
</select>
<input type="submit" value="Render the model!" />
</form>
As you can see, the user selects from a dropdown, and then data is POSTed on /renderer.
So, let's handle this POST request on routes.js:
app.post('/renderer', function(req, res) {
var myModel = req.body.model;
res.render('renderer.ejs', {data: myModel});
});
Pretty basic, we get the data that the form sent and we send it to renderer.ejs as parameters.
Finally, let's grab the data on /renderer.ejs (this is inside a <script> tag):
var modelName = <%- JSON.stringify(data) %>;
And i get this error:
data is not defined
But why is that? Data is the name of the variable that the router sent to the view, as parameter.
This is the third day that i am trying to make POST data appear on another view. If anyone could help i would really appreciate it.
I finally found this.
The form has to contain role="form", or else it wouldn't work.

how make checkbox stay checked and reset in node js

I am working on a small project with checkbox and node js. I need the checked box stay on the screen after I click submit button and reset the form after clicking reset button.How can do that?
ejs code
<form method="post" action="/">
<input type="checkbox" name="preference" value="A">A
<input type="checkbox" name="preference" value="B">B
<input type="checkbox" name="preference" value="C">C
<input type="submit" value="Click to Submit">
<input type="reset" value="Erase and Restart">
</form>
node js
express.get('/', (req, res) => {
res.render('form');
});
express.post('/', (req, res) => {
console.log(req.body);
let checkedValue =req.body.preference;
let output = checkedValue==undefined?`You didn' make selection.`:`The preference iterm on menu is ${checkedValue}`;
res.render('form',{
output:output,
});
});
What's going on is that when you submit your form, the webpage is reloaded, so you lose your checked state. You can either save the values on your server and have them pre-checked using an optional checked flag in your ejs template or you can add some client side javascript to handle the form submission for you by writing and event handler for the submit event on the form.
if you expand your ejs template with a conditional checked value on your inputs, your returned page will have them pre-checked
<input type="checkbox" name="preference" <% if (submittedValue === "A") { %>checked<% } %> value="A">A
Or, here's a super simple bit of javascript that would send the values to your server
document.forms[0].addEventListener('submit', function (e) {
e.preventDefault(); // prevent the form from submitting with a page refresh
const data = { values: [] };
e.target.elements.forEach((formEl) => {
if (formEl.checked) data.values.push(formEl.value);
});
fetch('/urlToProcessYourForm', { method: 'POST', body: JSON.stringify(data) });
});

Node.js with express insert new field into existing mongoDB document from server side

Hello I am looking to implement a way to dynamically insert new fields to an existing mongoDB document from the server side with node.js and express.
For example in the local mongoDB the document looks like this.
{
value: 'Google',
url: 'https://google.com',
env: 'Test'
}
I have a route that will already update the current document fields from a form on the UI. However I want to combine that logic with the ability to insert new fields upon updating.
The route below handles updating the document with the existing fields.
router.put("/:id", (req, res) => {
let value = req.body.value;
Application.findByIdAndUpdate(req.params.id, req.body.application, (err,
updatedApp) => {
if(err){
console.log(err);
} else {
console.log(updatedApp)
req.flash("info", updatedApp.value + " " + "successfully edited!");
res.redirect("/qa-hub/applicationmanager");
}
});
});
On the front end I use EJS with a form to update the document. Example below:
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input class="form-control" type="url" name="application[url]" value="<%= application.url %>" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<select class="form-control" name="application[env]" required="true">
<option class="text-center" value='<%= application.env %>'><%= application.env %></option>
<option value='Beta'>Beta</option>
<option value='Dev'>Dev</option>
<option value='Does Not Apply'>Does Not Apply</option>
<option value='Prod'>Prod</option>
<option value='QA'>QA</option>
<option value="Test">Test</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<a class="btn btn-outline-warning" href="/qa-hub/applicationmanager">Cancel</a>
</div>
<div class="form-group">
<button class="btn btn-outline-primary" id="btn" >Update</button>
However i'd like to add three additional fields upon submitting the form. I want to capture the currently logged in user that performed the edit and the date and time. I already have that worked out but how could I implement inserting new data to the existing document from the route.put while also keeping the logic to update the current fields if any changes are made.
So after the user makes some changes and updates the three fields the document would look something like below, except id handle the logic to get the currently logged in user at that time and the date/time and pass it in but for the example below I will hardcode it.:
{
value: 'Google',
url: 'https://google.com',
env: 'Test',
updatedBy: "Test User"
timeUpdated: "12:54",
dateUpdated: "7/25/2018"
}
So ultimately I want to keep a log of the changes and than be able to add it to the UI.
So with a little help from this post TypeError: callback.apply is not a function (Node.js & Mongodb) I was able to append new fields to the existing document using $set. However when trying to perform the req.body.application before $set it would throw an error stating that callback.apply is not a function. So I just created a callback if you will to update the document after setting the new fields. I know its messy but just wanted to get it working feel free to use and clean up the code for your self.
router.put("/:id", (req, res) => {
let value = req.body.value;
let value = req.body.value;
let date = new Date();
let hour = date.getHours();
hour = (hour < 10 ? "0" : "") + hour;
let min = date.getMinutes();
min = (min < 10 ? "0" : "") + min;
let time = hour+":"+min;
let year = date.getFullYear();
let month = date.getMonth() + 1;
month = (month < 10 ? "0" : "") + month;
let day = date.getDate();
day = (day < 10 ? "0" : "") + day;
today = month+"/"+day+"/"+year;
let updatedTo = month+"/"+day+"/"+year;
let updatedT = hour+":"+min;
let updatedBy = req.user.username;
//Find the document based on it's ID and than append these three new fields
Application.findByIdAndUpdate(req.params.id,
{ $set: {
updatedTime: `${updatedT}`,
updatedToday: `${updatedTo}`,
updatedBy: `${updatedBy}`
}}, { upsert: true },
(err,updatedApp) => {
if(err){
return handleError(err);
} else {
// Than if any changes were made from the UI we apply those updates taken
// from the form with req.body.application
Application.findByIdAndUpdate(req.params.id, req.body.application,
(err, updatedApp) => {
if(err){
return handleError(err);
} else {
console.log(updatedApp)
req.flash("info", updatedApp.value + " " + "successfully edited!");
res.redirect("/qa-hub/applicationmanager");
}
}
});
});

Jhipster : disable dialog close on submit

I am using Jhipster V3.
I have created an entity, and Jhipster generated all the needed views.
My client wants that in the update dialog of this entity, the click on Save doesn't close the popup.
I have commented one line on this function :
var onSaveSuccess = function (result) {
$scope.$emit('rhTechvalleyApp:consultantUpdate', result);
//$uibModalInstance.close(result);
vm.isSaving = false;
};
In this popup I have a datepicker component. Its value is getting blank once the save process has finished. It s only a display issue, but I don't know how to get rid of it.
If anyone knows...
Thanks.
[UPDATE]
transformResponse: function (data) {
data = angular.fromJson(data);
data.dateEnregistrement = DateUtils.convertLocalDateFromServer(data.dateEnregistrement);
data.dateDernierPointDisponibilite = DateUtils.convertLocalDateFromServer(data.dateDernierPointDisponibilite);
data.dateDisponibilite = DateUtils.convertLocalDateFromServer(data.dateDisponibilite);
return data;
}
<div class="input-group">
<input id="field_dateEnregistrement" type="text" class="form-control" name="dateEnregistrement" uib-datepicker-popup="{{dateformat}}" ng-model="vm.consultant.dateEnregistrement" is-open="vm.datePickerOpenStatus.dateEnregistrement"/>
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="vm.openCalendar('dateEnregistrement')"><i class="glyphicon glyphicon-calendar"></i></button>
</span>
</div>
You need to add transformResponse to the update function of the Angular service for your entity. It should be the same as transformResponse for get.
Example:
'update': {
method:'PUT',
transformResponse: function (data) {
data = angular.fromJson(data);
data.birthDate = DateUtils.convertLocalDateFromServer(data.birthDate);
return data;
}
}
The reason you need to do this is because the server will return a string like 2016-04-12 for dates. This needs to be converted to a JavaScript Date object, which is what Angular expects for type="date" inputs. If you use a string instead of a date object for ngModel on a date input, Angular will throw an error and fail to fill the field. You can use DateUtils.convertLocalDateFromServer for LocalDate and DateUtils.convertDateTimeFromServer for DateTime.

Resources