Reputation: 3
The below code is a simple form that accepts a number from the user and dispalys a circle of the radius entered in the form. Everything is working fine except that the circle vanishes as soon as I click on the submit button. How to fix this? I want the circle to be there long after I clicked on the submit button.
<title>Dynamic Vector Circle</title>
<script type="text/javascript">
var svgNS = "http://www.w3.org/2000/svg";
function createCircle()
{
var myCircle = document.createElementNS(svgNS,"circle"); //to create a circle, for rectangle use rectangle
var radius= document.getElementById("rad").value;
myCircle.setAttributeNS(null,"id","mycircle");
myCircle.setAttributeNS(null,"cx",100);
myCircle.setAttributeNS(null,"cy",100);
myCircle.setAttributeNS(null,"r",radius);
myCircle.setAttributeNS(null,"fill","black");
myCircle.setAttributeNS(null,"stroke","none");
document.getElementById("mySVG").appendChild(myCircle).innerHTML;
}
</script>
<form>
<input type="text" id="rad" placeholder="Enter radius">
<button onClick="createCircle();">Submit</button>
<svg id="mySVG" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
</svg>
</form>
Upvotes: 0
Views: 1181
Reputation: 14429
The problem is the default action for a form on a button click is to submit. To avoid submitting, you can return false
from the function bound to the button. So if you change the end of createCircle
to:
...
return false;
}
It will work as you desired. Here is the whole function:
function createCircle()
{
var myCircle = document.createElementNS(svgNS,"circle"); //to create a circle, for rectangle use rectangle
var radius= document.getElementById("rad").value;
myCircle.setAttributeNS(null,"id","mycircle");
myCircle.setAttributeNS(null,"cx",100);
myCircle.setAttributeNS(null,"cy",100);
myCircle.setAttributeNS(null,"r",radius);
myCircle.setAttributeNS(null,"fill","black");
myCircle.setAttributeNS(null,"stroke","none");
document.getElementById("mySVG").appendChild(myCircle).innerHTML;
return false;
}
JSFiddle: http://jsfiddle.net/252yLdqx/2/
Or you can change the button
to an input
with type="button"
which will not have the default behavior to submit the form:
<input type="button" id="create" value="Create"/>
JSFiddle: http://jsfiddle.net/252yLdqx/3/
Or you can change the button
to have type="button"
to override the default type="submit"
like so:
<button type="button" onClick="createCircle();">Submit</button>
Or you can not enclose the inputs within a form
tag and do whatever you would like!
Upvotes: 1