Update database table - javascript

I am currently using grails and I am trying to figure out a way that I can update my database table utility with the two values selected from two drop down menus. My drop down menus are passed values from this table when a user selects a specific value from another drop down. I'm trying to figure out how to update my table so that I can load the newly changed values into the drop down menu upon reloading.
For example: I have mondayStart and mondayEnd drop down menus that are populated with times 9am-5pm based upon the values from the database. If the user changes the value from the drop down menu mondayStart from 9:00 am to 10:00 am the value 10:00:00 replaces the current database value 09:00:00 upon clicking the Update button I have created and will also update the other drop down menu mondayEnd upon being changed and will be overwritten in the database.
Currently I have my drop down menus which are populated from the users specific actions:
<td style="text-align: center; width: 115px;" onchange="e" >
<select name="mondayStart" id="mondayStart">
</select>
<select name="mondayEnd" id="mondayEnd">
</select>
</td>
And my test to see if the change alert is working:
$("#mondayStart").live('change', function(e){
alert($(this).val());
});
This is my update button:
<g:submitButton name="update" style="float: right; margin-right: 10px" type="button" id="update" value="Update" onchange="e" />
How can I set this up to allow my database to be updated with multiple values upon the click of my update button?

I think something along these lines should do the trick :-
$("#update").click(function() {
-- code for adding to the database would go here --
-- might be an idea to use $.post() --
});
Let me know if this helps and if it doesn't I will try and come up with something else.

You should submit the form (via ajax or normal way) and in your controller retrieve the values from params.
For example, you could have in your controller a method like the following:
def save(String mondayStart, String mondayEnd){
//Update your domain with those values
//render view, return values or redirect where you want
}
One note, you can define the parameters on the method parameters o just recover them from the params object

Related

Clear dropdown Select2 populated from JSP / Ajax with a button only works once

