Increase in number of divs, while using jsPlumb - javascript

I have created three div elements in an HTML page, each of these 3 div elements contain a text box i.e. an input element in it. One div, is made a source while other two are made target. The HTML page has a button name toggle.
The initial connection between source div and one of the target div is created with the help of drag and drop. When toggle is clicked, it will remove the connection between the source and the target, and will create the new connection between source and the other target. Now, when performing analysis using google chrome developer tools over this scenario, the number of div elements keep on increasing by 2 for every toggle.
<!DOCTYPE html>
<html>
<head>
<title>
jsplumb_demo
</title>
<script src="./dist/libs/jquery.js"></script>
<script src="./src/jquery-ui.min.js"></script>
<script src="./src/jquery.jsPlumb-1.7.6-min.js"></script>
<script>
var connection12 = undefined, connection13 = undefined;
jsPlumb.ready(function() {
var exampleGreyEndpointOptions = {
endpoint:"Rectangle",
paintStyle:{ width:10, height:10, fillStyle:'#666' },
isSource:true,
connectorStyle : { strokeStyle:"#666" },
isTarget:true,
container:$('#container'),
connector : "Straight",
deleteEndpointsOnDetach: true
};
jsPlumb.makeSource($('div.source'), exampleGreyEndpointOptions);
jsPlumb.makeTarget($('div.target'),exampleGreyEndpointOptions);
jsPlumb.makeTarget($('div.target1'),exampleGreyEndpointOptions);
init = function(connection){
};
connectionDelete = function(){
if(connection12 !== undefined){
jsPlumb.detach(connection12);
jsPlumb.unmakeTarget($('div.target'));
connection13 = jsPlumb.connect({source : $('#source'), target : $('#target1')},exampleGreyEndpointOptions);
connection12 = undefined;
}
else{
jsPlumb.detach(connection13);
jsPlumb.unmakeTarget($('div.target'));
connection12 = jsPlumb.connect({source : $('#source'), target : $('#target')},exampleGreyEndpointOptions);
connection13 = undefined;
}
};
});
jsPlumb.doWhileSuspended(function(){
jsPlumb.bind("connection", function(connInfo, originalEvent) {
init(connInfo.connection);
//alert("Source div id = " + connInfo.sourceId + " Target div id = " + connInfo.targetId);
var input = "input#" +connInfo.sourceId;
var inputval = $(input).val();
var output = "input#" +connInfo.targetId;
$(output).val(inputval + " from " + connInfo.sourceId);
connInfo.targetId ==='target'?connection12 = connInfo : connection13 = connInfo;
});
jsPlumb.bind("click", function(conn, originalEvent) {
if (confirm("Delete connection from " + conn.sourceId + " to " + conn.targetId + "?"))
jsPlumb.detach(conn);
});
jsPlumb.bind("connectionDrag", function(connection) {
// alert("connection " + connection.id + " is being dragged. suspendedElement is ", connection.suspendedElement, " of type ", connection.suspendedElementType);
});
jsPlumb.bind("connectionDragStop", function(connection) {
// alert("connection " + connection.id + " was dragged");
});
jsPlumb.bind("connectionMoved", function(params) {
//alert("connection " + params.connection.id + " was moved");
});
});
</script>
</head>
<body>
<div id="container">
<div class="source" id="source" style="position: absolute;left: 200px" >
<input/>
</div>
<div class="target" id="target" style="position: absolute;left: 600px" >
<input />
</div>
<div class="target1" id="target1" style="position: absolute;left: 600px; top:200px" >
<input />
</div>
</div>
<button name="delete" type="button" onclick="connectionDelete()">Toggle</button>
</body>
</html>
Edit :-
Fiddle link

Related

How to keep appended data on refresh?

