How to automatically generate new input fields by filling previous? - javascript

To be as simple as I can:
I have condition where I do not know where I'm going to have 3 or more input elements (type of "text") and I'm looking for solution which will generate 4th input type text when I start to fill 3th input field with characters, and so on.
Something similar Adminer have for adding new columns when creating/altering database:
here you click on + to add new input and x to remove it. This would also be good to me.
How to achieve that/what library should I use?

You can clone full row, and append it to parent table. Have a look at jQuery clone() and append().
Sample code:
$('#yourtableid').on('click', '.add', function() {
// clone first row
var row = $('#yourtableid tbody tr:first').clone();
// reset inputs
row.find('input[type!=button]').val('');
// append cloned row
$('#yourtableid tbody').append(row);
});
Live DEMO.
EDIT: To add row automatically when filled some text in last row, you can go with:
$('#tbl').on('change', 'input', function() {
// check that some input was entered and that it is in the last tr
if($(this).val() != '' &&
$(this).closest('tr').is(':last-child')) {
addRow();
}
});

It's difficult to tell what you're trying to get without a code sample, but do you want something like this?
HTML:
<input type='text' />
JS:
$('input').on( 'change', function() {
$(this).after( '<input type="text" />' );
$('input').off( 'change' );
});
jsFiddle is down and jsBin can't handle the extra load, but here's a demo.

Related

Click button to Edit Table titles

I have a table with Column title. There is also a edit button. If I click the button, Table title should be a Input field with title name as a value in it. Edit button will turn into Save Button.
I can rename the title and Save the new names. I not good in jquery and what I made creating bunch of input fields and I can't save new names. FIDDLE
Any help will save my day. Thanks in advance.
jQuery:
var textInfo = $('.table th').text();
$("html").on('click', '.btn-danger', function() {
$('.table th').append('<input id="attribute" type="text" class="form-control" value="' + textInfo + '" >');
$('.btn-danger').text('Save');
}) ;
Here is a fiddle that solves your problem.
http://jsfiddle.net/has9L9Lh/54/
It uses a common approach of toggling an element's class (or some other attribute), to determine the state of your program. In this case, it determines whether or not the columns are in edit-mode, and changes the button text and th html accordingly.
$("html").on('click', '.btn-danger', function() {
var editMode = $(this).hasClass('edit-mode'),
columns = $('.table th');
if (!editMode){
$(this).html('Save').addClass('edit-mode');
columns.each(function(){
var txt = $(this).text();
var input = $('<input type="text">');
input.val(txt);
$(this).html(input);
});
} else {
$(this).html('Edit').removeClass('edit-mode');
columns.each(function(){
var newName = $(this).find('input').eq(0).val();
$(this).html(newName);
});
}
}) ;
• you should not use id in the append this will create multiple id of the same name.
• use $(".form-control").length to check if it exist. this will solve multiple input when button is clicked multiple times.
• create a new button to submit your change.
• create another click event for the new button.
• than use it $.val() to get input value than pass that value to the new table title. and you are done.
I hope this will point you to the right direction. :D

Getting the value of a hidden field in <td> using jquery

I have a table data which is generated dynamically via a loop. The td contains a hidden field. below is the code for the same:
<td class="gridtd" id = "r<%=RowNumber%>c<%=ColumnNumber%>">
<input id="hiddendata" type="hidden" value="<%: item.Key%>"/>
</td>
I need to extract the value of the hidden field based on the td selected using jQuery. Please help me get the correct jquery code.
Just select your input and take the value (val()):
$("#hiddendata").val();
If you want to take all hidden input values:
$("input[type='hidden']").each(function () {
console.log($(this).val());
});
Note that the element ids must be unique.
I need to extract the value of the hidden field based on the td selected using jQuery.
If by select you mean, click, you can simply pass this when getting the value:
$("td").on("click", function () {
console.log(
$("[type='hidden']", this).val()
);
});
For your general knowledge, if you do $("#hiddendata", this).val(); inside of the click handler, it will return the correct value (even having multiple ids with the same value).
But definitely, the ids must be unique.
Use this :
$('#hiddendata').val();
$('td').click(
function(event)
{
$(event.target).find('#hiddendata').val();
}
);
It ll give the hiddendata value based on td selection
This will give the value of the hidden field for the selected td.
$('.gridtd').click(function(){
console.log($(this).find('input').val());
});
$('.gridtd').click(function(){
console.log($(this).find('input[type=hidden]').val());
});
You can try this:
$('.gridtd').each(function(){
var currentId = $(this).attr('id');
var hiddenval = $('#'+currentId).find('input[type=hidden]').val();
alert(hiddenval);
})

