replace parameter using jquery - javascript

I'm working with python and jinja. When I render template I sent two parameters like this :
return render_template('mod_page/index.html',
types_first = utils.questions_first(),
types_second = utils.questions_second())
questions_first and questions_second are two same functions, something like this:
def questions_first(self):
return ['Name','Surname', 'Phone']
In index page I have a tag like this:
<html lang="en">
...
I want to take lang attribute with jQuery and then to check if it is 'en' I want to use questions_first if it is 'sr' I want to use questions_second.
My question is how can I replace the parameter types_first inside jinja code or put there, I don't know exactly what to do, I tried to do it like this:
<script>
$(document).ready(function(e){
var language = $('html').attr('lang');
var selectedFunction;
if(language == "sq"){
selectedFunction = "sq";}
else{
selectedFunction = "sr"; }
</script>
....
<p> Questions: </p>
{{ _({% for type in types_first %}) }}
<div class="checkbox">
<label><input type="checkbox" value="{{ type }}">{{ type }}</label>
</div>
{% endfor %}

First solution (better):
If you want to change lang, you can use i18next framework (http://i18next.com/docs/). It's much simpler solution.
Second solution (worse):
Select via jQuery element you want to change -> use empty() function -> render element with changed values and assign it to selector with append()
You can also combine both solutions. Write function to rerender template and change dynamically langauge. e.g.:
fn_or_elt.empty();
fn_or_elt.append(markup);
fn_or_elt.i18n();

Related

Pass Javascript variable into Django tag

as the title says I'm trying to replace a value in my Django tag with a Javascript variable. I'm not sure if it's even possible but here is what I have (The tag is between ``):
const myTemplate = (list) => html`
<form method="post" class="notes-form">
{% csrf_token %}
{{ user.profile|meet_notes:15 }}
<div>
<button type="submit">Send</button>
</div>
</form>
`
I would like to replace the 15 by a variable like ${list.met_profile.id} for exemple (this tag will render an input with a value of this variable, here 15).
Thank you!
put the following code in your HTML document
<span id="change_val">abc</span>
<script>
const ele = document.getElementById("change_val")
ele.innerText = 15
</script>
The better way to do this is to use a serializer instead of a template tag. the django template tag will run before the js so this is not ideal.

Accessing a html tag attribute in Django template expression

There is a html element:
<input type="text" id="someInput" name="someInput"></input>
It's value is set in JavaScript:
var tbIndx = 10;
document.getElementById("someInput").value = tbIndx;
Now,I want to construct a Django for-loop which would use the value of the html tag described above.Something like this:
{% for i in val %}//val is the innerHTML of the input box described above.
//code
{% endfor %}
Can we access a value like this in a Django template?Please suggest some methods for achieving this functionality.
Thanks
No you can't do this. Django for loop will run only for values passed from context in view.py. Better you submit the input value using Ajax. And return it to run in template from Ajax response.

How to pass or use variable from GSP in Javascript

I have below line in my grails gsp file.
<div class="pagination">
<g:paginate total="${lotCount ?: 0}" />
</div>
I want to pass lotCount value to one of my javascript named area-switcher.js file to further use it. How can I do this?
I tried to refer one suggestion from How to pass a value directly from a controller to a javascript file in Grails
where I do below in my gsp
<g:javascript> var theId = ${lotCount} </g:javascript>
and try below in my js file for testing
alert(theId);
but it doesn't work.
Got error like ReferenceError: theId is not defined.
Please help.
Use a hiddenField:
<g:hiddenField name="lotCount" value="${lotCount}" />
<div class="pagination">
<g:paginate total="${lotCount ?: 0}" />
</div>
Your solution should work.
Just ensure that in source of generated html page line
<g:javascript> var theId = ${lotCount} </g:javascript>
is placed before line which includes area-switcher.js
<script type="text/javascript" src="area-switcher.js">
Besides that, there are two more options to pass some value from .gsp to javascript file (examples use jQuery):
By using of data attribute. For example,
gsp (here div, span, input, other tags could be used):
<div id="countElem" data-count="${count}">
js(jQuery used here):
var count = $("#countElem").data('count');
As was mentioned in another comments, by using of hidden field:
gsp:
<g:hiddenField name="countElem" data-count="${count}"/>
js(jQuery used here):
// hidden field will have name and id equals to countElem
var count = $("#countElem").val();

Fill input field, with twig value using jquery

I've been searching for a while with no luck.
I know my question looks mundane, and it has plenty (as in hundreds) of answers out in google and here, yet, still my problem seems far from solved.
I have the following problem, I need to fill an input field, with a value from silex variables in a twig file.
the form is as follows:
<span>Author: </span>
<input type="text" name="author" id="author"
{% if user.getAuthorName %}value="{{user.getAuthorName}}"{% endif %} />
<span>Use your own username</span>
and the js code is:
<script>
$(function(){
$('#filler').live('click', function() {
$("#author").val($("#author").text("{{user.getFirstName}} {{user.getLastName}}"));
});
});
</script>
the problem I'm having is, the code actually works, yet still, when i click, it fills the field with
[object Object]
instead of the actual value of the 2 variables
I've tried changing it to a hidden field with an id, and setting the variables as value, and using
.text($("#idfield").val())
still no luck, still fills the values with
[object Object]
has any of you any idea what I'm doing wrong here?
You should remove the double declaration:
$("#author").val("{{user.getFirstName}} {{user.getLastName}}");
Here is a bit cleaned up version of your code with no live as it's deprecated/removed.
$(function() {
$('#filler').on('click', function(e) {
e.preventDefault();
//If your JS is parsed as a twig template then, you could use
$("#author").val("{{user.getFirstName}} {{user.getLastName}}");
//and remove the data-full-name from your HTML
//If not, keep the data-full-name and use:
$("#author").val($("#author").data("fullName"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Author: </span>
<input data-full-name="{{user.getFirstName}} {{user.getLastName}}" type="text" name="author" id="author" value="{% if user.getAuthorName %}{{user.getAuthorName}}{% endif %}" />
<span>Use your own username</span>

How to pass parameter to js function from template parameter array

I generated in tornado template table with cities and I am trying to have like last column details button
{% if globals().has_key('results') %}
{% for result in results %}
<tr>
<td>{{result['name']}}</td>
<td>{{result['citizens']}}</td>
<td style="width:100px; height:100px;">
<div class="ui-grid-b">
<a class="ui-block-a ui-icon-detail" onclick="showDetails('{{id}}',{{result['city_id']}});" data-role="ui-li-aside" data-icon="right_arrow" data-theme="a"></a>
</div>
</td>
</tr>
{% end %}
{% end %}
and on click to load on another page with parameters in url.
<script type="text/javascript">
function showDetails(id, city_id)
{
window.location = '/cities?id='+id+'&city_id='+city_id;
}
</script>
How to pass parameters to show details function ? (I cannot use ', I tried with \" but it doesn't work). Results is list of dictionaries with keys name, citizens, city_id.
{{ }} is used by tornado template to access passed parameter.
showDetails = function (id, city_id)
{
window.location = '/cities?id='+id+'&city_id='+city_id;
}
I think is the easy way
The variable inside the braces will be output directly (or, the string representation of it), so it depends what it is set to.
e.g. if you have:
id = 'foo'
results = [{ 'city_id': 'bar' }]
and you are passing them to the template, then this line:
showDetails('{{id}}',{{result['city_id']}});
will be output as follows (you can confirm this with view source):
showDetails('foo',bar);
I'm guessing you're missing the quotes around {{result['city_id']}}, unless result['city_id'] is an integer, in which case it should work. Single or double quotes are both fine in JavaScript.
However, as #Pete already pointed out, "on click to load on another page with parameters in url" is what we have the href attribute for. You can save yourself a lot of work and potential brokenness with:
<a href="/cities?id={{ id }}&city_id={{ result['city_id'] }}" ....></a>

Categories

Resources