Dynamic row file name into textbox - javascript

Using jquery and bootstrap-jasny I created a dynamic row insert:
Code here
html:
<table id="internalTbl">
<tr><td><div class="fileinput fileinput-new" data-provides="fileinput"> <span class="btn btn-default btn-file"><span class="fileinput-new">Select file</span><span class="fileinput-exists">Change</span>
<input type="file" name="name">
</span> <span class="fileinput-filename"></span>
×
<input type="text" name="namehidden" />
</td></tr>
</table>
<button id="addInternal"> add </button>
javascript:
// add new row to internal listing table
$("#addInternal").click(function() {
$("#internalTbl").each(function () {
var tds = '<tr>';
$.each($('tr:last td', this), function () {
tds += '<td>' + $(this).html() + '</td>';
});
tds += '</tr>';
if ($('tbody', this).length > 0) {
$('tbody', this).append(tds);
} else {
$(this).append(tds);
}
});
// clear the last file input field
$("#internalTbl tr:last .fileinput").fileinput('clear');
});
For the subsequence, I am not able to assign the file name to the textbox.

You need to delegate the change event for dynamically added fileinput. More on delegate. The below code will attach the change event on future elements with class .fileinput
$(document).on('change.bs.fileinput', '.fileinput', function (e) {
var filename = $(this).closest('tr').find('.fileinput-filename').text();
$(this).closest('tr').find('input[type="text"]').val(filename);
});
Also I have used two methods of appending, one on click creates the trs and tds manually and other clones the first tr and appends to the table. You can use any one.
var fileinput = $('#internalTbl tr td:eq(0)').html();
var td = '<td>'+fileinput+'</td>';
var tr ='<tr>'+ td+'</tr>';
$("#addInternal").click(function () {
$("#internalTbl tbody").append(tr);
$("#internalTbl tr:last .fileinput").fileinput('clear');
});
$("#addInternal2").click(function () {
var cloned_elem = $('#internalTbl tr:first').clone();
$("#internalTbl tbody").append(cloned_elem);
$("#internalTbl tr:last .fileinput").fileinput('clear');
});
Demo Fiddle

Related

How to show hide specific div in table?

