I have a basic input form on html, where a button dynamically creates more input boxes with javascript.
Upon pressing submit the data is collected in python (flask) fine, however upon returning the response and static html page the extra dynamic input boxes created are destroyed.
What is the best way to render template, or return a variables to the html page, without destroying the dynamically created boxes.
Thankyou
***HTML:***
<div class="col-12" id = "InputRows">
<div class="row">
<div class="col-xl-4 offset-xl-0"><label for="Quantity">Quantity</label></div>
<div class="col-xl-4 offset-xl-1"><input type="number" name="Quantity" value = {{QuantityReturn}} required></div>
# New inputs are dynamically appended here
</div>
***Python:***
#app.route("/CalculateMaths", methods=['POST'])
def CalculateMaths():
if request.method=='POST':
Quantity=request.form.get("Quantity")
QuantityReturn=Quantity
return render_template("template.html",QuantityReturn=Quantity) #sending back this destroys the dynamically appended HTML inputs
The render_template method, as the name suggests, re-renders the entire page. This is why it is deleting any changes you made to the DOM dynamically. You are probably better off preventing the default submit event using a client-side script and simply requesting/returning the quantity in JSON format.
Related
I am using Spring Boot and Thymeleaf with some vanilla JavaScript. In my JavaScript, I have an array of strings as below:
var tags = ["ramen", "japanese"];
I want to use JavaScript to dynamically add/remove items in this array before it gets submitted to the backend. The user can add 0..* tags.
Data gets submitted to the backend only via HTML <form> submits. There is also a model attribute which captures these details from the HTML form into Spring called VenueForm.
<form id="tag-form" class="form" method="POST" th:object="${venueForm} th:action="/venue/tag">
VenueForm.java
public class VenueForm {
private List<String> tags;
private Object otherStuff;
...
// Getters and Setters
}
VenueController.java
#Controller
#RequestMapping("/venue/tag")
public class VenueController {
#PostMapping
public String createVenue(#ModelAttribute VenueForm venueForm){
List<String> tags = venueForm.getTags();
System.out.printLn(tag);
return "tags"
}
}
How do I assign the JavaScript array tags to the Thymeleaf form List field tags?
Usually the input comes from th:field="*{tags}" in an input field but because its an array I am not sure how to achieve this. Any help would be much appreciated. Please note jQuery is not an option, only vanilla JS.
I have tried to stop the HTML form submit using JS, then assigning the input field using JS but that did not work.
<input type="submit" value="Submit" th:onsubmit="submitForm(event)">
main.js
function submitForm(event){
event.preventDefault();
venueTagInput.value = JSON.stringify(tags);
console.log("sumitting...");
}
This existing post has helped me figure this out (Send Array using HTML)! Thymeleaf is just a templating engine on the server side, it renders into basic HTML. There is no need to do anything Thymeleaf specific to send an array of elements in the form. You have to follow the basic HTML way using the name attribute on an input field. You can use Javascript to create new DOM elements and making sure that for each element the index is incremented. No changes are needed on the controller side. Spring can work out that name="tags[0]" is tags.get(0);
<input type="text" class="form-control tag" id="1" name="tags[0]" value="">
I'm trying to send one <input type="file"... value to another <input type="file".. using Javascript.
I've created an HTML form and after filling it, I want to review the form. Then submit that form in my FormFill model through views.py.
So far what I have done is creating 2 different Divs for the same work.
In div1, I'm sending my form data using action="javascript:reviewForm()" and in reviewForm(), I'm setting all the form data of div1 to div2 form using
document.getElementById('cfname2').value = document.getElementById('cfname1').value;
It's setting all the values and then posting it to views.py successfully except my <input type="file" name="pic2".. data.
Since python retrieves form POST data using request.FILES['pic2'], in div2 I don't have file data to Post.
So far what I've tried is:
document.getElementById('pic2').value = document.getElementById('pic1').value;
where,
In div1 I have <input type="file" id="pic1"...
and in div2, <input type="file" id="pic2"...
My models.py
class FormFill(models.Model):
pic = models.ImageField(upload_to='candidates/pics/')
...
How can I post the div2 image data to views and then to Django models?
Note: I don't want to Post the div1 data directly to Django models since I want my users to first review the form that they have filled. And that's why using the concept of 2 Divs.
Thanks in advance.
Ps.Please ask me if I'm not able to clear the question.
I am using the BrainTree.js for PCI compliance, and the tutorial I am using here:
https://www.braintreepayments.com/docs/javascript
There recommendation is to call the form by the ID like so:
var braintree = Braintree.create("YourClientSideEncryptionKey");
braintree.onSubmitEncryptForm('braintree-payment-form');
I'm using AngularJS with the form being inside a controller. So inputs such as name, card, etc are tied to a scope using ng-model:
<div class="form-group">
<label>Card Number</label>
<input type="text" class="form-control" name="number" ng-model="card.number" />
</div>
My question is how can I submit a form using AngularJS and BrainTree.js in a manner that uses the data collected using ng-model?
Example:
braintree.onSubmitEncryptForm({name: $scope.card.name, card: $scope.card.number});
In Braintree, the braintree.onSubmitEncryptForm function wraps a small amount of functionality. Basically it just grabs the jQuery form representing the input data, transforms the form fields, and then scrubs them from the DOM, before allowing the request to be submitted to the server.
Since angular includes jQuery, you could call the braintree.encryptForm($('#braintree-payment-form')); which would return the encrypted data in the DOM. You should be able to access the 'ccv' and 'number' input elements like normal (the expire doesn't need to be encrypted).
month=55&year=5555&number=%24bt4%7Cjavascript_1_3_10%24ne0ib
vLjzzck52xzNiY2C8grXaZgpwfVpGrsR9TbHLPaW983e3y7R6tClw8YxYe5w
MA9%2BNHLjPBb%2FEsJQBSiCARJK7Wlxu53GO6mHMr0QMglQEiy9%2B9Dla8
DkY0XBpyfomqniwsDEuudiX7l%2FIb%2FsS4BRFu1BS8MpNpYWSghdj%2FTR
28jhRxlBNZVLjlG9cJd%2FNwDIRUv80qX4Di38bjrvywZR3nP%2BsEcUDSZj
DYQb08LDtN6Vhg5%2FTt1ketZqQH83XheDAFeTuGnb6iE1n8cZbePio8%2FC
m071d2zDZiSc57m%2BEnMJERc%2F2NYrWERl32o4L6DlltB9veZH30mKsPkB
Q%3D%3D%24qpTMCwpQQ5aEk3QO60yu8dQ1SBh3ezit564s1gK604tyIHh%2F
XqipKWgPCli2ZtFW%24AUph2EeuSMh2e8CxNRGVfsIRLvegNAulBDdDY3kwl
GA%3D&cvv=%24bt4%7Cjavascript_1_3_10%24e%2FWsFiRYkHsV%2B6RD5
j26KwII3ErBklZjXB2o1SKGtg1GvemW9J5cSQNBu3K%2BAy0uymAu5awICVR
pIB7%2FiIPBkC8vHBhX57oJabKkCyqkm6YWKio5Pce%2BasD1q4RzGFT1y1Q
iqw%2Fmt12ovQz6G%2B6yZbqQ0wUtFPt4vMSnmQIBogNtgiXeHbirSDHrY9N
V7hoBIaQ%2FV4up87AXs%2FL36FKuBF1rtTyhh%2BEEDgvqkKuRfr6Sim2zc
JNEvcsi7mJp4y6F1%2BNUiLao3w8RfTKt%2BUJUU1XHz3sWLeb2A1chamnFY
UjdVyEgrRFpGH9%2BLdrNYghpmibM6xRsO9p%2Bi1a8yYOMsg%3D%3D%24sd
IGDgI6Jo3zru4YEXtvYI37Oesw09HBISdpcCh6dho%3D%24s8SaRheCM6kWV
OQQ3Ae%2FJjVQQpw6Hht0BWrVIGpV1u4%3D
And then POST to your create_transaction method (if you're running from the tutorial).
I currently have this tree node which was created from http://mbraak.github.io/jqTree/. I am trying to implement this tree, so that when a user clicks on a node in the tree, it will send the data to my servlet. Is there any way to do this? I am currently using JSP. My initial solution was to add a button so that the button (with form tag) will do post action when it is being clicked(after selecting my node), but i would like to know if there is any solution without using a button. I also thought of using ajax but im new to this and am not sure if it works. Really need some help. Thanks
My Tree:
$('#tree1').tree({data: data});
$('#tree1').bind(
'tree.click',
function(event) {
if (event.node) {
// node was selected
node = event.node.name;
alert(node);
// send node value to servlet
}
else {
}});
HTML
<div id="tree1"></div>
My Initial idea
$('#saveCat').click(function(){
document.getElementById('mainCat').value = node;
document.getElementById('action').value = "savecategory";
});
<form action="TopicCloudServlet">
<button id="saveCat" class=" catbtn btn-primary">Save</button>
<input type="hidden" id="mainCat" name="mainCat" value="" />
<input type="hidden" id="action" name="action" value="" />
</form>
Assuming that you are dynamically creating the tree , you can add extra elements as attributes to each nodes of the tree when you render it.Do not worry,your custom attributes will be ignored by the browser.
Below "nodevalue" is your own attribute that you add to the div dynamically when rendering the tree to uniquely identify each node.
<div id="tree1">
<div nodevalue="node1" class="mynode">
</div>
<div nodevalue="node2" class="mynode">
</div>
</div>
Then write a jquery class selector onclick event and get the unique ID of the clicked node.
$(".mynode").on("click",function(){
alert(this.attr("nodevalue"));
});
this.attr("nodevalue")
will give the value of the node you currently clicked.
Ok i found 1 solution which is very simple( why didn't i thought of it)
Add an id to the form that is going to be submitted.
At the javascript where u want your form to be submitted,
document.forms["FormID"].submit();
I try to replace classic input file with JqueryFileUpload widget.
Here is my context :
I can have one or more file input in the same form.
The form is meant to create server side objects (each input is a field of this object and each file is a "resource" object linked to the main created object). Those object are stored in a database.
When the final user submit the form, I'd like to :
do many validation (for other inputs)
if all is ok, then trigger the ajax upload of file(s). A server-side handler create the
needed ressource object(s).
when all the uploads are completed (I can know that by using the widget callbacks), then I submit the main form (the action form is not the widget handler but a page that do the job and display a message) to create the main object : I don't want to send the file(s) here but only the ressource objects id that the handler send me back to link them to the main object).
My problem is, when I trigger the fileUpload the form is submitted and the action form page is loaded. The handler isn't called.
I made test with a simple page : if the widget is not within a form it works fine :
<body>
<div>
<!-- The file input field used as target for the file upload widget -->
<input class="fileupload" type="file" name="files[]"/>
</div>
</body>
but if I put it in a form the form is always submitted and I can't prevent this.
<body>
<form action="myPage.aspx">
<!-- The file input field used as target for the file upload widget -->
<input class="fileupload" type="file" name="files[]"/>
</form>
</body>
My questions are :
Doesn't the url option override the form action ?
Can I not use different target for the widget and the form that contains it ?
Can I put multiple widgets in a single form ?
Okay just for information it was a pretty stupid mistake from my side, I used a which default behavior is 'submit' so my form was always submitted.