show multiple selected span values in jquery using comma

I've posted my full code on jsfiddle. I'm trying to show the user selected seats here. If user selected 2 from BS the result should be BS-2. Again if user selected 4 from FC the result should be added with the old one like BS-2, FC-4.
But, I've tried something here. its show the value of span element but if i selected the another one it replaces the previous one. How to add a comma and show the multiple selected span values in jquery?
JsFiddle
jQuery
$(".text").click(function(){
$(this).toggleClass('selected');
var data = $(this).text();
$('.returndata').text(data);
})
Try
var $texts = $(".text").click(function () {
$(this).toggleClass('selected');
var selected = $texts.filter('.selected').map(function () {
return $.trim($(this).text())
}).get()
$('.returndata').text(selected.join());
})
Demo: Fiddle

Split values from table into different text inputs?

I have a table that is populated by user input. For example, there is a text input for First Name, and Last Name. John in one input and Smith in the next, will add the the table under the Name column as John Smith, one string of 2 values. This is working correctly, along with the Address column... but getting the values FROM the table TO the inputs is the issue. Clicking the corresponding row populates the inputs, but I need to split these values to populate the correct inputs (so that John Smith is split up again to first and last name for example). Any ideas? Thanks in advance.
http://jsfiddle.net/Z85QC/6/
jQuery
/* Add a click handler to the rows - this could be used as a callback */
$("#example tbody tr").click(function (e) {
if ($(this).hasClass('rowSelected')) {
$(this).removeClass('rowSelected');
} else {
oTable.$('tr.rowSelected').removeClass('rowSelected');
$(this).addClass('rowSelected');
}
var properties; // all td from .row_selected
properties = fnGetSelected(oTable).find("td");
$("#fName").val(properties.eq(0).text());
$("#email").val(properties.eq(1).text());
$("#company").val(properties.eq(2).text());
});
I advise you to wrap your data row elements in span with corresponding class names. Example given for first name and last name,
js
$('#addRow').click(function () {
var row =$('#example').dataTable().fnAddData([
'<span class="fname">'+$("#fName").val()+'</span> <span class="lname">' + $("#lName").val()+'</span>',
$("#email").val(),
html of the fiddle
<td><span class='fname'>John</span> <span class='lname'>Smith</span></td>
Then it is straighforward and clear to retrieve the values independent from their textual format.
http://jsfiddle.net/Z85QC/10/
In the fiddle you will also find code for associating click function logic to new added rows so that they can be selected.
$('#addRow').click(function () {
var row =$('#example').dataTable().fnAddData([
'<span class="fname">'+$("#fName").val()+'</span> <span class="lname">' + $("#lName").val()+'</span>',
$("#email").val(),
$("#company").val() + '<br>' + $('#address').val()]);
$(oTable.fnGetNodes(row)).click( function( e ) {
if ($(this).hasClass('rowSelected')) {
$(this).removeClass('rowSelected');
} else {
oTable.$('tr.rowSelected').removeClass('rowSelected');
$(this).addClass('rowSelected');
}
var properties; // all td from .row_selected
properties = fnGetSelected(oTable).find("td");
$("#fName").val(properties.eq(0).find('.fname').text());
$("#lName").val(properties.eq(0).find('.lname').text());
$("#email").val(properties.eq(1).text());
$("#company").val(properties.eq(2).text());
});
In order to keep your code DRY it is best to place the click function logic inside a function and call that directly, instead of copying the code.
If you are 100% sure that the last name and first name are seperated by a space, you can use this code :
$("#fName").val(properties.eq(0).text().split(' ')[0]);
$("#lName").val(properties.eq(0).text().split(' ')[1]);
For address :
$("#company").val(properties.eq(2).html().split('<br>')[0].trim());
$("#address").val(properties.eq(2).html().split('<br>').splice(1).join('\n').trim());
Fiddle : http://jsfiddle.net/Z85QC/11/
You can do a simple change like:
var properties; // all td from .row_selected
properties = fnGetSelected(oTable).find("td");
var names = properties.eq(0).text().split(' ');
$("#fName").val(names[0]);
$("#lName").val(names[1]);
$("#email").val(properties.eq(1).text());
$("#company").val(properties.eq(2).text());
JSFiddle Demo
But only if you're sure the First and Last name are separated by a constant single space, otherwise you'd have to change it a little bit more...

Delete Table Row Except in First Row

I have a form which allows the user to add a new table row via a button in the bottom row which all is working well. I now need to also add the functionality to have an additional button to allow them to delete a table row.
I gather the simplest method would be to use:
$(this).closest('tr').remove();
but I'm having trouble integrating this into the existing functionality. I also only need the "delete" button to appear on all rows except the first row (i.e. users can delete all rows except the first one). I've setup a jsfiddle here that demonstrates my current functionality:
http://jsfiddle.net/fmdataweb/daayf/1/
So in my example when the user clicks the "Add another activity" button it should create the new table row as it currently does but also add the "delete" button which deletes that row. I've currently hard-coded the "delete" button to the first row as I'm now sure how to make it appear only for new rows created via the "add new activity" button.
Few changes
In the starting markup, add the classes addbtn and delbtn also hide the delete button
<td>
<input type="button" class="button mt5 addbtn" value="Add another activity" id="button1" name="button2" />
</td>
<td>
<input type="button" class="button mt5 delbtn" value="Delete" id="deleteRowButton" name="deleteRowButton" style="display: none"/>
</td>
Then
$('#lastYear').on('click', '.delbtn', function () {
$(this).closest('tr').remove()
});
var newIDSuffix = 2;
$('#lastYear').on('click', '.addbtn', function () {
var thisRow = $(this).closest('tr')[0];
$(thisRow).find('.delbtn').show();
var cloned = $(thisRow).clone();
cloned.find('input, select').each(function () {
var id = $(this).attr('id');
id = id.substring(0, id.length - 1) + newIDSuffix;
$(this).attr('id', id);
});
cloned.insertAfter(thisRow).find('input:text').val('');
cloned.find('.delbtn').hide();
cloned.find("[id^=lastYearSelect]")
.autocomplete({
source: availableTags,
select: function (e, ui) {
$(e.target).val(ui.item.value);
setDropDown.call($(e.target));
}
}).change(setDropDown);
$(this).remove();
newIDSuffix++;
});
Demo: Fiddle
Check out this one!
if($("table tr").length > 1) {
$(this).parent().parent("tr").remove();
}
Try this
On your Delete Button
$('#lastYear').on('click', '#deleteRowButton', function(e){
$(this).closest('tr').remove()
})
First of all I renamed your Button1 for your Adding a Row to addRowButton and then I change the delegate method to be more specific to addRowButton that is from
$('#lastYear').delegate('input[type="button"]'
To like this:
$('#lastYear')delegate('input[type="button"][id^="addRow"]'
Then inside the delegate method specifically after
$(this).attr('id', id);
I add after that the one below:
var checkid = $(this).attr('id').substring(0,id.length-1);
if (checkid == 'deleteRowButto') // the 'deleteRowButto' is not a mistake
{
$(this).click(function() {
$(this).closest("tr").remove(); // I assign an onclick for the delete button in order to remove a specific row
});
}
Edit:
I made some improvements that once the row is deleted the previous add button is shown so I add the code below:
var showmenow = $(this).closest("tr").prev().find("td:eq(5)").find("input[type='button']");
$(showmenow).show();
$(this).closest("tr").remove();
});
And instead of removing the button in your original code:
$(this).remove();
newIDSuffix++;
I use hide instead:
$(this).hide();
newIDSuffix++;
See the new jsfiddle that I created.
Since you want to use the first row as template for all other row but do not want to have a delete on the all the other rows we should insert the delete only during first insertion in java script.Check this demo out i modified your fiddle for this to work.
if(cloned.find('input.mt5[value="Delete"]').length==0){
cloned.find('.mt5').each(function(){
cloned.append($('<td><input type="button" class="button mt5" value="Delete" id="deleteRow'+newIDSuffix+'" name="deleteRowButton" /></td>'));
})
}
now for handling the delete events
$('#lastYear').delegate('input.button[value="Delete"]', 'click', function () {
var thisrow=$(this).parent().parent();
var button=thisrow.find("input.button[value='Add another activity']");
if(button.length>0){
var buttoncell=button.parent().detach();
var prevrow=thisrow.prev();
var prevDelete=prevrow.find('input.button[value="Delete"]');
var previd=(prevDelete.length>0)?prevDelete[0].id:'deleteRow1';
buttoncell.children()[0].id=previd.replace('deleteRow','button');
prevrow.find('input:text:last').parent().after(buttoncell);
}
thisrow.remove();
});
Demo: http://jsfiddle.net/vwdXD/2/
You have got it right for the most part except for the small oversight here and there. I have fixed your code for you and you can find it here: http://jsfiddle.net/ManojRK/86Nec/ .
Please try to understand the changes by comparing your version and my version using a Code Diff Tool (like http://www.quickdiff.com). It will teach you a lot.
Changes Made:
I have used styles to show and hide your buttons. This is not the only way to do it. But since you are cloning rows to add, using styles will make your JavaScript simple. This is a lot less buggy and less susceptible to changes.
I have introduced css classes to differentiate Add Another Activity and Delete buttons for the click event.
Hope it helps you understand.
I used the jsfiddle that you provided in hopes of being more direct in terms of answering your question. The method I took was to:
Check if the add or delete button was pressed
If the delete button was pressed, check if its the delete button contained within the first row (actually the third row, but it's the first row with user input). If the delete button is in the first row, do nothing
If the delete button was not in the first row, create an 'add activity' button in the previous row and remove the clicked button's parent row.
Step 1:
// let's check whether they clicked the add or delete button
if ( $(this).val() == 'Add another activity' ) { // if the add button was clicked
Step 2-3:
if ( $(thisRow).index() == 2 ) { // if it's the first row, don't let them delete
return false;
} else { // if it is not the first row remove this row and create an 'add' button in first row
$(thisRow).prev().find('td:last').prev().append('<input type="button" class="button mt5" value="Add another activity" id="button2" name="button2">');
$(thisRow).remove();
}
Here's a fiddle for ya: http://jsfiddle.net/daayf/22/
I placed a couple comments in the code to help out a bit. My edits were at:
Line 275-276
Line 300-307
Hope this helps out!
I recommend adding an id attribute dynamically for each row that way you can just refer to that id with jQuery.
You can set a specific class for the buttons like this
<input type="button" class="button mt5 deleteButton" value="Delete" id="deleteRowButton" name="deleteRowButton" />
and add this code to jquery
$('.deleteButton').on('click',function(){
$(this).parent().parent().remove();
});
this jquery deletes the grandparent of the input with deleteButton Class(the delete button), which is the row it is located in.
how about do this?
$(this).find('tr').length > 0 ? $(this).closest('tr').remove() : ;
Why is your "add new activity" and "delete" having the same class "button mt5"? not sure if space is allowed for the name of a class.
You may want to refer to my table here http://jsfiddle.net/yvonnezoe/nbrSR/1/ :D I have a fixed row on top and dynamic rows following that can be deleted.
My new row is created as below:
var str = '<tr id="' + rowID + '">' + '<td>' + index + '</td><td>' + rowID + '</td><td class="type_row_' + textInput + '">' + type + '</td><td class="feedback number">' + textInput + '</td>' + '<td id="status_'+rowID+'"></td>' + '<td><input type="checkbox" name="CB" id="monitor_' + rowID + '" class="custom" data-mini="true" /><label for="CB"> </label></td><td class="outputRemove">x</td>' + '</tr>';
$('#status_table tr:last').after(str);
The remove buttons are having a same class. So the rows can deleted when clicked.
$('#status_table').on('click', '.outputRemove', function () {
$(this).closest('tr').remove();
$('#status_table tbody tr').find('td:first').text(function (index) {
return ++index;
});
});
Hope it inspires you somehow :)
very simple way
function remove_point_item(th) {
var tr = $(th).closest("tr");
var _counter=0;
$(tr.siblings('tr')).each(function(){
_counter++;
});
if(_counter!=1){
tr.remove();
}
}

Categories

Resources