generating textbox inside a table using jquery - javascript

Suppose this is the prepare table below. and each of 3 row there was a textbox and beside them there where 2 buttons the + or add and - for delete. when i click + in a row, a new textbox will be generated and when i click - the textbox will delete. like the sample below:
Could anyone suggest the snippet for this step or procedure?
Thank you

you could write something on these lines:
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes are allowed");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
});
</script>
If you do not want to create the div on the fly, you can find the id of your last table row, add 1 to it, create the table row, and then append the textbox creation html to it.

Assuming the html structure is as follows
<table border = "1">
<thead>
<tr><td> Text Boxes </td></tr>
</thead>
<tbody>
<tr><td><button class="add-text-box">+</button><button class="remove-text-box">-</button></td></tr>
<tr><td><button class="add-text-box">+</button><button class="remove-text-box">-</button></td></tr>
<tr><td><button class="add-text-box">+</button><button class="remove-text-box">-</button></td></tr>
</tbody>
​
the following jquery snippet should work
$(".add-text-box").click(function(){
$(this).parent().prepend(" <input class='text-box' /> <br>");
});
$(".remove-text-box").click(function(){
textboxes = $(this).parent().find('.text-box');
$(textboxes).last().remove();
if (textboxes.length === 0) {
$(this).siblings().remove();
$(this).remove();
}
});
​
You can see it in action here

Related

Dynamic add/delete input rows javascript,jquery

