I am developing a Rails 4 web application. In my Rails application View i have 2 forms . First form contains List of Employees where i can select employees and add to Second Form by clicking on ADD button . Second form also contains a button where i can remove employees from Second Form, all the removed employees will be moved back to first form.
Currently i achieving it like , when i click the add button in First form i will pass the selected employee data to controller through an Ajax call and return the same selected data to second form to display selected employees.
Is it possible to manage this from client side without making any call to Server.
Is there any gems available in Rails to achieve this.
I am using Rails 4 and Ruby 2.
Example : Sample List Manipulation in Javascript
Any help is appreciated.
Yes it's possible to do this on the client-side
Javascript
All I would do is replace your ajax calls with the on-page JS
Have used JQuery in this example (hope that's okay):
http://jsfiddle.net/U443j/3/
$(".move").on("click", "input", function() {
var button = $(this).attr("id");
var from = document.getElementById("FromLB");
var to = document.getElementById("ToLB");
if (button == "left") {
move(to, from);
}else{
move(from, to);
}
});
function move(tbFrom, tbTo)
{
var arrFrom = new Array(); var arrTo = new Array();
var arrLU = new Array();
var i;
for (i = 0; i < tbTo.options.length; i++)
{
arrLU[tbTo.options[i].text] = tbTo.options[i].value;
arrTo[i] = tbTo.options[i].text;
}
var fLength = 0;
var tLength = arrTo.length;
for(i = 0; i < tbFrom.options.length; i++)
{
arrLU[tbFrom.options[i].text] = tbFrom.options[i].value;
if (tbFrom.options[i].selected && tbFrom.options[i].value != "")
{
arrTo[tLength] = tbFrom.options[i].text;
tLength++;
}
else
{
arrFrom[fLength] = tbFrom.options[i].text;
fLength++;
}
}
tbFrom.length = 0;
tbTo.length = 0;
var ii;
for(ii = 0; ii < arrFrom.length; ii++)
{
var no = new Option();
no.value = arrLU[arrFrom[ii]];
no.text = arrFrom[ii];
tbFrom[ii] = no;
}
for(ii = 0; ii < arrTo.length; ii++)
{
var no = new Option();
no.value = arrLU[arrTo[ii]];
no.text = arrTo[ii];
tbTo[ii] = no;
}
}
This will allow you to move the items between form elements. The reason this is important is because it allows you to send the data to the controller as one data-set:
Controller
On my JSFiddle, I have a save button
This can be tied to your Rails controller, allowing you to send your form data to your system
This will send your params hash like this:
params { "FromLB": ["value1", "value2"], "ToLB": ["value1", "value2"] }
The hash will be structured differently, but you'll get two sets of data, which you can then put into your db:
#app/controllers/your_controller.rb
def action
#from = params[:FromLB]
#to = params[:ToLB]
#Save the data-sets here
end
Related
I have a flask-based site and I query the database in Flask and send that list of values to my html page. From there I have a script that compares a variable to an element in the list, but the case never works.
def start():
title = ""
paragraph = ["Cognitive Motor"]
pageType = 'start'
#if request.form.get("cognitiveAbility1" != None):
methodsQuery = db.engine.execute("select method from permutations")
motorQuery = db.engine.execute("select cognitivemotor from permutations")
motorList = motorQuery.fetchall()
data = request.stream.read()
methodList = methodsQuery.fetchall()
data2 = request.stream.read()
return render_template("start.html", title=title, paragraph=paragraph, pageType=pageType,data=data, methodList=methodList,motorList=motorList)
That is the code in flask, and below is the script I have in my html file.
The case if the if statement never works and won't print out the console.log("test").
<script>
$(document).ready(function() {
$(document).on('click', '.submitButton', function cognitiveFunction() {
var checkCog = document.getElementsByName("cognitive");
var checkMot = document.getElementsByName("motorCheck");
var resultCog = '';
var resultMot = '';
var motorQuery= "";
for(i = 0; i <3; i++) {
if(checkCog[i].checked === true) {
resultCog += checkCog[i].value + '';
console.log(resultCog);
}
}
for(i = 0; i <8; i++) {
if(checkMot[i].checked === true) {
resultMot += 'Yes';
}
else {
resultMot += 'No';
}
}
motorQuery = resultCog + resultMot ;
for(i = 0; i <19; i++) {
if ( '{{ motorList [i]}}' == motorQuery){
console.log('test');
$('body').append("{{ methodList [i] }}")
}
}
When I just print a value from the list of motorList into my html page manually, it looks like this,
(u'Cognitively intactNoNoYesNoYesNoYesYes',)
But in the database it is just
Cognitively intactNoNoYesNoYesNoYesYes
You have a basic misunderstanding of how JS and Flask interact. There is no possible way to put the JS variable i into the Jinja template variable '{{ motorList[i] }}, because Jinja is rendered on the server long before the JS runs on the client.
You will need to output the entire motorList in a format accessible to your script, ie JSON, and then iterate through that in JS.
I've been trying to convert this section of script to jQuery instead of vanilla javascript, but I'm not sure how to loop through the elements with jQuery. Basically, I'm grabbing a data attr value from each field to be used as an error message that displays near the field.
This is all inside a click event on the submit button, FYI
What's the jQuery way?
//Set some variables
var invalidFields = $(form).querySelectorAll(':invalid'),
errorMessages = $(form).querySelectorAll('.error-message'),
parent;
// Remove any existing messages
for (var i = 0; i < errorMessages.length; i++) {
errorMessages[i].parentNode.removeChild(errorMessages[i]);
}
//Get custom messages from HTML data attribute for each invalid field
var fields = form.querySelectorAll('.sdForm-input');
for (var i = 0; i < fields.length; i++) {
var message = $(fields[i]).attr('data-ErrorMessage');
$(fields[i]).get(0).setCustomValidity(message);
}
//Display custom messages
for (var i = 0; i < invalidFields.length; i++) {
parent = invalidFields[i].parentNode;
parent.insertAdjacentHTML('beforeend', '<div class='error-message'>' +
invalidFields[i].validationMessage +
"</div>");
}
I converted your code one-to-one to jQuery. But there might be other ways, when i will know where form, setCustomValidity and validationMessage is coming from.
var $form = $(form);
// Remove any existing messages
$(".error-message", $form).remove();
// Get custom messages from HTML data attribute for each invalid field
$(".sdForm-input", $form).each(function() {
var message = $(this).attr('data-ErrorMessage');
// i don't know where the 'setCustomValidity' function is coming from
// this is a custom function
$(this)[0].setCustomValidity(message);
});
// Display custom messages
$(":invalid", $form).each(function() {
// i don't know where 'validationMessage' is comig from
// this is a custom property
$(this).parent().append("<div class='error-message'>" + $(this)[0].validationMessage + "</div>");
});
You can simple replace this.
var fields = form.querySelectorAll('.sdForm-input');
for (var i = 0; i < fields.length; i++) {
var message = $(fields[i]).attr('data-ErrorMessage');
$(fields[i]).get(0).setCustomValidity(message);
}
Replace with jQuery way
var fields = form.find('.sdForm-input');
$.each(fields, function(index, el){
var message = $(el).attr('data-ErrorMessage');
$(el).setCustomValidity(message);
});
I have created a page containing a text-area field and few check boxes, from where user can write many domain names in each line in text-area field, and then can choose different domain type through check-boxes. then user clicks on submit button which is redirected to bulk domain search page ?
Link to page where I'm trying to do this is --
http://www.ailogica.com/wp/packages/
I tried to create a simple submit button, but that does not work, then I wrote following code to submit the data by calling a function --
<script type="text/javascript">
function alerttlds() {
jQuery.noConflict();
var i = 0;
var j = 0;
var values = new Array();
var tld = new Array();
var bulkdomains = new Array;
jQuery.each(jQuery("input[name='tld[]']:checked"), function() {
tld[j++] = jQuery(this).val();
});
for(var k = 0; k < tld.length; k++) {
var lines = jQuery('textarea[name=sld]').val().split('\n');
jQuery.each(lines, function(){
bulkdomains[i++] = this+tld[k];
});
}
//alert(bulkdomains.join("\n"));
document.getElementById('bulkdomains').value = bulkdomains.join("\n");
document.forms["bulkchecks"].submit();
}
</script>
I am trying to create a button using SharePoint designer that onclick will allow users to browse folders and then put the contents (path:\filenames) into a sharepoint list column. I have used the below code and it works except I need a solution that does NOT use activeX as my system is set to not allow unsigned activex. I am open to any solution that will work on a sharepoint list that does not use and activex control. My button onclick="getFolderFiles()"
function getFolderFilesSub(fsoFolder, astrFolderFiles) {
var eFiles = new Enumerator(fsoFolder.Files);
eFiles.moveFirst();
While (eFiles.atEnd() ==false) {
astrFolderFiles.push(eFiles.item().Path);
eFiles.move.next();
}
var eSubFolders = new Enumerator(fsoFolder.SubFolders);
eSubFolders.moveFirst();
while (eSubFolders.atEnd() == false({
getFolderFilesSub(eSubFolders.item(), astrFolderFiles);
eSubFolders.moveNext();
}
}
function getFolderFiles() {
var objShell = new ActiveXObject('Shell.Application');
var objShellFolder = objShell.BrowseForFolder(0, 'Choose a folder', 0, 0);
if (objeShellFolder != null) {
var fso = new ActiveXObject('Scripting.FileSystemObject');
var fsoFolder = fso.GetFolder(objShellFolder.Items().Item().Path);
astrFolderFiles = new Array();
getFolderFilesSub(fsoFolder, astrFolderFiles);
if (astrFolderFiles.length != 0) {
var strFolderFiles = astrFolderFiles[0];
for (var i=1; i <= astrFolderFiles.length-1; i++) {
strFolderFiles = (strFolderFiles + '\n\ + astrFolderFiles[i];
}
document.getElementById(ct100$PlaceHolderMain$g_85cf34cd_8dc3_47ca_85d9_
a6f47297db56$ffFileNames$ct100#ct100$text
field").value = strFolderFiles;
}
}
javascript
function test(abc) {
var ddlArray = new Array();
var ddl = document.getElementById('AdjusterList');
for (i = 0; i < ddl.options.length; i++) {
ddlArray[i] = ddl.options[i].value;
}
var indexsel = ddl.selectedIndex;
return indexsel ;
}
ASP
strArrayCRN = osRecordSet.RecordCount
strArrayCRN2 = osRecordSet2.RecordCount
dim StrCount
StrCount =strArrayCRN+strArrayCRN2
HTML +ASP
<select name="AdjusterList" id="AdjusterList" onchange='test("<%=StrCount%>")'><%
%>
<option value="0">Please choose an option from the list.</option>
<% Do While (osRecordSet.EOF = False)
%><option value="<%=osRecordSet.RowPosition%>">
<%=osRecordSet.Fields("NAME")%></option>
<%
osRecordSet.MoveNext
Loop %><%
Do While (osRecordSet2.EOF = False)
%><option value="<%=osRecordSet2.RowPosition%>">
<%=osRecordSet2.Fields("NAME")%></option>
<% osRecordSet2.MoveNext Loop %>
Here i want to pass the return value of function test() i.e value of the selected index to asp server side
If you want to send it to server during normal html page submit, put the return value in hidden field.
If you want to send the value before the form submit, use AJAX.
Hidden Field method
JavaScript
function test(abc) {
var ddlArray = new Array();
var ddl = document.getElementById('AdjusterList');
for (i = 0; i < ddl.options.length; i++) {
ddlArray[i] = ddl.options[i].value;
}
var indexsel = ddl.selectedIndex;
document.getElementById("returnValueField").value = indexsel;
return indexsel ;
}
HTML
<input type="hidden" id="returnValueField" name="returnValueField" />
In ASP access this hidden field like an other form field.
For AJAX use some library like jQuery to make things easier.
Using AJAX with jQuery
First you need to include the jQuery library in your page.
Then modify your function like this
function test(abc) {
var ddlArray = new Array();
var ddl = document.getElementById('AdjusterList');
for (i = 0; i < ddl.options.length; i++) {
ddlArray[i] = ddl.options[i].value;
}
var indexsel = ddl.selectedIndex;
// Ajax call starts
$.ajax({
url: "your_asp_page_to_handle_request.asp",
data: {"selected_index": indexsel },
success: function() {
alert("I am back after sending data sucessfully to server.");}
});
// Ajax call ends
return indexsel ;
}
Your ASP code in your_asp_page_to_handle_request.asp will be something like this
<%
dim selectedIndex
selectedIndex = Request.QueryString("selected_index")
%>
Please note that you can also use jQuery.get() instead of the Ajax function we used above.