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.
Related
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 a JQuery function that fetches and displays a page worth of images through the use of JSON files. I want to display the next set of images upon a button click, but that requires adding on a short string to the request url, which is found and stored in a var when I first run the script. I need to call this JQuery function again and pass the string var to it (lastId in code below). I am an utter noob with JavaScript in general and don't know how to go about doing that.
Here is a full version of the code:
$(function runthis(un){
var lastId;
un = typeof un !== 'undefined' ? un : "";
$('#domainform').on('submit', function(event){
event.preventDefault();
$('#content').html('<center><img src="img/loader.gif" alt="loading..."></center>');
//var lastId;
var domain = $('#s').val();
var newdomain = domain.replace(/\//g, ''); // remove all slashes
var requrl = "http://www.reddit.com/r/";
var getmore;
getmore = "?after=t3_"+un;
var fullurlll = requrl + domain + ".json" + getmore;
$.getJSON(fullurlll, function(json){
var listing = json.data.children;
var html = '<ul class="linklist">\n';
for(var i=0, l=listing.length; i<20; i++) {
var obj = listing[i].data;
var votes = obj.score;
var title = obj.title;
var subtime = obj.created_utc;
var thumb = obj.thumbnail;
var subrdt = "/r/"+obj.subreddit;
var redditurl = "http://www.reddit.com"+obj.permalink;
var subrdturl = "http://www.reddit.com/r/"+obj.subreddit+"/";
var exturl = obj.url;
var imgr = exturl;
var imgrlnk = imgr.replace("target=%22_blank%22","");
var length = 14;
var myString = imgrlnk;
var mycon = imgrlnk;
var end = mycon.substring(0,14);
myString.slice(-4);
var test1 = myString.charAt(0);
var test2 = myString.charAt(1);
var timeago = timeSince(subtime);
if(obj.thumbnail === 'default' || obj.thumbnail === 'nsfw' || obj.thumbnail === '')
thumb = 'img/default-thumb.png';
if(end == "http://i.imgur" ){
$("#MyEdit").html(exturl);
html += '<li class="clearfix">\n';
html += '<img src="'+imgrlnk+'" style="max-width:100%; max-height:750px;">\n';
html += '</li>\n';
html += '<div class="linkdetails"><h2>'+title+'</h2>\n';
/*html += '<p class="subrdt">posted to '+subrdt+' '+timeago+'</p>'; /*'+test1+test2+'*/
html += '</div></li>\n';
}
if (listing && listing.length > 0) {
lastId = listing[listing.length - 1].data.id;
} else {
lastId = undefined;
}
} // end for{} loop
htmlOutput(html);
}); // end getJSON()
}); // end .on(submit) listener
function htmlOutput(html) {
html += '</ul>';
$('#content').html(html);
}
});
The way you currently are executing the function run this doesn't ever leave you a handle to that function. This means it only really exists in the context of document.ready (what $(function()) is a shortcut for).
What you want to do instead is to keep a reference to this function for later use.
If you want to be able to put it directly into an onclick='' you will need to put the function in global,
eg:
var myFunction = function() { /*Stuff here*/}
$(myFunction)
this declares a function called myFunction and then tells jQuery to execute it on document ready
Global is generally considered pretty naughty to edit. One slightly better option would be to assign the click to the button inside your javascript
eg:
$(function(){
var myFunction = function() { /*Stuff here*/}
myFunction(); //call it here
$('#my-button-id').click(myFunction);//attach a click event to the button
)
This means that the function myFunction only exists in the scope of your document.ready, not in global scope (and you don't need onclick='' at all)
tTo add listener on some event you can use live('click',function(){}) Like yhis:
<div id="my-button">some content</div>
<script type="text/javascript">
$('#my-button').live('click',function(){
//your code
})
</script>
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
Is there any way to get the city and state name from zip code from google api using jquery(not using ajax).
I can get the details from here http://maps.googleapis.com/maps/api/geocode/json?address=17078&sensor=true.
and my code is
var googleAPI = "http://maps.googleapis.com/maps/api/geocode/json?address=17078&sensor=true";
$.getJSON(googleAPI, function (response) {
console.log("JSON Data: " + response.items);
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
// in production code, item.text should have the HTML entities escaped.
//document.getElementById("content").innerHTML += "<br>" + item.volumeInfo.title;
alert(item.address_components);
}
});
but this is not working
You have to find the administrative_area_level_1 and administrative_area_level_2 which gives you the state and city names.
Read Geocoding docs
Try this,
<script>
// let you got the items.address_components
for(var a=0,len=items.address_components.length;a<len;a++)
{
ac=items.address_components[a];
if(ac.types)
{
for(var t=0,tl=ac.types.length;t<tl;t++)
{
ty=ac.types[t];
if(ty=='administrative_area_level_1')
{
alert('State'+ac.long_name);
}
if(ty=='administrative_area_level_2')
{
alert('City'+ac.long_name);
}
}
}
}
</script>
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.