I have a contenteditable div that serves as an editor to allow users to input and save text. Upon clicking a save button, I prompt them to ask what they want to save the text as.
The title is then saved to localstorage and appended to a separate div, where they click the title and the text they saved it under will appear in the editor.
The issue now is that whenever I refresh the page, the appended data disappears. Was wondering how I could keep the appended data there on refresh? Also, I need it to still be able to link to its content, not just become a bunch of text in a div.
I've simplified the entire code here:
<!doctype html>
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js">
</script>
</head>
<body>
<div style="width:10em; height:10em; border-style:solid; border-color:black;" id="editor1" contenteditable="true"></div>
<button id="savebtn">Save Changes</button>
<div style="width:10em; height:5em; border-style:solid; border-color:red;" id="Contentable"></div>
<script>
var editElem = document.getElementById("editor1");
$(document).ready(function() {
$("#savebtn").click(function() {
var title = prompt("What would you like your title to be?");
localStorage.setItem(title, editElem.innerHTML);
titles = localStorage.getItem("titles");
if (titles == null) {
titles = [];
} else {
titles = JSON.parse(titles);
}
titles.push(title);
localStorage.setItem("titles", JSON.stringify(titles));
var htmlData = "<a onclick=showData('" + title + "')>" + title + "</a><br>";
$("#Contentable").append(htmlData);
var userVersion = editElem.innerHTML;
localStorage.setItem("userEdits", userVersion);
editElem.innerHTML = "";
});
});
function showData(txt) {
editElem.innerHTML = localStorage.getItem(txt);
}
</script>
</body>
</html>
EDIT: How can I also remove the data from the div using say a "remove" button? In the event where the div gets too packed and there are some useless titles that the user wants the remove.
Try this ... i hope it works
<!doctype html>
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js">
</script>
<style type="text/css">
.selected{
background-color: blue;
color:white;
}
</style>
</head>
<body>
<div style="width:10em; height:10em; border-style:solid; border-color:black;" id="editor1" contenteditable="true"></div>
<button id="savebtn">Save Changes</button>
<button id="remove">Remove Data</button>
<div style="width:10em; height:5em; border-style:solid; border-color:red;" id="Contentable"></div>
<script>
var editElem = document.getElementById("editor1");
$(document).ready(function() {
$("#savebtn").click(function() {
var title = prompt("What would you like your title to be?");
localStorage.setItem(title, editElem.innerHTML);
titles = localStorage.getItem("titles");
if (titles == null) {
titles = [];
} else {
titles = JSON.parse(titles);
}
titles.push(title);
localStorage.setItem("titles", JSON.stringify(titles));
var htmlData = "<a onclick=showData('" + title + "')>" + title + "</a><br>";
$("#Contentable").append(htmlData);
var userVersion = editElem.innerHTML;
localStorage.setItem("userEdits", userVersion);
editElem.innerHTML = "";
});
});
function showData(txt) {
editElem.innerHTML = localStorage.getItem(txt);
}
function loadData()
{
var htmlData=localStorage.getItem("titles");
htmlData=htmlData.replace(/\[|\]/g, "");
htmlData=htmlData.replace(/["']/g, "")
htmlData=htmlData.split(",");
var arlength=htmlData.length;
console.log(arlength)
for(num=0;num<arlength;num++)
{
$("#Contentable").append("<a onclick=showData('" + htmlData[num] + "')>" + htmlData[num] + "</a><br>");
}
}
loadData();
var selected;
$("#Contentable a").click(function(){
selected=$("#Contentable a").index(this);
$("#Contentable a").removeClass("selected")
$(this).addClass("selected");
})
$("#remove").click(function(){
$("#Contentable a:eq("+selected+")").remove();
// Some Delete codes to localStorage here=================================
})
</script>
</body>
</html>

How can I run a function when a radio is selected and I click a button?

I've created this simple code that I'll use to store in the user's browser, so, I'd like to know how can I run a function when there's a selected radio and when I click the delete button, using JS or JQuery. Any help is appreciated.
Thanks in advance.
check it on liveweave
P.S.: Your browser should have WebStorage support
var taskCounter = 1 + Number(localStorage.getItem("count"));
var name = "de"+ taskCounter;
for(var i=1;i<taskCounter;i++){
var temp = "de" + i;
document.writeln("<br/>"+'<input type="radio" name="rad" value="'+localStorage.getItem(temp)+'" /> <label>'+localStorage.getItem(temp)+'</lable>');
}
function saveItUp(){
var desc = $('#descrip').val();
alert(desc);
// Store
localStorage.setItem(name, desc);
localStorage.setItem("count", taskCounter);
// Retrieve
console.log(localStorage.getItem(name));
console.log(localStorage.getItem("count"));
}
//This is where I'm trying to do that, I know selected doesn't exist, but I put it just for a better comprehension
function deleteItUp(){
$('input:radio').selected(function(){
if (this.checked) {
alert(this.value);
}
});
}
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div id="main">
<label>Task</label> <textarea id="descrip"></textarea>
<button onclick="saveItUp();" id="save">Save it</button>
<button onclick="deleteItUp();" id="delete">Delete</button>
</div>
</body>
</html>
I have edited your snippet. Use $('input[type="radio"]').prop('checked') to see whether the radio button is checked. You will need to modify the selector to get the appropriate radio button if there are multiple on the page.
var taskCounter = 1 + Number(localStorage.getItem("count"));
var name = "de" + taskCounter;
for (var i = 1; i < taskCounter; i++) {
var temp = "de" + i;
document.writeln("<br/>" + '<input type="radio" name="rad" value="' + localStorage.getItem(temp) + '" /> <label>' + localStorage.getItem(temp) + '</lable>');
}
function saveItUp() {
var desc = $('#descrip').val();
alert(desc);
// Store
localStorage.setItem(name, desc);
localStorage.setItem("count", taskCounter);
// Retrieve
console.log(localStorage.getItem(name));
console.log(localStorage.getItem("count"));
}
//This is where I'm trying to do that, I know selected doesn't exist, but I put it just for a better comprehension
function deleteItUp() {
if ($('input[type="radio"]').prop('checked')) {
alert('Deleting!');
} else {
alert('Delete radio not checked!');
}
}
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div id="main">
<label>Task</label>
<textarea id="descrip"></textarea>
<button onclick="saveItUp();" id="save">Save it</button>
<button onclick="deleteItUp();" id="delete">Delete</button>
<input type="radio">Check to delete
</div>
</body>
</html>
I've been trying other ways to achieve it, and I found a nice way that gave me the expected result, thank all of you who tried to help me.
var taskCounter = 1 + Number(localStorage.getItem("count"));
var name = "de" + taskCounter;
for (var i = 1; i < taskCounter; i++) {
var temp = "de" + i;
document.writeln("<br/>" + '<input type="radio" name="rad" value="' + temp + '" /> <label>' + 'Code: ' + temp + ' | Value: ' + localStorage.getItem(temp) + '</lable>');
}
function saveItUp() {
var desc = $('#descrip').val();
alert(desc);
// Store
localStorage.setItem(name, desc);
localStorage.setItem("count", taskCounter);
// Retrieve
console.log(localStorage.getItem(name));
console.log(localStorage.getItem("count"));
}
var selectedRadioId = 0;
$('input:radio').change(function() {
if (this.checked) {
selectedRadioId = this.value;
}
});
function deleteItUp() {
if (selectedRadioId !== 0) {
alert('Deleting!');
} else {
alert("Radio hasn't been checked!");
}
}
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div id="main">
<label>Task</label>
<textarea id="descrip"></textarea>
<button onclick="saveItUp();" id="save">Save it</button>
<button onclick="deleteItUp();" id="delete">Delete</button>
</div>
</body>
</html>
You are talking about firing an event when a radio button is checked and then calling a callback function: https://api.jquery.com/checked-selector/

Error when calling jQuery html method

I am making my first foray into javascript + jQuery, designing a simple page but encountering errors, I'm sure it's something silly but I've been over the code several times and can't spot it.
The error I receive is below:
The entire code is below (I've changed the dynamic '#' + elementname + 'perc' to a string and I get the same error), can anyone offer any insight?
<DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<!--<script src="js/dealercalc.js"></script>-->
<script type="text/javascript">
$(document).ready(function(){
$(".val-adjust").click(function(){
var name = $(this).attr('name');
var bit = $(this).attr('value');
setvalue(name,bit);
//discountbits['basic'] = false;
//$("#basedisper").text(discountlist['basic']);
});
$("#basdisyes").click(function(){
discountbits['basic'] = true;
//$("#test1").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val(gettotal());
});
}
);
function getpercbypurc(value){
return 0;
};
function setvalue(elementname,yesno){
discountbits[elementname] = yesno;
if (yesno) {
$("#basicperc").hmtl(discountlist[elementname] + "%");
} else {
$('#' + elementname + 'perc').hmtl("0%");
}
};
function gettotal() {
var total = 0;
for (var i=0; i<keys.length; i++){
if (discountbits[keys[i]] = true) {
total += discountlist[keys[i]];
}
}
return total;
};
function displaytotal(){
$('#totalper').html(gettotal());
};
var keys = ['basic', 'marketing'];
var discountlist = {
basic:20,
marketing:2
};
var discountbits = {
basic:true,
marketing:false
};
</script>
</head>
<body>
Base Discount<br>
<button class="val-adjust" name="basic" value="false">No</button>
<button class="val-adjust" name="basic" value="true">Yes</button>
<span id="basicperc">0</span>
<br>
<br>
Marketing Plan<br>
<button class="val-adjust" name="marketing" value="false">No</button>
<button class="val-adjust" name="marketing" value="true">Yes</button>
<span id="marketingperc">0</span>
<br>
<br>
Total<br>
<span id="totalper">0</span>
</body>
</html>
You have wrong spelling for html, hmlt should be html
Change
$("#basicperc").hmtl(discountlist[elementname] + "%");
To
$("#basicperc").html(discountlist[elementname] + "%");
you have a typo
$("#basicperc").hmtl(discountlist[elementname] + "%");
//-----^^^^---here
should be
$("#basicperc").html(discountlist[elementname] + "%");
you've made a typo, it's html not hmtl :)
Very obvious typo. It's html, not hmtl !

Call a cfquery in javascript but, it's not doing anything

I'm trying to create a query using Coldfusion (cfquery) to retrieve several dollar amounts, add them, and then see if it matches the dollar amount being calculated in the application. But, it's not doing anything.
I'm attempting to do all of this in javascript.
Here is the code.
function ValidateFunding(){
var casenum = document.getElementById('CaseNum').value;
var cycle = document.getElementById('Cycle').value;
var year = document.getElementById('FSYear').value;
var cnty = document.getElementById('selCounty');
var cntyID = cnty.options[cnty.selectedIndex].value;
<cfquery name="PSP" datasource="QueryTest">
SELECT g.Fee220 + g.Fee330 + g.Fee456 + g.Fee225 AS GrandTotal
FROM ProgFees g INNER JOIN County ON g.CountyID = cntyID
WHERE g.Year = year
AND g.Cycle = cycle
AND g.CaseNum = casenum
</cfquery>
if (document.getElementById('totbud').value = PSP.GrandTotal){
alert('The fee matches.');
return false;
}
else
{
alert('Fees do not match.');
}
return true;
}
Here is a page I worked up for a test. There are comments in the code to help explain what's going on. Two key lines are the <cfajaxproxy> tag and jd.getData(); is my AJAX call to CF.
<cfscript>
variables.folders = {"client":["Favorites","Not Used"],"org":["2012","2011"],"public":["New","Old"]};
</cfscript>
<cfajaxproxy cfc="cfc.jsondata" jsclassname="emaildata" />
<!DOCTYPE html>
<html>
<head>
<title>DevJSON</title>
<script src="js/jquery.1.7.2.js" type="text/javascript" language="JavaScript"></script>
<script src="js/handlebars.js" type="text/javascript" language="JavaScript"></script>
<link rel="stylesheet" href="css/json.css" type="text/css"/>
<script type="text/javascript">
<!--- toScript will output CF vars as js vars --->
<cfoutput>
var #toScript(variables.folders, 'folders')#;
var #toScript(cgi.http_host & '/data/emaildata.json','jsonPath')#;
</cfoutput>
var jd = new emaildata();
// setup my js object from cfajaxproxy above
var buildGrid = function(dataObj){
var menus;
var source = $('#grid').html();
var template = Handlebars.compile(source);
$("#mainContent").hide();
$("#mainContent").children().remove();
$("#mainContent").append(template(dataObj));
$("#mainContent").fadeIn('slow');
}
// Error handler for the asynchronous functions.
var badJson = function(statusCode, statusMsg){
alert('Status: ' + statusCode + '<br /><br /> ' + statusMsg);
}
// output data
var buildmenu = function(){
$.each(folders, function(fkey,fval) {
if(this.indexOf() < 1){
$('li[data-type="' + fkey + '"] > div').append('<ul class="' + fkey + '"></ul>');
}
$.each(fval, function(dkey, dval){
$('[class="' + fkey + '"]').append('<li id="' + fkey + '">' + dval + '</li>');
});
});
}
$(document).ready(function(){
buildmenu();
$('.directory > ul > li').click( function() {
//set callback, errorhandler and then call the getData function in my CFC
jd.setCallbackHandler(buildGrid);
jd.setErrorHandler(badJson);
jd.getData(this.id);
$(".directory > ul > li").removeClass("highlight");
$(this).addClass('highlight');
});
$("#mainContent").css('display','none');
$('li[data-type]').css('cursor','pointer');
});
</script>
<!--- Setup handlebars template --->
<script id="grid" type="text/x-handlebars-template">
<div class="gridDetail">
{{#each DATA}}
<div class="row">
{{#each this}}
<span class="cell">
{{.}}
</span>
{{/each}}
</div>
{{/each}}
</div>
</script>
</head>

how to add text boxes dynamically without losing values of previous textboxes?

i am using innerHTML to add text boxes dynamically. The code sample is as follows:
<html>
<head>
<script type="text/javascript" >
var i=0;
function add()
{
var tag = "<input type='text' name='" + i + "' /> <br/>";
document.getElementById("y").innerHTML += tag;
i++;
}
</script>
</head>
<body>
<input type="button" id="x" value="Add" onclick="add();" />
<div id="y"></div>
</body>
</html
Are there any ways to add text boxes dynamically without losing values of previous text box when a new text box is added?
Similar question has been posted, but there are no answers :(
What if I want to add textbox in this situation:
function add() {
var element='<li class="ie7fix" style="width:620px;"><div class="m_elementwrapper" style="float:left;"><label class="fieldlabel" style="width:106px;float:left;padding-top:3px;" for="p1f4"><span><span class="pspan arial" style="text-align:right;font-size:14px;"><span class="ispan" xml:space="preserve"></span></span></span></label><div style="float:left;width:475px;" class="m_elementwrapper"><input type="text" style="font-family:Arial, Helvetica, sans-serif;font-size:14px;width:244px;max-width:244px;" name="' + i + '" class="fieldcontent"><div class="fielderror"></div></div></div><div style="clear:both;font-size:0;"></div></li>';
document.getElementById("addskills").innerHTML += element;
i++;
}
Yes, through DOM Manipulation:
function add() {
var tag = document.createElement('input'); // Create a `input` element,
tag.setAttribute('type', 'text'); // Set it's `type` attribute,
tag.setAttribute('name', i); // Set it's `name` attribute,
var br = document.createElement('br'); // Create a `br` element,
var y = document.getElementById("y"); // "Get" the `y` element,
y.appendChild(tag); // Append the input to `y`,
y.appendChild(br); // Append the br to `y`.
i++;
}
This doesn't trigger the browser's DOM parser like a innerHTML does, leaving everything intact.
(innerHTML forces the browser to re-parse the entire DOM, because anything could be added with innerHTML, so the browser can't predict anything, in contrast to adding a node to a element.)
Now, to add this:
<li class="ie7fix" style="width:620px;">
<div class="m_elementwrapper" style="float:left;">
<label class="fieldlabel" style="width:106px;float:left;padding-top:3px;" for="p1f4">
<span>
<span class="pspan arial" style="text-align:right;font-size:14px;">
<span class="ispan" xml:space="preserve">
</span>
</span>
</span>
</label>
<div style="float:left;width:475px;" class="m_elementwrapper">
<input type="text" style="font-family:Arial, Helvetica, sans-serif;font-size:14px;width:244px;max-width:244px;" name="' + i + '" class="fieldcontent">
<div class="fielderror">
</div>
</div>
</div>
<div style="clear:both;font-size:0;">
</div>
</li>
You'll need:
function add() {
// Create elements
var d1 = c('div'), s1 = c('span'), ip = c('input'),
d2 = c('div'), s2 = c('span'), li = c('li'),
d3 = c('div'), s3 = c('span'), la = c('label'),
d4 = c('div');
// You can "chain" `appendChild`.
// `li.appendChild(d1).appendChild(la);` is the same as `li.appendChild(d1); d1.appendChild(la);`
li.appendChild(d1).appendChild(la).appendChild(s1).appendChild(s2).appendChild(s3);
d1.appendChild(d2).appendChild(ip);
d2.appendChild(d3);
li.appendChild(d4);
setAttributes(
[li, d1, la, s2, s3, d2, ip, d3, d4],
[
{'class':"ie7fix", 'style':"width:620px;" },
{'class':"m_elementwrapper", 'style':"float:left;" },
{'class':"fieldlabel", 'style':"width:106px;float:left;padding-top:3px;", 'for':"p1f4" },
{'class':"pspan arial", 'style':"text-align:right;font-size:14px;" },
{'class':"ispan", 'xml:space':"preserve" },
{'class':"m_elementwrapper", 'style':"float:left;width:475px;" },
{'class':"fieldcontent", 'type':"text", 'style':"font-family:Arial, Helvetica, sans-serif;font-size:14px;width:244px;max-width:244px;", 'name':''+i},
{'class':"fielderror" },
{'style':"clear:both;font-size:0;" }
]
);
var br = document.createElement('br'); // Create a `br` element,
var y = document.getElementById("y"); // "Get" the `y` element,
y.appendChild(li); // Append the input to `y`,
y.appendChild(br); // Append the br to `y`.
i++;
}
// Apply a array of attributes objects {key:value,key:value} to a array of DOM elements.
function setAttributes(elements, attributes){
var el = elements.length,
al = attributes.length;
if(el === al){
for(var n = 0; n < el; n++){
var e = elements[n],
a = attributes[n];
for(var key in a){
e.setAttribute(key, a[key]);
}
}
}else{
console.error("Elements length " + el + " does not match Attributes length " + al);
}
}
// Alias for shorter code.
function c(type){
return document.createElement(type);
};
use jquery library
<html>
<head>
<script src='jquery.js' type="text/javascript"></script>
<script type="text/javascript" >
var i=0;
function add()
{
var tag = "<input type='text' name='" + i + "' /> <br/>";
var div_content=$('#y').append(tag);
i++;
}
</script>
</head>
<body>
<input type="button" id="x" value="Add" onclick="add();" />
<div id="y"></div>
</body>
</html>
I've got round this before by reading all of the values into an array before replacing the innerHTML and then writing them back again afterwards. This way you can write whatever you like into the div. Following works on all browsers that I have tried:
<html>
<head>
<script type="text/javascript" >
var i=0;
function add() {
if(i>0) {
values=new Array();
for(z=0;z<i;z++) {
values.push(document.getElementById(z).value);
}
}
var tag = '<input type="text" name="' + i + '" id="' + i + '" /> <br/>';
document.getElementById("y").innerHTML += tag;
if(i>0) {
for(z=0;z<i;z++) {
document.getElementById(z).value=values[z];
}
}
i++;
}
</script>
</head>
<body>
<input type="button" id="x" value="Add" onclick="add();" />
<div id="y"></div>
</body>
</html>

Categories

Resources