I'm using JsTree to create a tree structure and the display works just fine. I'm populating the tree with an unordered HTML list and each list element has a value saved under the "title" attribute.
What I want to do is, when the user selects a node, a form is submitted which runs objectQuery.php.
<form id="sampleForm" name="sampleForm" method="post" action="objectQuery.php">
<input type="hidden" name="userInputObject" id="total" value="">
Since I usually don't use Javascript or JsTree i don't have any experience in it and I looked up similar questions that were asked and tried my own version of the script which looks like this.
The tree is created like in this script:
<script>
$(function () { $('#treeViewer').jstree(); });
</script>
And what i tried with the other questions to submit the form and pass the value to objectQuery.php:
<script>
$("#treeViewer").on("select_node.jstree", function(e){
var selected_titles = [];
$("#treeViewer").jstree('get_selected').each(function () {
document.sampleForm.userInputObject.value = selected_titles.push(this.title);
document.forms["sampleForm"].submit();
});
// $.post("objectQuery.php");
}
);
</script>
Now when I select a node, nothing happens. Can someone please push me in the right direction.
And again I know this is similar to other questions about this topic but I looked at other questions and tried on my own for a while (otherwise I wouldn't be able to create that script in the first place since I can't code in javascript).
Have a look at this solution - this allows selection of multiple nodes and append them into json to your #total field (made visible for demonstration in the snippet). In this case you will need to handle the form submit separately after last item is selected (You can select more items while holding CTRL or SHIFT). If you want to autosubmit just the first selected, put your submit code right after you set the #total field.
$(function () {
$('#treeViewer').jstree();
$("#treeViewer").on("select_node.jstree", function(e){
var selected_titles = [];
var selectedIndexes = $("#treeViewer").jstree("get_selected", true);
$.each(selectedIndexes,function () {
selected_titles.push(this['li_attr'].title);
});
$("#total").val(JSON.stringify(selected_titles))
// for plaintext
$("#total_plain").val(selected_titles.join(","))
}
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.4/jstree.min.js"></script>
<link rel="stylesheet" href="https://static.jstree.com/latest/assets/dist/themes/default/style.min.css"/>
<div id="treeViewer">
<ul>
<li title="val1">Root node 1</li>
<li title="val2">Root node 2</li>
<li title="val3">Root node 3</li>
<li title="val4">Root node 4</li>
<li title="val5">Root node 5</li>
</ul>
</div>
<input type="text" name="userInputObject" id="total" value="">
<br>
<input type="text" id="total_plain" value="">