I want to add $(this) value when the button is clicked.
uhm. let me show you my code below first.
$("#filenameList button").click(function(){
$(this).parent().remove();
});
$("#file").change(function(){
$("#filenameList div.notyet").remove();
for(var i = 0, len = this.files.length; i < len; i++){
var file = this.files[i];
var fr = new FileReader();
fr.onload = (function (file) {
return function(e) {
var div = document.createElement("div");
$(div).addClass("notyet").css({
margin : "30px"
,position : "relative"
});
//var html = ['<input type="hidden" name="screenshots_filename[]" value="' + file.name + '">'
var html = ['<img src="" width="100%">'
,'<input type="hidden" name="">'
,'<button type="button" class="close img-close" aria-label="Close"><span aria-hidden="true">×</span></button>'
].join("");
$(div).append(html);
$(div).find("button").click(function(){
$(this).parent().remove();
});
$(div).find("img").attr("src", e.target.result);
$("#filenameList").append(div);
}
})(file);
fr.readAsDataURL(file);
}
});
All i want to do is verify which element is removed by clicking the button so that i add the value to name attribute that is hidden above html variable.
How can i do this?
<div class="col-xs-4 vcenter from-group">
<h1>test</h1>
<input id="file" type="file" name="inputScreenshots[]" accept="image/*" multiple>
<div id="filenameList" style="width : 400px">
<?
$str = $screenshot_urls;
$arr = explode("+", $str);
foreach ($arr as $filename) {
?>
<div style="margin : 30px; position :relative;">
<input type="hidden" name="screenshots_filename[]" value="<?=$filename?>">
<img src="<?="http://cspmedia.net:3001/gp_images/ames/".$filename?>" width="100%">
<button type="button" class="close img-close" aria-label="Close"><span aria-hidden="true">×</span></button>
<input type="hidden" name=""> // TODO HERE ##
</div>
<? } ?>
</div>
okay here is the html code. and i really sorry. i was so confused.
I move the todo to bottom code.
I want to know the list of element which is clicked by the button.
I figured out like this. Im new in php so i totally confused about client and server because they are all in just one page.
Anyway this is the code what i wanted. sorry guys.
$("#filenameList button").click(function(){
var targetDom = document.getElementById( "filenameList" );
var targetInput = document.createElement("input");
targetInput.setAttribute("name", "del_img[]" );
targetInput.setAttribute("type","hidden");
targetDom.appendChild(targetInput);
//alert(targetInput.getAttribute("name"));
var filename = $(this).parent().find("input[name='screenshots_filename[]']").val();
alert(filename);
targetInput.setAttribute("value", filename);
$(this).parent().remove();
});
Why i wrote this code is submitting the value and deleting the file in the server.
if (isset($_POST["del_img"])) {
echo "<br/>del_img[] isset";
$tmp = $_POST["del_img"];
// TODO : delete images in server
foreach ($tmp as $value) {
echo "<br/> Unlnk image ::: ".$value;
unlink("http://cspmedia.net:3001/gp_images/games/".$value);
}
}
$('Selector( 'whose value you want to set' )').attr('value',$(this).val());
For example like given below
$('input[type="hidden"]').attr('value',$(this).val());
$(div).find("button").click(function(){
$(this).parent().remove();
// TODO : I want add $(this).val() to input name attribute
});
But note that here you will set the value of button which will gonna clicked.
because in you code $(this) will refer to button as it is picking the that by
.find("button")
Not certain if requirement is to set name at <input type="hidden" name=""> to current file , or previously user selected file , before current change event ?
Solution below attempts to set name at <input type="hidden" name=""> within html array to current file.name
$("#filenameList button").click(function(){
$(this).parent().remove();
});
$("#file").change(function(){
$("#filenameList div.notyet").remove();
for(var i = 0, len = this.files.length; i < len; i++){
var file = this.files[i];
var fr = new FileReader();
fr.onload = (function (file) {
return function(e) {
var div = document.createElement("div");
$(div).addClass("notyet").css({
margin : "30px"
,position : "relative"
});
//var html = ['<input type="hidden" name="screenshots_filename[]" value="' + file.name + '">'
var html = ['<img src="" width="100%">'
,'<input type="hidden" name="'+file.name+'">'
,'<button type="button" class="close img-close" aria-label="Close"><span aria-hidden="true">×</span></button>'
].join("");
$(div).append(html);
$(div).find("button").click(function(){
$(this).parent().remove();
});
$(div).find("img").attr("src", e.target.result);
$("#filenameList").append(div);
}
})(file);
fr.readAsDataURL(file);
}
});
Related
As seen in the image I have index.html (it has a index.js) that loads multiple images using a json image array and on edit icon click I need to send the clicked image info to another site let's say: index1.html (it has a index1.js) so it would load on an editor using canvas...
image
I can't seem to get it pass with session or local storage because it gives me the last result of the index instead of a specific index of the array related to the click event. I don't know if I need to use a server to upload all the images or not, currently I don't use a server.
var k=0;
var filesArr = [];
var newArr = [];
if (input.files && input.files[0]) {
$(input.files).each(function () {
var reader = new FileReader();
reader.readAsDataURL(this);
reader.onload = function (e) {
filesArr.push(e.target.result);
newArr = JSON.parse(JSON.stringify(filesArr));
var jsonedImgArr = [];
var file = {};
// manually create a new file obj for each File in the FileList
for (var i = 0; i < newArr.length; i++) {
var source = newArr[i];
var name = input.files[i].name;
var id = i;
file = {
'id': id,
'name': name,
'src': source
}
//add the file obj to your array
jsonedImgArr.push(file);
}//$("#previewImg") is an id="" inside a div
$("#previewImg").append("
<div class='container1'>
<img class='img-fluid1 img1 ' src=" + jsonedImgArr[k]['src'] + ">
<p class='title'>" + jsonedImgArr[k]['name'] + "</p>
<div class='overlay'></div>
<button type='button' class='responsive-width' data-toggle='modal' data-target='#myModal'>
<i style='color:white;' class='button far fa-edit'></i>
</button>
<div class='modal fade' id='myModal'>
<div class='modal-dialog modal-xl'>
<div class='modal-content'><div class='modal-header'>
<button type='button' class='close responsive-width' data-dismiss='modal'>×</button>
</div>
<div class='modal-body'>
<iframe id='frame' style='width:100%;height:100%;' src='index1.html'></iframe>
</div>
<div class='modal-footer'>
<button type='button' class='btn btn-secondary responsive-width' data-dismiss='modal'>Close</button>
</div>
</div></div></div>");
k++;
}
//the src should be instead of the '' down here
fabric.Image.fromURL('', function (oImg) {
add(oImg,75,98);
});
I need to get the index and the array to the file "index1.js" so I could edit save and update the existing json array on "index.js" as it will appear on "index.html" as seen in the image.
I have the following code which displays the image previews. But when I select new images or say when I change images then on change the previously selected images preview should be removed and only new images should show up in the preview. But its not happening. Currently, if I select 3 images then the preview shows up. But when I select more images then the preview adds up to the previous images.
Also please tell me how can I get values of <img id="imgs"> to insert in the database rather than the values from <input type="file" name="files[]" multiple="multiple" id="file-5">. Please help.
HTML:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="newstatus" runat="server" enctype="multipart/form-data">
<textarea name="status" class="textarea newstatuscontent" placeholder="What are you thinking?"></textarea>
<input type="file" name="files[]" multiple="multiple" id="file-5"><br />
<img id="imgs"><br />
<input type="submit" name="post" value="Post" class="post-btn" id="submit" />
</form>
Jquery:
$(document).ready(function(){
$("#file-5").on('change',function() {
var fileList = this.files;
for(var i = 0; i < fileList.length; i++){
var t = window.URL || window.webkitURL;
var objectUrl = t.createObjectURL(fileList[i]);
$('.removeimg').fadeIn();
$('#imgs').append('<!--span class="img_'+i+'" onclick="del('+i+')" style="cursor:pointer; margin-right: 3px;"><b>x</b></span--><img class="img_'+i+'" src="' + objectUrl + '" width="150" height="150" style="margin-right: 3px;">');
j = i+1;
if(j % 3 == 0)
{
$('#imgs').append('<br>');
}
}
});
});
Ajax code used in insert the data into the database:
$(function() {
$("#submit").click(function() {
$(this).val("Please wait...");
var textcontent = $(".newstatuscontent").val();
/*if(media == ''){*/
if(textcontent == ''){
$('.cap_status').html("Status cannot be empty. Please write something.").addClass('cap_status_error').fadeIn(500).delay(3000).fadeOut(500);
$("#submit").val("Post");
}else{
/*}else{*/
$.ajax({
type: "POST",
url: "post-status.php",
data: {content:textcontent},
cache: true,
success: function(html){
$("#shownewstatus").after(html);
$(".newstatuscontent").val('');
$("#submit").val("Post");
}
});
}
//}
return false;
});
});
The img element is not a container. You should use a div element instead like this:
<div id="imgs"></div>
Then to have all images removed whenever the user selects new images, simple use jQuery empty (before the for loop) on your container div#imgs to remove all the images it contains:
$('#imgs').empty();
A full working example:
function del(index) {
$('div.img_'+index).remove();
updateFiles();
}
function updateFiles() {
var fileIndexes = $('#imgs > div').map(function() {
return $(this).data('index');
}).get().join(",");
$('#files_selected').val(fileIndexes);
}
$(document).ready(function() {
$("#file-5").on('change', function() {
var fileList = this.files;
$('#imgs').empty();
for (var i = 0; i < fileList.length; i++) {
var t = window.URL || window.webkitURL;
var objectUrl = t.createObjectURL(fileList[i]);
$('.removeimg').fadeIn();
$('#imgs').append('<div data-index="' + i + '" class="img_' + i + '"><span class="img_' + i + '" onclick="del(' + i + ')" style="cursor:pointer; margin-right: 3px;"><b>x</b></span><img class="img_' + i + '" src="' + objectUrl + '" width="150" height="150" style="margin-right: 3px;"></div>');
j = i + 1;
if (j % 3 == 0) {
$('#imgs').append('<br>');
}
}
updateFiles();
});
});
#imgs > div {
display:inline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="newstatus" runat="server" enctype="multipart/form-data">
<textarea name="status" class="textarea newstatuscontent" placeholder="What are you thinking?"></textarea>
<input type="file" name="files[]" multiple="multiple" id="file-5"><br />
<div id="imgs"></div>
<input type="submit" name="post" value="Post" class="post-btn" id="submit" />
<input type="hidden" name="files_selected" id="files_selected" />
</form>
EDIT
The javascript files property is readonly, so to do what you want, you'll have to have a hidden input and update it with a string of comma separated indexes that point to the selected files array in PHP. Also, if you add display: inline CSS rule, then you'll have the divs on the same line and break every 3 images as your code works. See my updated snippet code for the whole working example.
To see the exact out put, use the following PHP code:
<pre><?php
print_r($_POST);
print_r(explode(',', $_POST['files_selected']));
?></pre>
<pre><?php
print_r($_FILES);
?></pre>
OUTPUT
Array
(
[status] =>
[post] => Post
[files_selected] => 0,2
)
Array
(
[0] => 0
[1] => 2
)
Array
(
[files] => Array
(
[name] => Array
(
[0] => 1c.jpg
[1] => 1e.jpg
[2] => 2c.jpg
)
[type] => Array
(
[0] => image/jpeg
[1] => image/jpeg
[2] => image/jpeg
)
[tmp_name] => Array
(
[0] => /var/www/clients/client3/web35/tmp/phpzkmzlf
[1] => /var/www/clients/client3/web35/tmp/php9HuwoF
[2] => /var/www/clients/client3/web35/tmp/phpZiOur5
)
[error] => Array
(
[0] => 0
[1] => 0
[2] => 0
)
[size] => Array
(
[0] => 11384
[1] => 7348
[2] => 12700
)
)
)
You have all selected files indexes to an array by making this call $selected = explode(',', $_POST['files_selected']
Some edit you need to do in your code. Those are:
1.> Under <form> tag remove the <img> tag and add this <div id="imgs"></div> tag.
2.> Inside your onchange function() at from first line
$(document).ready(function(){
$("#file-5").on('change',function() {
var length= $('[id^=image]').length;
for(var i = 0; i < length; i++){
var imgTag = document.getElementById("image" + i);
imgTag .parentNode.removeChild(imgTag );
}
var fileList = this.files;
for(var i = 0; i < fileList.length; i++){
var t = window.URL || window.webkitURL;
var objectUrl = t.createObjectURL(fileList[i]);
$('.removeimg').fadeIn();
$('#imgs').append('<span id="image'+i+'" class="img_'+i+'" onclick="del('+i+')" style="cursor:pointer; margin-right: 3px;"><b>x</b><img class="img_'+i+'" src="' + objectUrl + '" width="150" height="150" style="margin-right: 3px;"/></span>');
j = i+1;
if(j % 3 == 0)
{
$('#imgs').append('<br>');
}
}
});
});
I am adding the tag inside the .
The span tags will have id like "image1","image2",...
And whenever any changes occur in the selection then the old image are deleted and new images are added.
You can edit your del() function to take input as the id of the span tag and whenever u click on the tag it should call the del('image1') deleted the corresponding span tag which contain the clicked image.
You should edit the line:
$('#imgs').append('
I tried for hours but could not find any solution.
Simplified my code looks like following.
PHP :
foreach($db->query("SELECT id FROM news ORDER BY position ASC") as $row)
{
...
<input type="text" class="_title" >
Search: <input type="file" class="_file" >
<input type='button' class="_submit" value='Save' >
...
}
?>
JS :
$(document).ready(function(){
$("._submit").click(function(){
?? var _title = document.getElementById('_title'),
?? _file = document.getElementById('_file');
var data = new FormData();
data.append('SelectedFile', _file.files[0]);
data.append('title', _title.value);
...
</script>
I don't know how to get the data by class. By ID it is working, but i can't use IDs, because there would be several same IDs because of the foreach loop.
Tried this as well without success:
var _file = document.getElementsByClassName('_file');
I hope somebody can help me.
Misch
You can wrap your elements in container div like
<?php
foreach($db->query("SELECT id FROM news ORDER BY position ASC") as $row)
{
...
<div class='container'>
<input type="text" class="_title" >
Search: <input type="file" class="_file" >
<input type='button' class="_submit" value='Save' >
</div>
}
?>
Then use .closest() to traverse up the container. After wards you simply use find to get the desired elements.
<script>
$(document).ready(function(){
$("._submit").click(function(){
var container = $(this).closest('.container');
var _title = container.find('._title'),
var _file = container.find('._file')[0];
var data = new FormData();
data.append('SelectedFile', _file.files[0]);
data.append('title', _title.value);
//Rest of your code
});
});
</script>
Since you're using jquery you could use .each() function and class selector . to loop through all the element with same class :
$('.class').each(function(){
var input_value = $(this).val();
})
Since you have more than one field with class _title and _file you should pass them as array to Formdata() using array signs [] :
var data = new FormData();
$('._file').each(function(){
var _file = $(this).val();
data.append('SelectedFile[]', _file.files[0]);
})
$('._title').each(function(){
var _title = $(this).val();
data.append('title[]', _title);
})
Hope this helps.
One more thing you can do a bit same as #satpal
Wrap your code in a div element.
PHP:
foreach($db->query("SELECT id FROM news ORDER BY position ASC") as $row)
{
...
<div> <!-- wrapper -->
<input type="text" class="_title" >
Search: <input type="file" class="_file" >
<input type='button' class="_submit" value='Save' >
</div>
}
?>
Then try following code.
JS:
$("._submit").click(function(){
var title = $(this).siblings('._title').val();
var file = $(this).siblings('._file')[0].files[0];
var data = new FormData();
data.append('SelectedFile',file);
data.append('title', title);
});
The above code makes use of .siblings() function
I'm attempting to create a page where the user is able to customize the form to their needs by adding in extra divs or nested divs (as many layers deep as they'd like). Within each div I'd like to have text input and a button which adds another div on the same level and a button that nests a div within it. Both divs should again have a text input and a button which does the same thing.
However I've gotten a bit stuck. When I attempt to create a nested div I always end up adding it at the very bottom instead of inside its parent.
<html>
<script type="text/javascript">
var counter = 1;
function addNode() {
var newDiv = document.createElement('div');
counter++;
newDiv.innerHTML = "Entry " + counter + " <br><input type='text' name='myInputs'>";
document.getElementById("dynamicInput").appendChild(newDiv);
var newButton = document.createElement('button');
newButton.type = "button";
newButton.onclick = addSub;
document.getElementById("dynamicInput").appendChild(newButton);
}
function addSub() {
var newDiv = document.createElement('div');
counter++;
newDiv.innerHTML = "Entry " + counter + " <br><input type='text' name='myInputs' style='margin:10px'>";
document.getElementById("subInput").appendChild(newDiv);
}
</script>
<form class="form" method="POST">
<div id="dynamicInput" name="dynamicInput" multiple="multiple">
Entry 1<br><input type="text" name="myInputs">
<div id="subInput" name="subInput" multiple="multiple">
<input type="button" value="add nested" onClick="addSub();">
</div>
</div>
<input type="button" value="Add another text input" onClick="addNode();" >
<input type="submit" value = "answer" multiple="multiple"/>
</form>
</html>
Here is a complete solution for you keep in mind that if you need to bind extra events on your produced inputs and buttons you ll have to do it inside the functions addNode or addSub as i did for the click event on the buttons.
Working example : https://jsfiddle.net/r70wqav7/
var counter = 1;
function addNode(element) {
counter++;
var new_entry="Entry "+counter+"<br><input type='text' name='myInputs'><br>";
element.insertAdjacentHTML("beforebegin",new_entry);
}
function addSub(element) {
counter++;
var new_sub_entry="<div class='block'>"
+"Entry "+counter+"<br><input type='text' name='myInputs'><br>"
+"<div class='buttons'>"
+"<input class='add_sub_button' type='button' value='add nested'>"
+"<input class='add_button' type='button' value='Add another text input' >"
+"</div>"
+"</div><br />"
+"</div>";
element.insertAdjacentHTML("beforebegin",new_sub_entry);
var blocks=element.parentNode.getElementsByClassName("block");
blocks[blocks.length-1].getElementsByClassName("add_sub_button")[0].addEventListener("click",function(){
addSub(this.parentNode);
});
blocks[blocks.length-1].getElementsByClassName("add_button")[0].addEventListener("click",function(){
addNode(this.parentNode);
});
}
var buttons=document.getElementsByClassName("add_button");
for(i=0;i<buttons.length;i++){
buttons[i].addEventListener("click",function(){
addNode(this.parentNode);
});
}
var nested_buttons=document.getElementsByClassName("add_sub_button");
for(i=0;i<buttons.length;i++){
nested_buttons[i].addEventListener("click",function(){
addSub(this.parentNode);
});
}
div.block{
padding:5px;
border:2px solid #000;
}
<form class="form" method="POST">
<div class="block">
Entry 1<br><input type="text" name="myInputs"><br>
<div class="buttons">
<input class="add_sub_button" type="button" value="add nested">
<input class="add_button" type="button" value="Add another text input" >
</div>
</div><br />
<input type="submit" value = "answer" multiple="multiple"/>
</form>
EDITED : There was an error binding the click event on nested items updated to work properly
Here's another worked example which makes use of the concepts I mentioned in an earlier comment. I've moved the Add-Item button outside the form and altered the method used to determine the text for each new item added. Rather than keep a counter, I count the number of existing items in the document and increment it, using this as as the n in the string "Entry n"
I should have added(appended) the sub-item before the button that creates new ones, but was lazy and just called appendChild on the button after the other new element was added - the end result is the same, but it's less efficient and will cause slower performance/shorter battery life.
I was going to use the .cloneNode method of the .dynamicInput div, when clicking "Add new item", however this will copy all subitems of the chosen target and we still need to call addEventListener for the button anyway, so I've opted to simply create each input-item added with the "Add new item" button instead.
<!doctype html>
<html>
<head>
<script>
"use strict";
function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}
function allByClass(className,parent){return (parent == undefined ? document : parent).getElementsByClassName(className);}
function allByTag(tagName,parent){return (parent == undefined ? document : parent).getElementsByTagName(tagName);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt)
{
byId('addNewInputBtn').addEventListener('click', myAddNewItem, false);
var subItemBtn = document.querySelectorAll('.dynamicInput button')[0];
subItemBtn.addEventListener('click', myAddSubItem, false);
}
function makeNewItem(titleStr)
{
var div = newEl('div');
div.className = 'dynamicInput';
var heading = newEl('h3');
heading.innerText = titleStr;
div.appendChild(heading);
var input = newEl('input');
div.appendChild(input);
var btn = newEl('button');
btn.innerText = 'Add sub-items';
btn.addEventListener('click', myAddSubItem, false);
div.appendChild(btn);
return div;
}
function myAddNewItem(evt)
{
var numAlreadyExisting = allByClass('dynamicInput').length; // count number of divs with className = dynamicInput
var newNum = numAlreadyExisting + 1;
var newInputPanel = makeNewItem('Entry ' + newNum);
byId('myForm').appendChild(newInputPanel);
return false;
}
function myAddSubItem(evt)
{
evt.preventDefault(); // stops this button causing the form to be submitted
var clickedBtn = this;
var inputDiv = clickedBtn.parentNode;
var newInput = newEl('input');
inputDiv.appendChild(newInput);
inputDiv.appendChild(clickedBtn);
}
</script>
</head>
<body>
<form id='myForm'>
<div class='dynamicInput'>
<h3>Entry 1</h3>
<input type='text'/><button>Add sub-item</button>
</div>
</form>
<button id='addNewInputBtn'>Add new item</button>
</body>
</html>
I have a code like this...
<html>
<head>
<title>test</title>
<script type="text/javascript">
var counter = 2;
var idCounter= 3;
function addNew() {
if(counter<=5){
// Get the main Div in which all the other divs will be added
var mainContainer = document.getElementById('mainContainer');
// Create a new div for holding text and button input elements
var newDiv = document.createElement('div');
newDiv.id='divs'+counter;
// Create a new text input
var newText = document.createElement('input');
var newText1 = document.createElement('input');
newText.type = "input";
newText.id="ans"+(idCounter);
idCounter++;
newText1.type = "input";
newText1.id="ans"+(idCounter);
idCounter++;
// newText.value = counter;
// Create a new button input
var newDelButton = document.createElement('input');
newDelButton.type = "button";
newDelButton.value = "Remove";
// Append new text input to the newDiv
newDiv.appendChild(newText);
newDiv.appendChild(newText1);
// Append new button input to the newDiv
newDiv.appendChild(newDelButton);
// Append newDiv input to the mainContainer div
mainContainer.appendChild(newDiv);
counter++;
// Add a handler to button for deleting the newDiv from the mainContainer
newDelButton.onclick = function() {
mainContainer.removeChild(newDiv);
counter--;
}
}
else{
alert('Only 5 rows are allowed');
}}sss
function removeRow(divId){
mainContainer.removeChild(divId);
counter--;
}
</script>
</head>
<body >
<div id="mainContainer">
<div><input type="button" value="Add New Row" onClick="addNew()"></div>
<div id="div1"><input type="text" id="ans1"><input type="text" id="ans2"><input type="button" value="Remove" onClick ="javascript:removeRow(div1);"></div>
</div>
</body>
</html>
I want to achieve the same using jQuery.I also need the values entered in each of these textboxes.Please help.
Okay, because I had nothing better to do, and, to be honest, I was curious, I put this together. As implied in my comment, above, I didn't particularly like the way you had it laid out, so I used the following (x)html:
<form action="#" method="post">
<fieldset id="rows">
<ul>
<li>
<input type="text" id="ans1" name="ans1" />
<input type="text" id="ans2" name="ans2" />
</li>
</ul>
</fieldset>
<fieldset id="controls">
<button id="addRow">add</button>
<button id="removeRow" disabled>remove</button>
</fieldset>
</form>
With the following jQuery (although I've clearly not optimised, or refined it, but it should meet your requirements):
$(document).ready(
function(){
$('#addRow').click(
function() {
var curMaxInput = $('input:text').length;
$('#rows li:first')
.clone()
.insertAfter($('#rows li:last'))
.find('input:text:eq(0)')
.attr({'id': 'ans' + (curMaxInput + 1),
'name': 'ans' + (curMaxInput + 1)
})
.parent()
.find('input:text:eq(1)')
.attr({
'id': 'ans' + (curMaxInput + 2),
'name': 'ans' + (curMaxInput + 2)
});
$('#removeRow')
.removeAttr('disabled');
if ($('#rows li').length >= 5) {
$('#addRow')
.attr('disabled',true);
}
return false;
});
$('#removeRow').click(
function() {
if ($('#rows li').length > 1) {
$('#rows li:last')
.remove();
}
if ($('#rows li').length <= 1) {
$('#removeRow')
.attr('disabled', true);
}
else if ($('#rows li').length < 5) {
$('#addRow')
.removeAttr('disabled');
}
return false;
});
});
JS Fiddle demo of the above
I'm not, however, sure what you mean by:
I also need the values entered in each of these textboxes.
If you can explain what that means, or how you want them to be available (and, ideally, why they're not already available to you) I'll do my best to help.
I have a solution which will help you use here is the code
<script type="text/javascript" src="js/jquery.js"></script>
<script type = 'text/javascript'>
var newRowNum = 1;
var project_id ;
$(function() {
$('#addnew').click(function()
{
newRowNum++; // This is counter
//var i = 0;
///////// <a> <td> <tr>
var addRow = $(this).parent().parent();
///////// In the line below <tr> is created
var newRow = addRow.clone();
$('input', addRow).val('');
$('td:first-child', newRow).html();
$('td:last-child', newRow).html('<a href="" class="remove span">Remove<\/a>');
var newID = 'project'+newRowNum;
var add = 'description'+newRowNum;
newRow.children().children().first('input').attr('id', newID).attr('name', newID);
newRow.children().children().eq(1).attr('id', add).attr('name', add);
$('#table').find('tr:last').after(newRow);
$('a.remove', newRow).click(function()
{
newRowNum--;
$('#table').find('tr:last').remove();
return false;
});
return false;
});
});
</script>
<table width="75%" border="0" align = "center" id = 'table'>
<tr>
<td align = "center">Project </td>
<td align = "center">Description</td>
<td align = "center">Add Row</td>
</tr>
<tr>
<td align = "center"><input type = 'text' size = '35'name = 'project[]' id="project" ></td>
<td align = "center"><input type = 'text'size = '55' name = "description[]" id = 'description'></td>
<td width = '10%'><a id="addnew" href= "" class = 'span'>Add</a></td>
</tr>
</table>
You can also give each text box unique name if you change code like this and changing these two variables
var newID = 'project'+newRowNum;
var add = 'description'+newRowNum;
if you use the first method i shown here it will be easy to post data using array. That's all.