I have a page in which to make a query to the database, 12 filters are applied (each filter corresponds to a select2 dropdown).
When the page loads, the selects are filled by default with data from the java controller.
Example from a jsp page:
<select id="selectFPA" name="selectFPA" form="formResult" class="form-control">
<option selected>All the results</option>
<c:forEach items="${fpaList}" var="fpaList">
<option><c:out value="${fpaList.fpaname}" /></option>
</c:forEach>
</select>
But, if the user selects any value in any of the filters, all the filters are updated based on the chosen selection, through an AJAX call.
For example, suppose we have two select filters (dropdown):
Select 1 (Animal group):
- Birds
- Mammals
Select 2 (Animal name):
- Parrot
- Dog
If the user chooses mammals, an AJAX function will be called that will query the database and update the content of the select 2, eliminating the Parrot option. (And so on with up to 12 filters).
The problem comes when I want to clear the applied filters and return to the original select content (the content that appears by default every time the page is loaded from the java controller).
I have tried many things, from similar Stackoverflow questions without success.
The last thing I tried was:
Save the initial content of the select in a variable:
const fpa = $("#selectFPA").find("option").clone();
Onclick event (Reset filters button)
$("#ResetFilters").on("click",function() {
//first we empty the content
$('#selectFPA').empty().trigger('change.select2');
//original value injection
$("#selectFPA").html(fpa),
$('#selectFPA').trigger('change.select2')
})
This works fine if I press the button once, if I press the button a second time, the selects randomly select different values by default and they behave strangely.
I know this is a very specific question, but could someone help me? What am I doing wrong?
Thank you.
I think as per this answer you cannot create constant in jquery that's the reason only first time it works and next time it doesn't .Alternate, solution might be assign that clone value to some div and fetch it anytime when needed.Like below :
//call when page loads for the first time
$(document).ready(function() {
//cloning
var fpa = $("#selectFPA").find("option").clone();
//assigning value to div
$("#abc").html(fpa);
$("#ResetFilters").on("click", function() {
//getting clone value from div
var c = $("#abc").find("option").clone();
//first we empty the content
// $('#selectFPA').empty().trigger('change.select2');
//original value injection
$("#selectFPA").html(c);
//$('#selectFPA').trigger('change.select2')
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectFPA" name="selectFPA" form="formResult" class="form-control">
<option selected>All the results</option>
<option>1</option>
<option>2</option>
</select>
<button id="ResetFilters">Reset</button>
<div id="abc" style="display:none"></div>

Angular UI-Grid - Selected items not being reset after the grid's data is refreshed

I have a grid (ui-grid) where I need to update its data some times. But when I refresh the data I keep getting the selected row from the old "view". My code:
$scope.gridApiDfcAss.selection.clearSelectedRows();
$scope.gridOptionsDfcAss.data = $scope.data.fidSelected.dfc;
$scope.gridApiDfcAss.grid.notifyDataChange(uiGridConstants.dataChange.ALL);
It's inside a function (setInfoOnListChange) called when I change the value on a list in a html page:
<select class="form-control" ng-options="fid.label for fid in myFidList" ng-model="data.fidSelected" ng-change="setInfoOnListChange('fid')" ng-if="onlyMyResponsability" ></select>
Example to understand:
https://postimg.org/image/enkw3796h/
after that I refresh the data but the first line remains the same ("DFC_AFCRestrLvl1") (I can't post more than 2 links, so I can't show it).
That It's wrong how you can see in the debugger:
https://postimg.org/image/mu8ubc2v5/
should be "DFC_AirCClntPAnaSRCMin" not "DFC_AFCRestrLvl1" (that is my selected row in the previous grid).
As you can see in my code I have already tried to clear the selected row before update the data. I'm also calling the notifyDataChange method but it's not working :-(

Hold input=date value in HTML after submited button in table

I searched a lot but maybe because I am quite new here i couldn't fine a result that's works for my challenge.
Project view
What's is going on:
I have made page where users could click on a date-picker, after the user selected a date or a date range and they click on the submit button "Verzenden"the table that is positioned under the selection area shows all data from that specific date or date range that is available in the database.
In this table the user is able to adjust some data from a specific table row.
After clicking on the submit "Ok" button the changes the user made is pushed to the database.
Now my challenge:
After the user has changed some data from a row an they click on submit button "Ok" i want to achieve that the user is getting back to it's last date selection that he made before adjusting some data in a row table. What is the best way to handle this ?? I hope someone could help me, thanks already for participating and reading.
The term you're looking for is "pre-populating a form". You can pre-populate the form with PHP by generating HTML that has the value written directly in the HTML
<input type="text" value="<?php echo htmlspecialchars($someValue, UTF8, ENT_BOTH);?>">
Your homework probably wants you to save the input into the user's SESSION, and then check the SESSION every time you render the page. If a previous value is in the session, then pre-populate the form (i.e. render the HTML with the hard-coded values).
Try this:
<form autocomplete="on">...</form>
the "autocomplete" attribute allows you to save your selection that you've submit after reload the site.
If you don't want this feature take effect for some special tag,you should write your code like this:
<form autocomplete="on">
...
<input type="date" autocomplete="off" /> // this tag won't save the choice
</form>
check this fiddle : https://jsfiddle.net/9nfz311z/
html part:
<input type="date" name="test"/>
js part :
var dateInput = document.querySelector('input[name="test"]');
var DOMReady = function(a,b,c){b=document,c='addEventListener';b[c]?b[c]('DOMContentLoaded',a):window.attachEvent('onload',a)}
// on change save in localStorage the value
dateInput.addEventListener('change', function(e) {
localStorage.setItem(dateInput.name, dateInput.value);
});
// on dom ready if localStorage has date value apply it to the input
DOMReady(setDateValue);
function setDateValue() {
var date = localStorage.getItem(dateInput.name);
if (date) {
dateInput.value = date;
}
}

Making Meteor reactive for html elements

So I have a modal box that allows the user to edit / save some data.
I just want to add that unlike other Meteor apps, I don't want to save the data straight away - I want the user to fill in all the fields before hitting save where it will save to the database and send to server etc. This is mainly because I want the user to be able to hit the "cancel" button to revert all changes.
I have a drop down box at the start of the form where depending on the value, fields will be shown or hidden
<select class="form-control" id="ddlNewInputType" placeholder="Enter your input type">
<option value="input">Input</option>
<option value="formula">Formula</option>
</select>
And I have a handlebar around a field like this to determine whether I want to show it
{{#if isFormula }}
<div class="row">
<input type="text"
id="txtNewInputFormula" placeholder="Enter formula">
</div>
{{/if}}
With a helper looking like this
isFormula: ->
$('#ddlNewInputType').val() == 'formula'
However, this doesn't work. Aside from when it first loads onto the page, it never hits isFormula, probably because Meteor doesn't consider any of the HTML elements as reactive so it never re-evaluates when the HTML element changes.
What is a suitable way to get around this? Is it possible to make something reactive explicitly in Meteor? I was also considering putting the dropdown list value into a session variable but that just seems messy because I'm going to need to manage this session variable (remember to clear it when the modal box closes etc.)
Your analysis is correct - a reactive variable needs to be involved in order for your helper to reevaluate after changing the select element. The basic strategy looks like:
Initialize a reactive variable when the template is created.
Whenever the select changes, update the reactive variable.
Read the reactive variable in your helper.
Rather than use a session variable, let's use a ReactiveVar scoped to your template. Here's an example set of modifications:
Template.myTemplate.helpers({
isFormula: function() {
return Template.instance().isFormula.get();
}
});
Template.myTemplate.events({
'change #ddlNewInputType': function (e, template) {
var isFormula = $(e.currentTarget).val() === 'formula';
template.isFormula.set(isFormula);
}
});
Template.myTemplate.created = function() {
// in your code, default this to the current value from
// your database rather than false
this.isFormula = new ReactiveVar(false);
};
Remember that you'll need to also do:
$ meteor add reactive-var
See my post on scoped reactivity for a full explanation of this technique.

Dynamically populate drop down menu with selection from previous drop down menu

I have a cgi script written in Python. There are two drop down menus and then a submit button. I'd like to be able to make a selection from the first menu, and based off that choice, have the second drop down menu dynamically populate new choices. The second menu should populate without having to click any button, but simply from making a selection from the first menu. The second menu should also repopulate continually every time I select a new item on the first menu - again, without clicking submit.
What's the general idea to getting this done? I already have implemented some of the code. It uses if/else statements on conditions of whether the inputs have been provided. So after the first drop down menu selection is made, the page submits, and an if/else statement directs to code that displays the same form but with the selection maintained in the drop down menu. I'm using onchange='this.form.submit() to submit the form without having to use the submit button. The current problem is that while making a selection submits the form automatically the first time, reselecting on this form does not seem to work. So, I'm not sure if onchange='this.form.submit() submits the form after the first time.
Here is a prototype. Am I going in the right direction? Or should I be using Ajax? (not familiar with this at all yet):
firstChoicesList = firstChoices()
print(""" <form method="post" action="/cgi-bin/thisScript.py">""")
# if both choices are not selected yet
if "firstChoice" not in form and "secondChoice" not in form:
# first choice drop down menu
print("""<p>first choice <select name="firstChoice">""")
for f in fristChoicesList:
print("""<option value='""" + f + """'>""" + f + """</option>""")
# second choice drop down menu
print("""</select></p>""")
print("""<p>second choice <select name="secondChoice">""")
for f in secondChoicesList: # currently contains 1 empty string
print("""<option value='""" + f + """'>""" + f + """</option>""")
print("""</select></p>""")
print("""
<p><input type="submit" />
</form>
""")
print("Please fill in the forms.")
sys.exit(1) # don't proceed with rest of code below these if/else statements
# if first choice has been selected but not the second
elif "firstChoice" in form and "secondChoice" not in form:
# <code for first drop down menu again with choice selected>
# this function takes the first choice as an argument and returns selections for the second menu
secondChoicesList = secondChoices(form["firstChoice"].value)
# <code for second drop down menu with choices populated from secondChoicesList>
print("""
<p><input type="submit" />
</form>
""")
print("Please fill in the forms.")
sys.exit(1)
# if both are selected
else:
# <same code as above except have both drop down menus save previous selections>
# proceed to run rest of cgi script
This is an hint: you can populate the next menu with an ajax call to a server side page (that will give you back the data): this will let you:
- Avoid to send forms and pass values through pages (you will send the form only at the end)
- Let user changes his choise (if he need it), without surfing the history
I think that using ajax with jquery will be really simple to use, also if you don't know it.
Please, check short ajax jquery fiddle example to see how easy is to use jquery (here, for cross domain request, that shouln't be your case, you have to disable web security of your browser, e.g. for google chorme set google chrome to make cross domain request with ajax )
code of the fiddle:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<body>
<select name="a" id="a" onchange="func(this.value)">
<option value="">choose</option>
<option value="https://www.google.it/search?q=ajax+and+juery&oq=ajax+and+juery&aqs=chrome.0.57j0l3.7474j0&sourceid=chrome&ie=UTF-8#sclient=psy-ab&q=ajax+jquery&oq=ajax+jquery&gs_l=serp.3..0l10.2179.3578.2.3820.7.3.1.3.3.1.206.516.0j2j1.3.0...0.0.0..1c.1.15.serp.9gdUZUmAxcI&psj=1&bav=on.2,or.r_qf.&bvm=bv.47244034,d.ZGU&fp=41333c9f97f3f20a&biw=800&bih=505">google</option>
<option value="http://it.bing.com/search?q=ajax+jquery&go=&qs=n&form=QBLH&filt=all&pq=ajax+jquery&sc=0-0&sp=-1&sk=">bing</option>
</select>
</body>
<script>
function func(ak){
$.ajax({
url : ak,
success : function (data,state) {
$("body").html(data);
alert(state);
},
error : function (request,state,error) {
alert("Error. stato della chiamata: "+request+' '+error+' '+state);
console.log("Error. stato della chiamata: "+request+' '+error+' '+state);
}
});
}
</script>

Categories