Submit form in javascript using form name - javascript

I'm dynamically generating forms with hidden input in a webpage using django templates, which should be submitted when clicking on some associated text label. The problem is that I just can't get it to work.
{% for tag in tags %}
<form name="remove_{{ tag }}" id="{{ tag }}" action="/filter" method="post" accept-charset="utf-8">
<input type="hidden" name="remove_tag" value ="{{ tag }}" />
</form>
{{ tag }}
{% endfor %}
<script type="text/javascript">
function remove_tag(tag) {
document.getElementById(tag).submit();
return false;
}
</script>
This code generates the following javascript error: Uncaught TypeError: Cannot call method 'submit' of null
I've also tried submitting the form using
document.forms[tag].submit();
(changing the form name to tag), but receive pretty much the same error but with 'undefined' instead of null.
In the second example, it looks like the javascript function tries to interpret 'tag' as an integer. If I do use an integer it works alright. I could use the forloop.counter used to generate the forms in the first place, but that is kind of ugly and makes the code harder to maintain.
Is there any other, functioning, way of calling submit() on the forms?

Quotes:
{{ tag }}
The "tag" value has to be properly quoted for the Javascript snippet to be syntactically correct.

Related

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.

Using javascript variable in python(flask/Django) dictionary html

I am trying to use a javascript variable in a python dictionary in html, is this possible? Any help would be great.
e.g if I had a dictionary - current_data
var num_key = "4";
alert( {{ current_data[num_key] }} );
If I do the following it works perfectly,
alert( {{ current_data["4"] }} );
But with the javascript variable, it won't work.
Thanks again.
No, while you can use Jinja to create JavaScript embedded in <script> tags, you cannot use it the other way around. When Flask renders this page it's static. The page does not still have blocks of code inside {{ }} or {% %}, it holds the result of those operations. However, there are other options. You could put the contents of current_data into hidden input with the keys as the id attributes.
View
{% for key in current_data %}
<input id="{{ key }}" type="hidden" value="{{ current_data[key] }}"/>
{% endfor %}
JavaScript
var num_key = "4";
alert(document.getElementById(num_key).value);
One extra piece of advice, it's not good practice to embed JavaScript into your html. You should have a separate .js file containing this and then include it in your html.

Editors returning contents with html tags

At first I thought it was the wysiwyg editors fault I had to try different ones. But turns out they all return contents with html tag...so it must be me. I'm using https://github.com/douglasmiranda/django-wysiwyg-redactor and this also returns with html tag. ex: if I type hello it returns <p>hello</p> so I tried safe filtering and some other filtering but none of them works. how do I fix this? Thanks in advance
{% block content %}
<form id="post_form" method="post" action="/add_post/" enctype="multipart/form-data">
{% csrf_token %}
{{ form |crispy|safe }}
<input type="submit" name="submit" value="Create Post">
</form>
{% endblock %}
I also tried {{form|safe}} which doesn't work...and I want to use crispy as well.
After I read the docs I've found this one:
data = django_wysiwyg.clean_html(data)
Try it, I hope it works...
EDIT:
{{ form |crispy|safe }}
This outputs the RAW Html, this is what you don't want I guess...

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>

Javascript validation for dynamically generated forms in Django template

I am struggling with something that is probably very basic: I need to generate a form with marks for my University database application. Each student in each module has a class got "Performance" that stores all the marks for the module. There are different assessments and the Performance class calculates the average for them.
I need to be able to enter, for example, all the marks for the first assessment, and I did that with a dynamically generated Django Form as a table in the template:
{% for performance in performances %}
<tr>
<td>
{{ performance.student }}
</td>
<td>
{% if to_mark == 1 %}
<input type="text" class="input-mini" name="{{ student.student_id }}" value="{{ performance.assessment_1 }}">
{% else %}
{{ performance.assessment_1 }}
{% endif %}
</td>
And the same for the other assessments (to_mark gets passed on by views.py to indicate which assessments needs to be marked here)
I have failed to use Inlineformfields and therefore decided to generate a form dynamically and validate it with Javascript, also because the validation is simple (has to be a number between 1 and 100), and also because I want to use Javascript to calculate the average on the fly.
My problem is that I have no clue about Javascript. All the tutorials (like this one http://www.w3schools.com/js/js_form_validation.asp) use the name of the form field in the Javascript function, but in my case that name is dynamically generated, so that I can access it easily in the views.py:
if student.student_id in request.POST:
tmp = request.POST[student.student_id]
try:
mark = int(tmp)
if mark in range(0, 100):
performance = Performance.objects.get(student=student, module=module)
if to_change == 1:
performance.assessment_1 = mark
...and so on for the other assessments
except ValueError:
pass (in case someone accidentally enters a letter and not a number)
Is there a way I can use Javascript to address my form fields? Or should I use a different approach than taking the student_id as the name to read it out? How could I do that?
Thanks,
Tobi
There are at least 3 ways to get to the form fields using JavaScript:
By ID, by CSS class or by DOM traversal. If you're not familiar with JavaScript, I would suggest finding a django-friendly client-side form validator like: https://code.google.com/p/django-ajax-forms/

Categories

Resources