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();
Related
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.
I can easily update the html when it's not part of the form's submit or button. Or even when it's just a pure button element (rather than an input from a form). However, when I try to append a string to the class "chatGoesHere", nothing happens. The consolealso quickly reloads since the form is going to \send.
I'm happy to post my views.py and urls.py, however, I'm pretty sure the issue is inside of my html document below:
<p class="chatGoesHere" id="chatGoesHere"> 1st Item! </p>
<form action="\send\" method="post">
<input type="text" name="userMessage" />
<input type="submit" value="Send to smallest_steps bot" class="sendButt" id="sendButt" />
</form>
<script>
var btn = document.getElementById("sendButt");
btn.addEventListener("click", updateChat);
function createMenuItem(name) {
let li = document.createElement('p');
li.textContent = name;
return li;
}
const td = document.getElementById('chatGoesHere');
td.appendChild(createMenuItem("TEST2"))
function updateChat(){
const td = document.getElementById('chatGoesHere');
td.appendChild(createMenuItem("TEST3"))
}
</script>
I'd like it so that every time a user pushes the submit button of the form something gets added to the page without the page reloading.
Thank you
You need to use django with sockets.
Take a look at this walk through.
Helped me to do the same thing a few years ago!
https://channels.readthedocs.io/en/stable/tutorial/part_2.html
I’m using CFS for files upload in my Meteor App, almost everything works fine, except because when I try to upload another image, I see my previous sended image in the form, so I need to clear that form after submit the image. I've tried with .reset but it doesn't work. This is my code right now. Thanks for the help.
NewImage.html
<template name="newImage">
<div align="center">
<form align="center">
<div>
<div>
<span class="btn btn-success btn-file">
<input type="file" accept=".gif,.jpg,.png" class="myFileInputimagepub" id="image"/>
</span>
</div>
<div>
<img src="{{currentUser.profile.image}}" alt="Image" width="60px" height="60px" class="img-circle avatar-upload" value=''/>
</div>
</div>
</form>
</div>
</template>
NewImage.js
import './newImage.html';
Template.NewImage.events({
'change .myFileInputimagepub':function(evt,tmpl){
FS.Utility.eachFile(event,function(file){
fileImagespub.insert(file,function(err,fileObj){
if(!err){
var userId = Meteor.userId();
var imageurl = {
'profile.image':'/cfs/files/fileimages/' + fileObj._id
};
setTimeout(function(){
Meteor.users.update(userId,{$set:imageurl});
},2000);
}
})
})
},
'submit form':function(event,template){
event.preventDefault();
template.find("form").reset();
}
});
If the image in question is the one with class .img-circle, the issue is that its src attribute is being dynamically provided. Currently it is currentUser.profile.image. This won't clear just by resetting the form and manually clearing the image's src value would be fighting the framework.
Option 1 (Not Ideal):
If you don't want to keep the image, unset the database change made after the file upload by running something like this:
Meteor.users.update(userId, { $set: { 'profile.image': null }});
This is not ideal as it enables you to continue modifying the database with an image which may not be needed long-term.
Additionally, I'm assuming you're currently using the autopublish/insecure packages. You'll want to remove these before going public with your app as they allow any user to change the database without restriction.
Option 2:
You could save the returned value from your 'change .myFileInputimagepub' event as a ReactiveVar, then only actually run Meteor.users.update (preferably on the server using a Method) when your user submits the form. At that point you could clear the reactive variable.
Using a ReactiveVar will allow you to provide the saved URL to the src attribute via a helper, and then change the ReactiveVar's value when you wish to clear the form.
There's a simple example of manipulating ReactiveVars here: https://gist.github.com/ahoereth/a75d2d6528b1844ad503
Have a Java based web application with a page where a feed of posts is dynamically generated with the help of JSTL. The user can currently 'like' any post in the feed but this has proved much more difficult to implement using AJAX. I know i'm really close here but can't quite figure out what's wrong.
It works but only for the first item in the array.. So any like button that is pressed in the feed, only updates the first like button in the feed. Why is it that the dynamically assigned div value (input name=likesDivCount) only registers the first assignment?
index.jsp
<c:forEach items="${idFeedArray}" var="posts" varStatus="count">
...feed item (such as image, text etc..)...
<form id="likesform" action="../AddLike" method="post" style="display:inline;">
// the value of this input below is supposed to change...(i.e. #likesSize0,#likesSize1,#likesSize2)
<input name="likesDivCount" value="#likesSize${count.index}" type="hidden">
<input name="postUser" value="${userpost[count.index]}" type="hidden">
// this button sends the AJAX request
<button style="padding-right: 0;" type="submit" class="btn btn-link"><span class="glyphicon glyphicon-thumbs-up"></span></button>
</form>
// The span in the button below updates with the response from the AJAX
<button style="padding-left: 0;" class="btn btn-link"><span id="likesSize${count.index}">${likesArraySize[count.index]}</span></button>
</c:forEach>
<script>
$(document).on("submit", "#likesform", function(event) {
var $form = $(this);
var likesDivCount = $("input[name=likesDivCount]").val();
//this alert below is for testing, everytime the like button is pressed it displays '#likesSize0' and i need it to spit #likesSize1,#likesSize2,#likesSize3 etc...
alert(likesDivCount);
$.post($form.attr("action"), $form.serialize(), function(response) {
// only updates the first item :( (#likesSize0)
$(likesDivCount).text(response);
});
event.preventDefault(); // Important! Prevents submitting the form.
});
</script>
Looks like you have multiple forms with the same ID: '#likesform'. This is because your forms are generated in a loop.
I suggest you to remove the ID, replace it with a css class (or something else) and rewrite the JS to search for elements inside the target form, e.g.:
var $form = $(this);
var likesDivCount = $form.find("input[name=likesDivCount]").val();
Once you have valid html it will be easier to troubleshoot
I want to develop a webpage wich dynamically adds and removes particular webforms (all webforms with the same structure) on the page (when pressing add and remove buttons). Adding and removing the webforms already works in the code below (using a jquery function), but I still struggle to create the related unique name values when submitting more forms. My idea is:
- to put all forms in an array (forms() )- each with unique name values
- ...and maintain in a array (formsavailable()) which forms have been added/used and which have been removed.
I already added the code (below) to maintain formsavailable() when adding forms. But I dont know how to code formsavailable() for removing forms.
Any ideas? Or are there simpler ways for creating the unique name value's with the described context?
Please your comments.
Thank you.
The code:
<script>
var forms = Array();
var formsavailable = Array();
forms = getProductconfigforms(); //create a list of strings with the product forms
var NUMBER_OF_FORMS = 5;
for (var i=1; i<=NUMBER_OF_FORMS;i++)
{
formsavailable[i] = true; //at the start all forms are
}
//script for adding and removing productss
$(document).ready (function () {
var i;
$('.btnAdd').click (function () {
i = formsavailable.indexOf(true);
$('.buttons').append(forms[i]); // end append
formsavailable[i] = false;
$('div .btnRemove').last().click (function () {
$(this).parent().last().remove();
}); // end click
}); // end click
}); // end ready
</script>
</head>
<body>
<h2> text here </h2>
<div class="buttons">
<input type="button" class="btnAdd" value="Add"><br>
</div>
<p> tekst </p>
<input type="button" value="Terug naar stap 1" onclick="goBack()">
</body>
You actually don't need to make a unique index or unique name. The HTTP protocol supports sending multiple data points with the same name.
For example, this is totally fine: &name=me&name=you&name=them&name=her. On the back end, depending on which framework and language you are using, you simply get an array.
So in your form, you can use
<label> Product 1 <input name="product_name" type="text" /></label>
<label> Product 2 <input name="product_name" type="text" /></label>
...
And so on, until you've added however many forms you wish. When you submit the form, your page will automatically take care of sending them on to your backend form, where you can parse out each form programmatically.