HTML:-
'<td>' + item.Message + ' <input type="button" class="btn btn-info" id="' + item.LogID + '" onclick="Clicked(this);" value="View More" /> <p> ' + item.FormattedMessage + ' </p></td></tr>'
this is button in table
Jquery:-
function Clicked(e)
{
var SelectedID = e.id;
$("p").toggle();
};
In this When i click on button i want to show selected id column only and hide rest columns.
But when i click on button it shows all column or hides all column
In addition to balachandar answer. if you want to hide p tag initially then use display:none for p tag
function Clicked(e)
{
var SelectedID = e.id;
$("#"+SelectedID).next("p").toggle(function(){
var btn_text = $("#"+SelectedID).val();
if(btn_text == "View More"){
$("#"+SelectedID).val("Hide");
}else{
$("#"+SelectedID).val("View More")
}
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" class="btn btn-info" id="myID" onclick="Clicked(this)" value="View More" /> <p style="display:none"> Some Text you want to in future </p>
Try this below code
function Clicked(e)
{
var SelectedID = e.id;
$("#"+SelectedID).next("p").toggle();
};
Hope this will help you.
You can select the element by its id and find the p element inside:
function Clicked(e)
{
var SelectedID = e.id;
$("#" + SelectedID).find("p").toggle();
};
Or just use this:
function Clicked(e)
{
$(this).find("p").toggle();
};
function Clicked(e)
{
var SelectedID = e.id;
$("#" + SelectedID).toggle();
};
You can use:
function Clicked(d)
{
var SelectedID = d.id;
$("#" + SelectedID).toggle();
};
This function picks all p inside td of your table and hides all of them, then it shows only the one with the same ID as the button.
function Clicked(e) {
var SelectedID = e.id;
$("td p").hide();
$("#" + SelectedID).show();
};

jQuery - How to find a row in html table and replace its text with new text

I need to get a row by a hidden field value and replace the old text with new text.
My table looks like this:
var $data = $('<table id="mytable" class="table table-striped"> </table>');
var header = "<thead><tr><th>Property Name</th><th>Edit</th></tr></thead>";
$data.append(header);
$.each(response.list, function (i, row) {
var $row = $('<tr/>');
$row.append($('<td/>').html(row.PropertyName));
$hidden = $(' <input type="hidden" name="hid" value= "' + row.PropertyId + '">');
$row.append($hidden);
$editButton = $("<button class='editbtn' id='mybtn'>Edit</button>");
$row.append($editButton);
$deleteButton = $("<button class='deletebtn' id='delbtn'>Delete</button>");
$row.append($deleteButton);
$data.append($row);
I tried to find the row by Hidden field value and replace the old text with new text with this code but it didn't work:
$('#mytable tr').find('td').eq(0).find(HiddelFieldValue).find('td').eq(1).html('New Text');

jquery prev() return undef

After receiving the data via JSON and add content on a table, was used the event delegation to capture the links of this content, but when you click the link that was created dynamically want to access the prev () the tr element containing the data-id. But this is me returning undef. Can someone help me? The prev() is being called by editarComercial()
Javascript:
$(document).ready(function(){
function editarComercial(trthis) {
alert($(trthis).prev().prev().data('id'));
}
function listaComercial(){
url = BASE_URL + 'comercial/ajaxrequest/listagem';
$.getJSON(url,function(data){
var trs = [];
$.each(data,function (key){
tr = "<tr data-id=\""+data[key].id+"\">";
tr += "<td>"+data[key].nome+"</td>";
tr += "<td>Editar";
tr += "Excluir</td>";
tr += "</tr>";
trs.push(tr);
});
$("<tbody/>",{
html: trs.join("")
}).appendTo("#listagemComercial");
});
}
$(document).on('click','a.edit-comercial',function(){
editarComercial(this);
});
listaComercial();
});
HTML:
<div id="content">
<table id="listagemComercial">
<thead>
<tr>
<th>Nome</th>
<th>Ações</th>
</tr>
</thead>
</table>
</div>
.edit-comercial doesn't have a previous element, it's the first element in the TD.
You probably wanted closest() instead, to traverse up to the row
function editarComercial(trthis) {
alert( $(trthis).closest('tr').data('id') );
}

How to dynamically add a new column to an HTML table

I have a table to which I am currently dynamically adding rows: http://jsfiddle.net/fmuW6/5/
Now I'd like to add a new column to the table as well with a click of a button. The user will enter the column header in a textbox.
How can I achieve this? If the user adds 4 rows, the Add a new Column button should take care of all the existing rows (adding checkbox in each one).
update
I'm looking to add column name and checkbox at row level.
so I've added the text box in which the user will input the column name: http://jsfiddle.net/fmuW6/10/
<input type=text placeholder='columnname'/>
<button type="button" id="btnAddCol">Add new column</button></br></br>
so then when user clicks the button the columnname should be the value in the textbox and at the row level should be checkboxes. So basically the new column should be appended to all tr in the table except the first row since that is the column names
I updated your fiddle with a small example how you could do that.
jsFiddle - Link
var myform = $('#myform'),
iter = 0;
$('#btnAddCol').click(function () {
myform.find('tr').each(function(){
var trow = $(this);
if(trow.index() === 0){
trow.append('<td>Col+'iter+'</td>');
}else{
trow.append('<td><input type="checkbox" name="cb'+iter+'"/></td>');
}
});
iter += 1;
});
This would add a new column to every row, including an count-variable that gets applied to the first row as name and to the name-attribute of the checkboxes on the following rows.
Consider using th - elements for the table header, that way you wouldn't need the index-check i'm making and it would be more semantically correct.
I left out the part where the user would put in a name for the column, but as you see, you could just replace the iter - value with that in the end.
Modern pure JavaScript solution:
const addColumn = () => {
[...document.querySelectorAll('#table tr')].forEach((row, i) => {
const input = document.createElement("input")
input.setAttribute('type', 'text')
const cell = document.createElement(i ? "td" : "th")
cell.appendChild(input)
row.appendChild(cell)
});
}
document.querySelector('button').onclick = addColumn
<table id="table">
<tr><th><input type="text" value="test 1" /><th/></tr>
<tr><td><input type="text" value="test 2" /><td/></tr>
</table>
<button type="button">add column</button>
First row will contain a th instead of td. Each new cell contains a input. Feel free to change this to suit your need.
The answer works, but still here is an alternative way where we use thead and tbody !
JS
$('#irow').click(function(){
if($('#row').val()){
$('#mtable tbody').append($("#mtable tbody tr:last").clone());
$('#mtable tbody tr:last :checkbox').attr('checked',false);
$('#mtable tbody tr:last td:first').html($('#row').val());
}
});
$('#icol').click(function(){
if($('#col').val()){
$('#mtable tr').append($("<td>"));
$('#mtable thead tr>td:last').html($('#col').val());
$('#mtable tbody tr').each(function(){$(this).children('td:last').append($('<input type="checkbox">'))});
}
});
Use this code for adding new column:
$('#btnAddCol').click(function () {
$("tr").append("<td>New Column</td>");
});
But you need to change the value for the first row with a text and others to include a <input type="checkbox" />. And it is better to
Check it out jsFiddle .............................
http://jsfiddle.net/fmuW6/8/
$(document).ready(function () {
$('#btnAdd').click(function () {
var count = 3, first_row = $('#Row2');
while(count-- > 0) first_row.clone().appendTo('#blacklistgrid');
});
$('#btnAddCol').click(function () {
$("#blacklistgrid tr").each(function(){
$(this).append("<td>test</td>");
})
});
});
Using a table of 4 columns:
I can add values dinamically like this:
var TableId = "table_" + id;
var table = $("#" + TableId );
table.find("tbody tr").remove();
table.append("<tr><td>" + "1" + "</td><td>" + "lorem" + "</td><td>" + "ipsum" + "</td><td>" + "dolor" + "</td></tr>");
and the final result will be:

A table row is causing content adding to not work

I have a piece of code below which works fine when it comes to adding text from a modal window into a textarea:
<script type="text/javascript">
var plusbutton_clicked;
function insertQuestion(form) {
var $tbody = $('#qandatbl > tbody');
var $tr = $("<tr class='optionAndAnswer' align='center'></tr>");
var $plusrow = $("<td class='plusrow'></td>");
var $question = $("<td class='question'></td>");
$('.questionTextArea').each( function() {
var $this = $(this);
var $questionText = $("<textarea class='textAreaQuestion'></textarea>").attr('name',$this.attr('name')+"[]")
.attr('value',$this.val());
$question.append($questionText);
});
$('.plusimage').each( function() {
var $this = $(this);
var $plusimagerow = $("<a onclick='return plusbutton(this);'><img src='Images/plussign.jpg' width='30' height='30' alt='Look Up Previous Question' class='imageplus'/></a>").attr('name',$this.attr('name')+"[]")
.attr('value',$this.val());
$plusrow.append($plusimagerow);
});
$tr.append($plusrow);
$tr.append($question);
$tbody.append($tr);
form.questionText.value = "";
$('.questionTextArea').val('');
}
function closewindow() {
$.modal.close();
return false;
}
$('.plusimage').live('click', function() {
plusbutton($(this));
});
function plusbutton(plus_id) {
// Set global info
plusbutton_clicked = plus_id;
// Display an external page using an iframe
var src = "previousquestions.php";
$.modal('<iframe src="' + src + '" style="border:0;width:100%;height:100%;">');
return false;
}
function addwindow(questionText) {
if(window.console) console.log();
if($(plusbutton_clicked).attr('id')=='mainPlusbutton') {
$('#mainTextarea').val(questionText);
} else {
$(plusbutton_clicked).parent('td').next('td.question').find('textarea.textAreaQuestion').val(questionText);
}
$.modal.close();
return false;
}
</script>
But the problem is that if I include this code below which I need into the function insertQuestion(form) {, then it stops the text adding into the textarea, why is it doing this?
var $qid = $("<td class='qid'>" + qnum + "</td>" );
...
$tr.append($qid);
$qid is the question number for each row, so everytime a row is added, it adds a question number by plus 1 each time.
Blow is the html code of where it appends the textarea from the top into a table row:
<table id="question">
<tr>
<th colspan="2">
Question Number <span class="questionNum">1</span>
<input type="hidden" class="num_questions" name="numQuestion" value="1">
</th>
</tr>
<tr>
<td rowspan="3">Question:</td>
<td rowspan="3">
<textarea class="questionTextArea" id="mainTextarea" rows="5" cols="40" name="questionText"></textarea>
</td>
</tr>
</table>
UPDATE:
I have included links to both applications. One that works but does not include $qid, and one that includes $qid and doesn't work but which I do need working. Please follow steps in both applications so you can test it yourself and see what is happening:
Application 1: No $qid but working.
Aplication 2: Contains $qid but not working:
Follow steps below for both applications:
Click on "Add Question" button, then will add a textarea within a new row.
Click on the "Green Plus" button within the table row you just added, a modal window will appear.
In modal window it displays a search bar, in search bar type in "AAA" and click on "Search" button
Results will appear of your search, click on "Add" button to add a row. You will find out modal window is closed but the content from the "Question" field is not added in the textarea within the row you clicked on the green plus button
Try explicity setting the td value with
var $qid = $("<td class='qid'></td>" ).text(qnum);
$tr.append($qid);
And then replace the text setting code from
$(plusbutton_clicked).parent('td').next('td.question').find('textarea.textAreaQuestion').val(questionText);
to
$(plusbutton_clicked).closest('tr').find('textarea.textAreaQuestion').val(questionText);
You can try it easily if you try with text:
var $qid = $("<td class='qid'>"+ qnum + "</td>" );
$tr.append($qid);
or
$("<td class='qid'></td>" ).text('hello').appendTo($tr);

Categories

Resources