When ever i click the add button it makes the previous value disappear.
Example if i click add first time and enter the values in the first input boxes. and the click the add button it is making the previous values disappear from the input boxes
function addInput(event) {
var field =
'<div class="form-group"><input type="text" class="form-control" name="selected_text" placeholder="Selected Text"></div>' +
'<div class="form-group"><input type="text" class="form-control" name="selected_route_url" placeholder="Route Url for selected text"></div>' +
'<div class="form-group"><input type="text" class="form-control" name="unselected_text" placeholder="UnSelected Text"></div>' +
'<div class="form-group"><input type="text" class="form-control" name="unselected_route_url" placeholder="Route Url for unselected text"></div>'
document.getElementById('inputField').innerHTML += field;
event.preventDefault();
}
<div class="form-group">
<a class="btn btn-primary pull-left" onclick="addInput(event)">Add</a>
</div>
<div id="inputField" style="background-color:#eceff1;">
</div>
Adding elements to innerHTML reloads the entire element beforehand. That's why the values get reset.
You could try using the insertAdjacentHTML function. Then this line
document.getElementById('inputField').innerHTML += field;
will become this
document.getElementById('inputField').insertAdjacentHTML('beforeend', field);
Snippet :
function addInput(event) {
var field =
'<div class="form-group"><input type="text" class="form-control" name="selected_text" placeholder="Selected Text"></div>' +
'<div class="form-group"><input type="text" class="form-control" name="selected_route_url" placeholder="Route Url for selected text"></div>' +
'<div class="form-group"><input type="text" class="form-control" name="unselected_text" placeholder="UnSelected Text"></div>' +
'<div class="form-group"><input type="text" class="form-control" name="unselected_route_url" placeholder="Route Url for unselected text"></div>'
document.getElementById('inputField').insertAdjacentHTML('beforeend', field);
event.preventDefault();
}
<div class="form-group">
<a class="btn btn-primary pull-left" onclick="addInput(event)">Add</a>
</div>
<div id="inputField" style="background-color:#eceff1;">
</div>
Source : this similar answer
I totally converted the program to jquery and its working..
$("#link").click(function() {
var field =
'<div class="form-group"><input type="text" class="form-control" name="selected_text" placeholder="Selected Text"></div>' +
'<div class="form-group"><input type="text" class="form-control" name="selected_route_url" placeholder="Route Url for selected text"></div>' +
'<div class="form-group"><input type="text" class="form-control" name="unselected_text" placeholder="UnSelected Text"></div>' +
'<div class="form-group"><input type="text" class="form-control" name="unselected_route_url" placeholder="Route Url for unselected text"></div>';
$('#inputField').append(field);
event.preventDefault();
});
HTML
<div class="form-group">
<a class="btn btn-primary pull-left" id="link">Add</a>
</div>
<div id="inputField" style="background-color:#eceff1;">
</div>
Fiddle
Related
I have a form with a textarea & a text box in 3 cols in a row, I can add more textbox on click, add this row dynamically on click event.
I've done create this row dynamically on click event, but I can't add textbox on click in the dynamically created row.
Can anyone help me with this?
Also if anything is missing in my code & my approach to this, feel free to suggest another way to do this.
I'm using jQuery and Bootstrap.
Here is a JSFiddle
var count = 3;
$(document).on('click', '#addpv1', function () {
var appendTxt = "<div class='form-group'><input type='text' class='form-control m-b-10' placeholder='Parameter Value' name='para_ans1[]' id='para_ans" + count + "'><small class='form-text'><a href='javascript:void(0);'id='removemanager'>Remove</a></small></div>"
$("#addpvdynamic").append(appendTxt);
count++;
console.log(count)
});
$(document).on('click', '#removemanager', function (e) {
$(this).closest("div").remove();
});
var count = 3;
$(document).on('click', '#addprv1', function () {
var appendTxt = "<div class='form-group'><input type='text' class='form-control m-b-10' placeholder='Parameter Value' name='para_ans1[]' id='para_ans" + count + "'><small class='form-text'><a href='javascript:void(0);'id='removemanager'>Remove</a></small></div>"
$("#addprvdynamic").append(appendTxt);
count++;
console.log(count)
});
$(document).on('click', '#removemanager', function (e) {
$(this).closest("div").remove();
});
var count = 3;
$(document).on('click', '#addprmv1', function () {
var appendTxt = "<div class='form-group'><input type='text' class='form-control m-b-10' placeholder='Parameter Value' name='para_ans1[]' id='para_ans" + count + "'><small class='form-text'><a href='javascript:void(0);'id='removemanager'>Remove</a></small></div>"
$("#addprmvdynamic").append(appendTxt);
count++;
console.log(count)
});
$(document).on('click', '#removemanager', function (e) {
$(this).closest("div").remove();
});
$(document).ready(function () {
var max_fields = 30; //maximum input boxes allowed
var wrapper = $("#dynamic"); //Fields wrapper
var add_button = $("#addparas1"); //Add button ID
var x = 1;
var pq = 3;
var pa = 3;
var pp = 3;
$(add_button).click(function (e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
pq++;
pa++;
pp++;
var $newSelects = $('<div class="row"><div class="col-md-4"> <div class="form-group"> <textarea type="text" name="parameter[]" parsley-trigger="change" required placeholder="Parameter" class="form-control m-b-10" id="pn1" rows="2"></textarea> <input type="text" class="form-control m-b-10" required placeholder="Parameter Value" name="para_ans1[]" id="pv1"> <input type="text" class="form-control m-b-10" placeholder="Parameter Value" name="para_ans1[]" id="pv2"> <input type="text" class="form-control m-b-10" placeholder="Parameter Value" name="para_ans1[]" id="pv3"> <small>Add parameter values</small> <div id="addpvdynamic"> </div></div></div><div class="col-md-4"> <div class="form-group"> <textarea type="text" name="parameter[]" parsley-trigger="change" required placeholder="Parameter" class="form-control m-b-10" id="pn2" rows="2"></textarea> <input type="text" class="form-control m-b-10" required placeholder="Parameter Value" name="para_ans5[]" id="prv1"> <input type="text" class="form-control m-b-10" placeholder="Parameter Value" name="para_ans5[]" id="prv2"> <input type="text" class="form-control m-b-10" placeholder="Parameter Value" name="para_ans5[]" id="prv3"> <small>Add parameter values</small> <div id="addprvdynamic"> </div></div></div><div class="col-md-4"> <div class="form-group"> <textarea type="text" name="parameter[]" parsley-trigger="change" required placeholder="Parameter" class="form-control m-b-10" id="pn3" rows="2"></textarea> <input type="text" class="form-control m-b-10" required placeholder="Parameter Value" name="para_ans9[]" id="prmv1"> <input type="text" class="form-control m-b-10" placeholder="Parameter Value" name="para_ans9[]" id="prmv2"> <input type="text" class="form-control m-b-10" placeholder="Parameter Value" name="para_ans9[]" id="prmv3"> <small>Add parameter values</small> <div id="addprmvdynamic"> </div></div></div>Remove</div>')
wrapper.append($newSelects);
console.log(pq);
console.log(pa);
console.log(pp);
}
});
$(wrapper).on("click", "#remove-pararow", function (e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<div class="row">
<div class="col-md-12"><label>Create Parameters</label></div>
<div class="col-md-4">
<div class="form-group">
<textarea type="text" name="parameter[]" parsley-trigger="change" required placeholder="Parameter" class="form-control m-b-10" id="pn1" rows="2"></textarea>
<input type="text" class="form-control m-b-10" required placeholder="Parameter Value" name="para_ans1[]" id="pv1">
<input type="text" class="form-control m-b-10" placeholder="Parameter Value" name="para_ans1[]" id="pv2">
<input type="text" class="form-control m-b-10" placeholder="Parameter Value" name="para_ans1[]" id="pv3">
<small>Add parameter values</small>
<div id="addpvdynamic">
</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<textarea type="text" name="parameter[]" parsley-trigger="change" required placeholder="Parameter" class="form-control m-b-10" id="pn2" rows="2"></textarea>
<input type="text" class="form-control m-b-10" required placeholder="Parameter Value" name="para_ans5[]" id="prv1">
<input type="text" class="form-control m-b-10" placeholder="Parameter Value" name="para_ans5[]" id="prv2">
<input type="text" class="form-control m-b-10" placeholder="Parameter Value" name="para_ans5[]" id="prv3">
<small>Add parameter values</small>
<div id="addprvdynamic">
</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<textarea type="text" name="parameter[]" parsley-trigger="change" required placeholder="Parameter" class="form-control m-b-10" id="pn3" rows="2"></textarea>
<input type="text" class="form-control m-b-10" required placeholder="Parameter Value" name="para_ans9[]" id="prmv1">
<input type="text" class="form-control m-b-10" placeholder="Parameter Value" name="para_ans9[]" id="prmv2">
<input type="text" class="form-control m-b-10" placeholder="Parameter Value" name="para_ans9[]" id="prmv3">
<small>Add parameter values</small>
<div id="addprmvdynamic">
</div>
</div>
</div>
<div class="col-md-12">
Add more
</div>
</div>
<div class="" id="dynamic">
</div>
Your Code is a mess and an excellent example of so many things you can go wrong in js but still achieve a kind of working result.
I guess you need to dig a bit more into how javascript is parsed and when which code will execute in which context, for example your multiple var count definitions are sensless and as far as i can see you dont need the count at all.
But i wont dive into all those errors,
I thing what you are conceptionally doing wrong is adding dynamic things and write static code for it.
Your job would be to keep everthing generic that is generic.
To give you a quickstart, if you have the following markup:
<div class="col-md-4">
<div class="form-group">
<input name="para_ans1[]" id="para_ans1_1" type="text" class="form-control m-b-10" required placeholder="Parameter Value" >
<input name="para_ans1[]" id="para_ans1_2" type="text" class="form-control m-b-10" placeholder="Parameter Value" >
<input name="para_ans1[]" id="para_ans1_3" type="text" class="form-control m-b-10" placeholder="Parameter Value" >
<a data-id="ans1" class="addParameterValue" href="javascript:void(0);"><small>Add parameter values</small></a>
<div class="dynamic" data-id="ans1">
</div>
</div>
</div>
.....
you would only need need two generic functions for adding and removing
$(document).on('click', '.addParameterValue', function () {
var current_id = $(this).attr('data-id');
// use the actual amount of dynamic added inputs in the _current_ form-group
var current_count = $(this).parent().find('input').length;
// for readability i splitted up the appendTxt, look how everything necessary is parametrized
var inp_txt = " <input name='para_'"+current_id+"[]' type='text' class='form-control m-b-10' placeholder='Parameter Value' >";
// and the removelink has a class now too and referrences the input above
var rmv_lnk = "<a data-removeid='para_"+current_id+"_"+current_count+"' class='removemanager' href='javascript:void(0);' >Remove</a>"
var appendTxt = "<div class='form-group' id='para_"+current_id+"_"+current_count+"'>"+inp_txt+"<small class='form-text'>"+rmv_lnk+"</small></div>";
// finally add it to the current row´s dynamic container
$('.dynamic[data-id="'+current_id+'"]').append(appendTxt);
});
// and your generic remove function
$(document).on('click', '.removemanager', function () {
var remove_id = $(this).attr('data-removeid');
$('#'+remove_id).remove();
});
so you this way would be the generation and removal of input generic, to add more rows you have to adapt this pattern but further investigation is your part
I'm using spring MVC and I have a form with dynamic field.
I can create several rows inside my form and each row has 4 input, like you can see below.
When I insert a number inside the second and third input field I want to multiply them and write the result into the fourth field.
How can I do it? Maybe using jQuery?
This is my code:
var riga = 0;
function aggiungiRiga() {
riga++;
var objTo = document.getElementById('rigaOfferta')
var divtest = document.createElement("div");
divtest.setAttribute("class", "removeclass" + riga);
var rdiv = 'removeclass' + riga;
divtest.innerHTML = '<div class="col-xs-5 col-sm-5 col-md-5"><div class="form-group"> <input type="text" class="form-control" id="descrizione_"' + riga + '" name="descrizione[]" value="" placeholder="Descrizione"></div></div><div class="col-xs-2 col-sm-2 col-md-2 col-md-offset-1"><div class="form-group"><input type="number" min="0" step="0.01" class="form-control" id="prezzo_"' + riga + '" name="prezzo[]" value="" placeholder="Prezzo €"/></div></div><div class="col-xs-2 col-sm-2 col-md-2 "><div class="form-group"><input type="number" min="0" step="0.5" class="form-control" id="ore_"' + riga + '" name="ore[]" value="" placeholder="Numero Ore"/></div></div><div class="col-xs-2 col-sm-2 col-md-2 "><div class="form-group"><div class="input-group"> <input type="text" class="form-control" id="totale_"' + riga + '" name="Totale[]" value="" placeholder="0" readonly="readonly"/><div class="input-group-btn"> <button class="btn btn-danger" type="button" onclick="rimuoviRiga(' + riga + ');"> <span class="glyphicon glyphicon-minus" aria-hidden="true"></span> </button></div></div></div></div>';
objTo.appendChild(divtest)
}
function rimuoviRiga(rid) {
$('.removeclass' + rid).remove();
}
<div id="rigaOfferta">
<jsp:text/>
</div>
<div class="col-xs-5 col-sm-5 col-md-5">
<div class="form-group">
<input type="text" class="form-control" id="descrizione_0" name="descrizione[]" value="" placeholder="Descrizione" required="required" />
</div>
</div>
<div class="col-xs-2 col-sm-2 col-md-2 col-md-offset-1">
<div class="form-group">
<input type="number" min="0" step="0.01" class="form-control" id="prezzo_0" name="prezzo[]" value="" placeholder="Prezzo €" required="required" />
</div>
</div>
<div class="col-xs-2 col-sm-2 col-md-2 ">
<div class="form-group">
<input type="number" min="0" step="0.5" class="form-control" id="ore_0" name="ore[]" value="" placeholder="Numero Ore" required="required" />
</div>
</div>
<div class="col-xs-2 col-sm-2 col-md-2 ">
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" id="totale_0" name="Totale[]" value="0" placeholder="0" readonly="readonly" />
<div class="input-group-btn">
<button class="btn btn-success" type="button" onclick="aggiungiRiga();"> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> </button>
</div>
</div>
</div>
</div>
Since you are going to have multiple input fields I suggest you add a class to them, something like input-listener and then a data attribute like data-row="n" where n stands for the row number. Then you add an event listener using jQuery (since it's easier) like so:
$('.input-listener').on('change', function(){
var row = $(this).data('row'); //this way you know which row you are working with
//now that you have the row you can get all the inputs you want
var prezzo = $('#prezzo_' + row).val() || 0;
var ore = $('#ore_' + row).val() || 0;
$('#totale_' + row).val(prezzo * ore);
});
As I didn't test the code I am not sure if it works 100% but it can be a place to start. If you find any errors in the code let me know and I'll try and correct them.
The only thing is that if you add a new row you will have to rebind this event handler, so you'll have to find a way around that. Maybe add it in your aggiungiRiga() function.
Edit: I removed the e and changed it to this then I added the # to the ID of the jQuery selectors as I previously forgot to.
This is my code. In this ckeditor function not applied to append data. I am using cdn link for ckeditor in header.php file. So how can I apply.
<script>
$(document).ready(function(){
var i = 1;
$('#add').click(function()
{
$.getScript("ckeditor.js");
i++;
$('#dynamic_fields').append('<tr id="row'+i+'"><td><label class="col-md-3 control-label">Title</label><input type="text" name="title[]" id="title" placeholder="Enter Name" class="form-control name_list"><label class="col-md-3 control-label">Description</label><textarea class="ckeditor form-control" name="desc[]" id="desc" rows="6" style="width:50%;" value=""></textarea><input type="hidden" name="imageid" value=""> <label class="col-md-3 control-label">Product Image</label><div class="form-group"><input type="file" class="form-control" name="userfile[]" multiple="multiple"></div></td><td><button name="remove" id="'+i+'" class="btn btn-danger btn-remove" >X</button></td></tr>');
});
$(document).on('click', '.btn-remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
});
</script>
It seems to be working. I have changed the place of your i++ to after the append and used the CDN for that js code and appended a counter to you ID because you can only have. I have tried this on my local machine and works without any errors. I am guessing this is what you wanted to do.
var i = 1;
$('#add').click(function() {
$('#dynamic_fields').append('<tr id="row' + i + '"><td><label class="col-md-3 control-label">Title</label><input type="text" name="title[]" id="title" placeholder="Enter Name" class="form-control name_list"><label class="col-md-3 control-label">Description</label><textarea class="ckeditor form-control" name="desc'+i+'" id="desc'+i+'" rows="6" style="width:50%;" value=""></textarea><input type="hidden" name="imageid" value=""> <label class="col-md-3 control-label">Product Image</label><div class="form-group"><input type="file" class="form-control" name="userfile[]" multiple="multiple"></div></td><td><button name="remove" id="' + i + '" class="btn btn-danger btn-remove" >X</button></td></tr>');
CKEDITOR.replace('desc'+i);
i++;
});
$(document).on('click', '.btn-remove', function() {
var button_id = $(this).attr("id");
$('#row' + button_id + '').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.ckeditor.com/4.7.2/basic/ckeditor.js"></script>
<button id="add">ADD</button>
<div id="dynamic_fields"></div>
I am working on a project where user can add records, on the add record page user has 1 html form with 10 fields in it. And a button to add more forms with all the 10 fields.
Now, 4 out of 10 fields has auto complete feature of bootstrap typeahead, and the typeahead suggestions works on the default 1st form.
The problem comes when user adds new form on a add-more button click, the form in actually prepared using jquery below:
var wrapper = '<div class="span6"><input type="hidden" name="count[]" value="' + count + '"/><div class="widget-box"><div class="widget-title"> <span class="fa"> <i class="fa fa-info-circle"></i> </span> <h5>Add Parent - ' + count + '</h5><button type="button" class="btn btn-mini btn-danger" id="remove">Remove</button><button type="button" class="btn btn-mini btn-success" id="add">Add</button></div><div class="widget-content nopadding">';
wrapper += '<div class="control-group"> <label class="control-label">First Name</label> <div class="controls"> <input class="span10" type="text" name="firstname[]" id="firstname"> </div></div>';
wrapper += '<div class="control-group"> <label class="control-label">Last Name</label> <div class="controls"> <input class="span10" type="text" name="lastname[]" id="lastname"> </div></div>';
wrapper += '<div class="control-group"> <label class="control-label">Gender</label> <div class="controls"> <select class="span10" name="gender[]" id="gender"> <option value="Male">Male</option> <option value="Female">Female</option> </select> </div></div>';
wrapper += '<div class="control-group"> <label class="control-label">Email Address</label> <div class="controls"> <input class="span10" type="email" name="email[]" id="email"> </div></div>';
wrapper += '<div class="control-group"> <label class="control-label">Password</label> <div class="controls"> <input class="span10" type="password" name="password[]" id="password" autocomplete="new-password"> </div></div>';
//typeahead input comes here.......
wrapper += '</div></div></div>';
$current_row.append(wrapper);
the above code does not include the typeahead inputs which I had previously like below:
wrapper += '<div class="control-group">
<label class="control-label">Hobby</label>
<div class="controls">
<input type="text" class="typeahead span10" name="hobby[]" id="hobby" data-provide="typeahead">
<input type="hidden" name="hobbyid[]" id="hobbyid" value=""/>
</div>
</div>';
now, when users click on add more fields, then the form is actually get added with all the input fields, but here the bootstrap typeahead didn't worked.
so I tried the below code after reading and searching on GOOGLE.
var hobby_typeahead = $('<input type="text" class="typeahead span10" name="hobby[]" id="hobby" data-provide="typeahead"> <input type="hidden" name="hobbyid[]" id="hobbyid" value=""/>');
$current_row.append(hobby_typeahead);
after this, my dynamic fields started showing me the bootstrap typeahead suggestions..
But, the main problem I am getting is to render the input fields under the bootstrap div ex: control-group, control-label and controls div.
Actually I am looking something like below:
wrapper += '<div class="control-group">
<label class="control-label">Hobby</label>
<div class="controls">
'+ hobby_typeahead +'
<input type="hidden" name="hobbyid[]" id="hobbyid" value=""/>
</div>
</div>';
I understand this will print object [Object] etc..
I would like to know, how I could attach it within the div's, I could do it by declaring something like this:
$control_group = $('<div class="control-group"></div>');
$control_label = $('<label class="control-label">Hobby</label>');
$controls = $('<div class="controls"></div>');
$controls.append($hobby_typeahead);
$control_group.append($control_label);
$control_group.append($controls);
$current_row.append($control_group);
But as I have 4 fields with typeahead suggestion and 6 normal fields, is there any smart way to do it, I don't want to go the long way above.
Thanks in advance, any help or suggestion would be really great help for me.
this is how I created it, to fit in my eyes, this is not the complete solution to fit in my requirement
I have a different and fully working copy with me, I thought posting it here, will add helpful resource for others.
var $span6 = $('<div class="span6"></div>');
var $hidden_count = $('<input type="hidden" name="count[]" value="' + count + '"/>');
var $widget_box = $('<div class="widget-box"><div class="widget-title"> <span class="fa"> <i class="fa fa-info-circle"></i> </span> <h5>Add User - ' + count + '</h5><button type="button" class="btn btn-mini btn-danger" id="remove">Remove</button><button type="button" class="btn btn-mini btn-success" id="add">Add</button></div>');
var $widget_content = $('<div class="widget-content nopadding"></div>');
$span6.append($hidden_count);
$span6.append($widget_box);
var $inputs = {
'First Name':'<input class="span10" type="text" name="firstname[]" id="firstname">',
'Last Name':'<input class="span10" type="text" name="lastname[]" id="lastname">',
'Gender':'<select class="span10" name="gender[]" id="gender"> <option value="Male">Male</option> <option value="Female">Female</option> </select>',
'Email Address':'<input class="span10" type="email" name="email[]" id="email">',
'Password':'<input class="span10" type="password" name="password[]" id="password" autocomplete="new-password">',
'Hobbies':'<input type="text" class="typeahead span10" name="hobby[]" id="hobby" data-provide="typeahead">'
};
for(var $k in $inputs){
var $control_group = $('<div class="control-group"></div>');
var $control_label = $('<label class="control-label">'+$k+'</label>');
var $controls = $('<div class="controls"></div>');
var $input = $($inputs[$k]);
$input.typeahead({
source: function (query, process) {
return $.get('get-hobbies?src=typeahead&q='+query, function (data) {
return process(JSON.parse(data));
});
}
});
$controls.append($input);
$control_group.append($control_label);
$control_group.append($controls);
$widget_content.append($control_group);
}
$span6.append($widget_content);
$current_row.append($span6);
I have a bit of javascript that I want to use to allow the user to enter in infinite options and infinite image URLS.
I have made a jsFiddle
here is the html:
<div class="container-fluid body">
<div class="admin-box">
<form action="http://localhost/MyZone/public_html/index.php/create_option/2" class="form-horizontal" method="post" accept-charset="utf-8"><div style="display:none">
<input type="hidden" name="ci_csrf_token" value="001b4b051689692edec29d09b9837f3a">
</div> <fieldset>
<legend>Option Title</legend>
<div class="control-group">
<label class="control-label" for="Option title">title</label>
<div class="controls">
<input type="text" name="name" id="name" class="span6">
</div>
</div>
<div class="admin-box" id="option_information">
<fieldset>
<legend>Option information</legend>
<div class="control-group">
<label class="control-label" for="value">Description</label>
<div class="controls">
<input type="text" name="value" id="value" class="span6">
</div>
</div>
<div class="control-group">
<label class="control-label" for="cost_including_vat">Cost including VAT</label>
<div class="controls">
<input type="text" name="cost_including_vat" id="cost_including_vat" class="span6">
</div>
</div>
<div class="control-group">
<label class="control-label" for="vat_of_cost">VAT of cost</label>
<div class="controls">
<input type="text" name="vat_of_cost" id="vat_of_cost" class="span6">
</div>
</div>
<div class="control-group">
<label class="control-label" for="sale_price_including_vat">Sale price including vat</label>
<div class="controls">
<input type="text" name="sale_price_including_vat" id="sale_price_including_vat" class="span6">
</div>
</div>
<div class="control-group">
<label class="control-label" for="vat_of_sale_price">VAT of sale price</label>
<div class="controls">
<input type="text" name="vat_of_sale_price" id="vat_of_sale_price" class="span6">
</div>
</div>
<div id="image_addition">
</div>
<div class="control-group">
<button class="controls" id="add_image" value="Add image">Add Image</button>
</div>
</fieldset>
</div>
<div class="control-group">
<button class="controls" id="add_option" value="Add option">Add option</button>
</div>
<div class="form-actions">
<br>
<input type="submit" name="save" class="btn btn-primary" value="Create option">
or Cancel </div>
</fieldset>
</form>
here is the Javascript
var counter_image = 1;
$('#add_image').click(function()
{
var newrow = '<div class="control-group">'+
'<label class="control-label" for="image_name'+counter_image+'">Image '+counter_image+' name</label>'+
'<div class="controls">' +
'<input type="text" name="image_name'+counter_image+'" id="image_name'+counter_image+'" class="span6" />'+
'</div>' +
'</div>' +
'<div class="control-group">' +
'<label class="control-label" for="image_description'+counter_image+'">Image '+counter_image+' message</label>' +
'<div class="controls">' +
'<input type="text" name="image_description'+counter_image+'" id="image_description'+counter_image+'" class="span6" />' +
'</div>' +
'</div>' +
'<div class="control-group">' +
'<label class="control-label" for="image_url'+counter_image+'">Image '+counter_image+' URL</label>' +
'<div class="controls">' +
'<input type="url" name="image_url'+counter_image+'" id="image_url'+counter_image+'" class="span6" />' +
'</div>' +
'</div>';
$('#image_addition').append(newrow);
counter_image++;
return false;
});
var counter_option = 1;
$('#add_option').click(function()
{
var newrow = '<fieldset>' +
'<legend>Option information</legend>'+
'<div class="control-group">'+
'<label class="control-label" for="value">Description</label>'+
'<div class="controls">'+
'<input type="text" name="value" id="value" class="span6" />'+
'</div>'+
'</div>'+
'<div class="control-group">'+
'<label class="control-label" for="cost_including_vat">Cost including VAT</label>'+
'<div class="controls">'+
'<input type="text" name="cost_including_vat" id="cost_including_vat" class="span6" />'+
'</div>'+
'</div>'+
'<div class="control-group">'+
'<label class="control-label" for="vat_of_cost">VAT of cost</label>'+
'<div class="controls">'+
'<input type="text" name="vat_of_cost" id="vat_of_cost" class="span6" />'+
'</div>'+
'</div>'+
'<div class="control-group">'+
'<label class="control-label" for="sale_price_including_vat">Sale price including vat</label>'+
'<div class="controls">'+
'<input type="text" name="sale_price_including_vat" id="sale_price_including_vat" class="span6" />'+
'</div>'+
'</div>'+
'<div class="control-group">'+
'<label class="control-label" for="vat_of_sale_price">VAT of sale price</label>'+
'<div class="controls">'+
'<input type="text" name="vat_of_sale_price" id="vat_of_sale_price" class="span6" />'+
'</div>'+
'</div>'+
'<div id="image_addition">'+
'</div>'+
'<div class="control-group">'+
'<button class="controls" id="add_option" value="Add image">Add Image</button>'+
'</div>'+
'</fieldset>';
$('#option_information').append(newrow);
counter_option++;
return false;
});
So basically I can keep adding options fine and on the FIRST option I can add infinite images, however, on any of the preceding options (the ones generated) when I press 'Add image' it just reloads the page making me loose everything generated so far?
The idea is that I want to allow someone to enter in as many options and images per option as they want to add then eventually add them to a database.
Thanks
In your callback function you just have to prevent the default action like this:
$("#whatever").click(function(event) {
event.preventDefault();
...
});
Also, from looking at your code, I think you might benefit from looking into a javascript templating engine. They make stuff like this super easy. http://underscorejs.org has a good one wrapped in, and http://handlebarsjs.com/ is also pretty sweet.
Change:
<button class="controls" id="add_option" value="Add option">
To:
<button type="button" class="controls" id="add_option" value="Add option">
To prevent the button from submitting the form. See the type attribute for more information.
You can also cancel the form submission within your click handler:
$('#add_option').click(function(e)
{
e.preventDefault(); // Cancel form submit
// Rest of code
});
You'll also, of course, need to update your injected HTML <button> tag as well. One issue you'll run into is your .click handler will not bind to the new buttons you create. One way around that is to use the .live binding instead:
$('#add_option').live('click', function()
{
// Old code here
});
Here's an updated Fiddle.
Advice: I would use a class instead of an id, since using the same id more than once is not recommended. Basically, change:
<button type="button" class="controls" id="add_option" value="Add option">
to:
<button type="button" class="controls add_option" value="Add option">
And bind it with:
$('.add_option').live('click', function()
If your UI gets too complicated, you might want to check into a MVVM type pattern such as Knockout.js, which can do all this stuff very easily by binding everything to a model. You would just add an item to a model and it would create the new UI automatically.
You are creating multiple elements with the id "add_option". That's not proper. It might work in some browsers.
Further, you are attaching a 'click' handler to that button, when its the one in the original HTML.
But when you add more HTML and another button, you don't put a click handler on it. Its something you would need to do right after you call .append() with the new HTML.
The normal job of a button is to submit the form it is in. Submitting form will send stuff to the server and the server will send content back that will be displayed.
HINT:
What you may want is a way to submit the form content via ajax within javascript. This is not for the faint of heart. There is a lot of conflicting information on the web because recent HTML5 changes have made it pretty easy but all the old info is still floating around. You will need to find out about FormData which is a javascript object class and pass that to jQuery's $.ajax() as the data. Be sure to look up examples of that to get the other properties right for the ajax call.