The dynamic add/delete input rows is not working properly. The rows are created using add function, but it is not deleted properly. Basically the delete function call is not working.
$(document).ready(function(){
var counter = 1; //initlal text box count
$("#addButton").click(function () {
if(counter > 3){
alert("Only 3 textboxes allowed");
return false;
}
var selectfield = $('#selectcolumnlist option:selected').val();
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv');
newTextBoxDiv.after().html('<label>'+ selectfield + ' : </label>' + '<input type="text" name="textbox_' + selectfield + '" id="textbox_'+selectfield+'" placeholder="' + selectfield + '" value="" /><input type="button" value="Remove Button" class="remove_this" id="removeid" />');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
alert(counter);
});
$("#removeid").click(function() {
alert("i'm in");
});
}
Assuming you're creating elements in a correct way, I mean, using unique ids, you should use event-delegation:
// This example selects the element with the class
// .removeid (here you need to set a specific class) or set something unique
// per new dynamically created element.
$("#TextBoxesGroup").on('click', '.remove_this', (function() {
alert("i'm in");
}));

Calling Remove button inside append

Here is the script i'm using to append name input field-
<script>
$(document).ready(function() {
$("#add").click(function() {
var someId = document.getElementById('someId').value;
var name = document.getElementById('name').value;
$('.print_box').append('<div class="' + someId + '"> <tr> <td> <input type="button" ref="'+someId+'" class="remove_button" value="Remove"></td> <td><input type="text" multiple name="name[]" value="' + name + '" </td> </tr>
});
});
</script>
Now I want to call remove button from a separate standalone script like-
<script>
$(document).ready(function() {
$(".remove_button").click(function() {
var getRemoveID = $(this).attr('ref');
$("." + getRemoveID + "").remove();
});
});
</script>
But this isn't working. It only works when remove function is included with append like-
<script>
$(document).ready(function() {
$("#add").click(function() {
var someId = document.getElementById('someId').value;
var name = document.getElementById('name').value;
$('.print_box').append('<div class="' + someId + '"> <tr> <td> <input type="button" ref="' + someId + '" class="remove_button" value="Remove"></td> <td><input type="text" multiple name="name[]" value="' + name + '" </td> </tr>
$(".remove_button").click(function() {
var getRemoveID = $(this).attr('ref');
$("." + getRemoveID + "").remove();
});
});
});
</script>
Now, How can I seperate those 2 function? i mean calling remove button outside that append script??
Just use on
$("body").on("click", ".button", function() {
alert("click")
});
https://codepen.io/anon/pen/BxRNjM
This is not how you solve it. You are going in wrong direction. The problem here is that you are trying to handle events for the elements which are being added on the DOM dynamically.
So you need to handle events like (click, mouseover etc) for those elements in this way
$(document).on('click', '.remove_button', function(){
//Code to handle that event when click on remove_button
});

Running external javascript function from a button clicked that was created dynamically using jquery in Wordpress

I am trying to execute the function that was created separately called uploads.js . This javascript file is a custom image uploader function to be used in Wordpress. I was able to run that javascript file whenever i create a new button just by the of the HTML by sending the needed parameters.
There is a part where i created a dynamic button creation function using jquery, where whenever a 'PLUS' sign button is pressed, that function will trigger and a new button is added. The id of that button is automatically incremented by one.
The problem here is, whenever i click on the button that was created not by using the dynamic button function, it was able to execute the uploads.js function. But the dynamic created buttons are not able to. It seems like the id of the dynamic button was not detected. I even inspect the element of that page, the id that was sent is exactly the same from what I have sent as a parameter to the uploads.js function.
Is there something that i have missed or I have done wrong? Below are the codes:
HTML
<tr class="form-field">
<th scope="row">
<label for="component1"> Component 1</label>
<br></br>
<input type='button' class="button button-large" value='+' id='addButton'>
<input type='button' class="button button-large" value='-' id='removeButton'>
<input type='button' class="button button-large" value='Get TextBox Value' id='getButtonValue'>
</th>
<td>
<div id='TextBoxesGroup'>
<div id="ImageDiv1">
<input id="section2_1" class="button" type="button" value="Upload Image" name="upload_s2_1"/>
</div>
<div id="TextBoxDiv1">
<label>Title #1 : </label>
<input type='text' id='title1' />
</div>
<div id="DescDiv1">
<label>Description #1 : </label>
<input type='text' id='description1' /><br></br>
</div>
</div>
</td>
</tr>
uploads.js
jQuery(document).ready(function($){
function dynamic_image( button , textbox )
{
var custom_uploader;
$(button).click(function(e) {
e.preventDefault();
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function() {
attachment = custom_uploader.state().get('selection').first().toJSON();
$(textbox).val(attachment.url);
});
//Open the uploader dialog
custom_uploader.open();
});
}
dynamic_image('#upload_image_button' , '#upload_image');
dynamic_image('#section2_1' , '#section2_text1');
dynamic_image('#section2_2' , '#section2_text2');
dynamic_image('#section2_3' , '#section2_text3');
dynamic_image('#section2_4' , '#section2_text4');
dynamic_image('#section2_5' , '#section2_text5');
});
script
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>5){
alert("Only 5 components are allowed");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
var newDescDiv = $(document.createElement('div'))
.attr("id", 'DescDiv' + counter);
var newImageDiv = $(document.createElement('div'))
.attr("id", 'ImageDiv' + counter);
newTextBoxDiv.after().html('<label>Title #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="title' + counter + '" value="" >');
newDescDiv.after().html('<label>Description #'+ counter + ' : </label>' +
'<input type="text" name="descbox' + counter +
'" id="desc' + counter + '" value="" ><br></br>');
newImageDiv.after().html('<input class="button" type="button" name="upload_s2_' + counter +
'" value="Upload Image" id="section2_' + counter + '" >');
newImageDiv.appendTo("#TextBoxesGroup");
newTextBoxDiv.appendTo("#TextBoxesGroup");
newDescDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more component to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
$("#DescDiv" + counter).remove();
$("#ImageDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
Other button(like #section2_2, #section2_3 ...) maybe not exist, When function dynamic_image run.
Then below code cannot have meaning.
dynamic_image('#section2_2' , '#section2_text2');
// cannot find #section2_2 , because not yet added
Try this.
// function is called when input.button(like #section2_1, #section2_2 ...) on #TextBoxesGroup clicked
$('#TextBoxesGroup').on('click','input.button',function(e){
e.preventDefault();
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function() {
attachment = custom_uploader.state().get('selection').first().toJSON();
$(textbox).val(attachment.url);
});
//Open the uploader dialog
custom_uploader.open();
})
See example
indicate actually like following
$('#TextBoxesGroup').on('click','input.button',function(e){
var $clickedInput = $(this);// JQuery Object of section2_2
var clickedInputId = $clickedInput.attr('id'); // section2_2
var indicateKey = clickedInputId.substring(10,clickedInputId.length);// 2
var neededTextId = 'section2_text'+indicateKey ; //section2_text2
var $neededText = $("#" +neededTextId ); // JQuery Object of section2_text2
// run logic what you want to do
})

jQuery variable is not updating on dynamic created textbox

I am trying to detect the current button click to assign values to its respective textboxes. Each time I select any of the button, it will detect the first button click and assign the value to the first textbox. Meaning to say that, the second and third button values are assigned to the first textbox. The upload_textbox variable is not changing its value.
I did some error testing, when upload_textbox variable enters custom_uploader.on('select', function(), the value stays and will not change. I am not sure on why it doesn't.
What have I done wrong here? Below are my codes:
function dynamic_image( button )
{
var custom_uploader;
$(button).on('click','input.button',function(e)
{
e.preventDefault();
var $clickedInput = $(this);// JQuery Object of section2_2
var clickedInputId = $clickedInput.attr('id'); // section2_2
var upload_textbox = '#' + 'upload_image_' + clickedInputId;
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media(
{
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function()
{
attachment = custom_uploader.state().get('selection').first().toJSON();
$(upload_textbox).val(attachment.url);
//console.log(upload_textbox);
});
//Open the uploader dialog
custom_uploader.open();
})
}
dynamic_image('#TextBoxesGroup');
HTML
<tr class="form-field">
<th scope="row">
<label for="component1"> Component 1</label>
<br></br>
<input type='button' class="button button-large" value='+' id='addButton'>
<input type='button' class="button button-large" value='-' id='removeButton'>
<input type='button' class="button button-large" value='Get TextBox Value' id='getButtonValue'>
</th>
<td>
<div id='TextBoxesGroup'>
<div id="ImageDiv1">
<input id="section2_1" class="button" type="button" value="Upload Image" name="upload_s2_1"/>
</div>
<div id="TextBoxDiv1">
<label>Title #1 : </label>
<input type='text' id='title1' />
</div>
<div id="DescDiv1">
<label>Description #1 : </label>
<input type='text' id='description1' /><br></br>
</div>
</div>
</td>
</tr>
script
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>5){
alert("Only 5 components are allowed");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
var newDescDiv = $(document.createElement('div'))
.attr("id", 'DescDiv' + counter);
var newImageDiv = $(document.createElement('div'))
.attr("id", 'ImageDiv' + counter);
var newUploadDiv = $(document.createElement('div'))
.attr("id", 'UploadDiv' + counter);
newTextBoxDiv.after().html('<label>Title #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="title_section2_' + counter + '" value="" >');
newDescDiv.after().html('<label>Description #'+ counter + ' : </label>' +
'<input type="text" name="descbox' + counter +
'" id="desc_section2_' + counter + '" value="" ><br></br>');
newImageDiv.after().html('<input class="button" type="button" name="upload_s2_' + counter +
'" value="Upload Image" id="section2_' + counter + '" >');
newUploadDiv.after().html('<input type="text" name="image_url_' + counter +
'" id="upload_image_section2_' + counter + '" >');
newUploadDiv.appendTo("#TextBoxesGroup");
newImageDiv.appendTo("#TextBoxesGroup");
newTextBoxDiv.appendTo("#TextBoxesGroup");
newDescDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more component to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
$("#DescDiv" + counter).remove();
$("#ImageDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
Then I suspect this could be the culprit.
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
This would always give you instance of first custom_uploader object.
Try to destroy the previous instance and generate new one.
There might be issue with the event binding within dynamic_image method.
Try
$(button).live('click',function(e) (deprecated as of jQuery 1.7 though)
or
$( document ).on( 'click', button, data, function(e)
instead of
$(button).on('click','input.button',function(e)
I hope it helps.
Can you try following.
$(button).change(function(){
//Write code here
});
I have solved my question. The culprit behind this was the custom_uploader mentioned by #Aman. There was a return statement there where it made the function not to take the new value that has been replaced. After doing so, the custom_uploader opens twice because there is two statement of it which it was called. Did it into an if else statement and had it the way I wanted. Below is my updated code.
function dynamic_image( button )
{
var custom_uploader;
var upload_textbox;
$(button).on('click','input.button',function(e)
{
e.preventDefault();
var $clickedInput = $(this);
var clickedInputId = $clickedInput.attr('id');
upload_textbox = '#' + 'upload_image_' + clickedInputId;
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media(
{
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function()
{
attachment = custom_uploader.state().get('selection').first().toJSON();
$(upload_textbox).val(attachment.url);
});
if (custom_uploader) {
custom_uploader.open();
}else
//Open the uploader dialog
custom_uploader.open();
})
}
#Aman, you have mentioned about optimizing it. It seems quite fast at the moment. Maybe if there is a way to optimize it for the better, it would be a great help.
Thank you all, #Regent, #Aman, #Bhushan Kawadkar, #Arindam Nayak, #Raj

jQuery add or remove table row based on inputs

Sorry, if this is too basic.
I am trying to add rows to a table if current number of rows are
less than a user's demand.
At the same time, I need to delete the
extra rows if current number of rows are more than a user's need.
My code is working, but I think it does not make a lot of sense. So I am wondering if anyone could correct my mistakes and make my code more reasonable. (I was trying to use two indices to control this add or remove activity. One index check the current existed elements and get the difference between user's new input. Then do the add or remove movements. But I failed to do this.)
In addition, is it possible to adjust the width of added <td> without changing the shape of the first table row? Thanks for your help! Here is a demo.
HTML
<form method="post" id="form1" action=index.html>
<table class="tab tab_Application" border="0">
<tr>
<th>
<label for="id_noa">Number of Applications:</label>
</th>
<td>
<select name="noa" id="id_noa">
<option value="">Make a selection</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</td>
</tr>
<tr id='noa_header' style="display:none">
<th>App#</th>
<th>Month</th>
<th>Day</th>
<th>Mass Applied (kg/hA)</th>
<th>Slow Release (1/day)</th>
</tr>
</table>
</form>
JS
$(document).ready(function () {
var i = 1
$('#id_noa').change(function () {
var total = $(this).val()
$('#noa_header').show()
//I was trying to use two indices to control this add or remove activity. One index check the current existed elements and get the difference between user's new input. Then do the add or remove movements. But I failed to do this.
while (i <= total) {
$('.tab_Application').append('<tr class="tab_noa1"><td><input type="text" size="5" value="' + i + '"/></td><td><input type="text" size="5" name="mm' + i + '" id="id_mm' + i + '""/></td><td><input type="text" size="5" name="dd' + i + '" id="id_dd' + i + '""/></td><td><input type="text" size="5" name="ma' + i + '" id="id_ma' + i + '""/></td><td><input type="text" size="5" name="sr' + i + '" id="id_sr' + i + '" value="0""/></td></tr>');
i = i + 1;
}
while (i-1 > total) {
$(".tab_Application tr:last").remove();
i=i-1
}
$('</table>').appendTo('.tab_Application');
})
});
I took the ideas presented by #B3aT, edited, and fleshed out to make this (available at my fork of OP's jsfiddle:
var row_i = 0;
function emptyRow() {
row_i++;
this.obj = $("<tr></tr>");
this.obj.append('<td><input type="text" size="5" value="' + row_i + '"/></td>');
this.obj.append('<td><input type="text" size="5" name="mm' + row_i + '" id="id_mm' + row_i + '""/></td>');
this.obj.append('<td><input type="text" size="5" name="dd' + row_i + '" id="id_dd' + row_i + '""/></td>');
this.obj.append('<td><input type="text" size="5" name="ma' + row_i + '" id="id_ma' + row_i + '""/></td>');
this.obj.append('<td><input type="text" size="5" name="sr' + row_i + '" id="id_sr' + row_i + '" value="0""/></td>');
}
function refresh(new_count) {
if(new_count > 0) {
$("#noa_header").show();
}
else {
$("#noa_header").hide();
}
var old_count = parseInt($('tbody').children().length);
var rows_difference = parseInt(new_count) - old_count;
if (rows_difference > 0)
{
for(var i = 0; i < rows_difference; i++)
$('tbody').append((new emptyRow()).obj);
}
else if (rows_difference < 0)//we need to remove rows ..
{
var index_start = old_count + rows_difference + 1;
$('tr:gt('+index_start+')').remove();
row_i += rows_difference;
}
}
$(document).ready(function () {
$('#id_noa').change(function () {
refresh( $(this).val() );
})
});
The reason the emptyRow function is so long is that I wanted to make the number of columns easy to manipulate. Each column is appended individually, so changing the default pattern is simple.
In the html, I had to add the thead and tbody tags as described in #B3aT's answer. The thead includes the first two rows, because row 1 is the select box and row 2 is the actual header for the table. The tbody is empty to start.
As far as changing styles for individual rows (like adjusting column width), you'd be better off not using a table. Table-like behavior can be as simple as using float:left in your column style, making sure to place a div with clear:both at the end of each row.
At these situations jQuery excels, let us play with all sort of selectors.
First you need to separate the header and body of the table (thead and tbody).
(Code not tested).
function refresh(new_count) {
//how many applications we have drawed now ?
var old_count = parseInt($('tbody').children().count());
//the difference, we need to add or remove ?
var rows_difference = parseInt(new_count) - old_count;
//if we have rows to add
if (rows_difference > 0)
{
//$('tbody').append() or prepend() new empty rows based on your pattern with a loop
}
else if (rows_difference < 0)//we need to remove rows ..
{
var index_start = old_count - rows_difference;//for the LAST X rows
$('tr:gt('+index_start+')').remove();
}
}

Categories

Resources