I am a beginner in this field.
I created a HTML page and on the click of some “+”/”-” buttons I am calling add() and remove() respectively from Multiple.js file to add or remove a block of code from the HTML page. But I am getting unexpected results. The files are as follow:
Multiple Group Selection.html
<!DOCTYPE HTML >
<HTML>
<HEAD>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<link rel="stylesheet" href="style.css">
<TITLE>Multiple Group Selections</TITLE>
<script src="Multiple.js" type="text/javascript"></script>
</HEAD>
<BODY BGCOLOR="#FDF5E6">
<H2 ALIGN="CENTER">Multiple Group Selections</H2>
<div id="clonedInput1" class="clonedInput">
<FIELDSET class="field">
<LEGEND ALIGN="RIGHT">
<button type="button" class = "clone" onclick={add();} >+</button>
<button type="button" class = "remove" onclick={remove();}>-</button>
</LEGEND>
Field 2A: <INPUT TYPE="TEXT" NAME="field2A" VALUE="Field A"><BR>
Field 2B: <INPUT TYPE="TEXT" NAME="field2B" VALUE="Field B"><BR>
Field 2C: <INPUT TYPE="TEXT" NAME="field2C" VALUE="Field C"><BR>
</FIELDSET>
</div>
</BODY>
</HTML>
Multiple.js:
function add(){
var regex = /^(.*)(\d)+$/i;
var cloneIndex = $(".clonedInput").length;
$("button.clone").live("click", function(){
$(this).parents(".clonedInput").clone()
.appendTo("body")
.attr("id", "clonedInput" + cloneIndex)
.find("*").each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cloneIndex);
}
});
cloneIndex++;
});
}
function remove(){
$("button.remove").live("click", function(){
$(this).parents(".clonedInput").remove();
});
}
style.css
.clone {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 12px;
font-weight: bold;
color: #00ffff;
Background-COLOR: white;
border: black;
border-style: solid;
border-width: 1px;
}
.remove{
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 12px;
font-weight: bold;
color: #00ffff;
Background-COLOR: white;
border: black;
border-style: solid;
border-width: 1px;
}
All I want is at the click of “+” button the must be appended to the . At the click of “-” button it should be removed as well. Please help me out. I am exhausted.
one place you are definitely going astray is trying to mix inline
onclickhandlers with unobtrusive jquery click handlers. Especially when they are both click handlers for same element. If you are just starting up, and going to work with jQuery the best approach would be to not use any inline javascript at all.Reading your
add()function you have to click on the add button, which then creates a jQuery clcik handler… but the click has already occured, so that handler won’t fire the first time.Stripping out the inline
onclickand unwrapping theadd()andremove()functions takes all the javascript out of the markup and makes it easier to follow.DEMO: http://jsfiddle.net/Xfg7P/
Note: fieldset should be inside form tag , there is no form tag in markup.