I have a table of data where users can edit the information by a click. The click will replace the number data with an input text field that will allow the users to submit their edits. I've included a "cancel" link where once clicked, the input field will disappear and the data text reappears. However, if I clicked to edit multiple rows and cancel it, the data text will reappear as the first row that I clicked.
For example, my table of data looks like this
Ref No. | Container No.
0006 | OLKI2940
0005 | KL2223KL
0004 | PPO80596
0003 | JLJ93459
If I clicked to edit Container # "OLKI2940", I cancel it and "OLKI2940" will reappear fine. However, if I clicked to edit the second row Container # "KL2223KL" and cancel, the Container # "OLKI2940" will appear. So it's copying the first row that I clicked. How do I get it for the right container number to appear?
My html as follow:
// this is in a loop
<tr>
<td>{{ refnum }}</td>
<td id="{{ ctrnum }}">{{ ctrnum }}</td>
</tr>
My JS:
// editing container no
$('#containers').delegate("a.ctrnoedit","click", function() {
var index = $(this).closest("td").attr("id");
var html = "<form id='editctrno' method='post'><input name='ctrnum' type='text' value='"+index+"'>" +
"<br><button type='submit'>Update</button> <a href='#' id='canceledit'>Cancel</a></form>";
$(this).closest("td").html(html);
$('#containers').delegate("a#canceledit", "click", function() {
$(this).closest("#editctrno").html("<a href='#' class='ctrnoedit'>"+index+"</a>");
})
})
JS fiddle example:
http://jsfiddle.net/9Lsgw2ve/1/
although your way of coding violates the rules of html by generating duplicated ids, this is a Working Demo
var index='';
// editing container no
$('#containers').delegate("a.ctrnoedit", "click", function () {
index = $(this).closest("td").attr("id");
var html = "<form id='editctrno' method='post'><input name='ctrnum' type='text' value='" + index + "'>" +
"<br><button type='submit'>Update</button> <a href='#' id='canceledit'>Cancel</a></form>";
$(this).closest("td").html(html);
$('#containers').delegate("a#canceledit", "click", function () {
$(this).closest("#editctrno").html("<a href='#' class='ctrnoedit'>" + index + "</a>");
})
})
you just need to define index out of the click function
also if you wanna get the exact same values as it was in the links then try this:
DEMO
var index='';
// editing container no
$('#containers').delegate("a.ctrnoedit", "click", function () {
index = $(this).closest("td").children('a').html();
var html = "<form id='editctrno' method='post'><input name='ctrnum' type='text' value='" + index + "'>" +
"<br><button type='submit'>Update</button> <a href='#' id='canceledit'>Cancel</a></form>";
$(this).closest("td").html(html);
$('#containers').delegate("a#canceledit", "click", function () {
$(this).closest("#editctrno").html("<a href='#' class='ctrnoedit'>" + index + "</a>");
})
})
Related
I've created a table using an AJAX request to the database of items in our inventory displaying a picture/part name/price/stock remaining. When the table displays I would like to be able to click on any part of one of the rows and have it link to the item page associated with that item but it won't work.
I've tried the on.click with a static table written right into the html and it worked fine. Also if I direct the on.click script to just the table id instead of the table id and tr i can make the entire table clickable to the first row's href. So it appears that since the tr doesn't really exist in the html the javascript won't find it. Is there a way to get the script to recognize each 's href attribute?
HTML CODE + on.click script:
<html>
<body>
<table id="ctable">
<tbody id="tbody1" class="tbody1">
</tbody>
</table>
<script>
$('#ctable tr').click(function() {
var href = $(this).find("a").attr("href");
if(href) {
window.location = href;
}
});
</script>
</body>
</html>
.JS File CODE that creates table from .php file/mysql database
document.addEventListener('DOMContentLoaded', function() {
$.post('test.php', function(data) {
$("#tbody1").empty();
$.each(JSON.parse(data), function (index, value){
var eachrow = "<tr>" +
"<td class=\"image\">" + '<img src="images/thumbs/' +
value.image + '">' + "</td>" +
"<td>" + '<a href="' + value.link + '">' + value.part + "
</td>" +
"<td>" + value.price + "</td>"
"<td>" + value.stock + "</td>"
"</tr>";
$('#tbody1').append(eachrow);
});
});
}, false);
If you are dynamically adding rows, you need to either restructure your click event to listen from the context of the parent as in:
$("#tbody1").on("click", "tr", function(e) {
});
Assuming #tbody1 is a good place to start since you probably don't want the header row to be clickable. Or, every time you dynamically add rows, since the code is rebuilding the table, you can reattach the click event handlers:
$("#tbody1").empty();
$.each(JSON.parse(data), function (index, value){
var eachrow = "..
$('#tbody1').append(eachrow);
});
// or .on("click", function() { })
$("#tbody1 tr").click(function() { });
If you attach click handler via on, it would be good to then do an off as in:
$("#tbody1").off("click", "tr");
To remove the existing click handlers.
I am trying to dynamically add new elements to my html. But i am currently stuck on the "second level". It starts with a single div where new elements will get stored at:
<div id="inputquestions"></div>
When I click a button, new elements will get added to the div via a javascript function which looks something like this
function addQuestion() {
var div = document.createElement('div');
questionID++; // increment questionID to get a unique ID for the new element
div.className = 'newQuestion';
div.id = 'newQuestionID';
div.innerHTML =
"<div class='input-group'>" +
"<input id='question-" + questionID + "' class='form-control' name='questionbox' type='text' placeholder='New Question'/>" +
"<button class='btn btn-secondary' onclick='removeQuestion(this.parentNode)' type='button'>Remove</button>" +
"</div>" +
"<div class='btn-group' role='group' aria-label='Basic example'>" +
"<button class='btn btn-secondary' onclick='addRadioButton()' type='button'>+ Radiobutton</button>" +
"</div>";
document.getElementById('inputquestions').appendChild(div);
}
This will create multiple divs inside the first div and I now want each div to create new divs for them individually but can't figure out how to do it. How does my function addRadioButton() have to look like in order to make the new divs appear inside the div I pressed the button at?
In your function addRadioButton() you can look at event.target.parentElement to get the <div> that contains the <button> that was clicked on.
Then you add the new elements into that <div>.
I have a form where user can submit a few values and they get stored inside a list in a span separated by a comma, like this:
<li>
<span>
Harvard,Marketing,2009,2014
</span>
<br><a>[Remove]</a>
<br><a>[Edit]</a>
</li>
//output
Harvard,Marketing,2009,2014
[Remove]
[Edit]
When clicking on [Edit] I'd like to show up the form replacing the list space with the values in the span filling the inputs showing in the new form so the user can modify them and save again. How can I accomplish this?
Complete code on jsFiddle: http://jsfiddle.net/YueX2/
Please run it so you can see how it works, just click on "Add another" and then on the "Save" button.
is a bit messy but should give you an idea how to do this.
the given template for the "li" is slightly modified
<li>
<span>
Harvard,Marketing,2009,2014
</span>
<br>[Remove]
<br>[Edit]
</li>
the code could be like this:
$('.edit').click(function(){
var parent = $(this).parent();
//get the String from the span element
var values = $.trim( parent.find('span').text() );
//and plit them
values = values.split(',');
//prepend an container to hold the inputs
parent.prepend('<div class="editCont"></div>');
var container = parent.find('.editCont');
//create inputs for each of the seperated values
for(var v in values){
container.append('<input type="text" value="'+values[v]+'" /><br>');
}
//create save link and bind click event to it
container.append('<a href="#" class="editContButton" >save</a><br>');
parent.find('.editContButton').click(function(){
//collect all values from the inputs
var text = [];
var inputs = container.find('input');
for(var i = 0; i < inputs.length; i++){
text.push( $(inputs[i]).val() );
}
parent.find('span').show();
//replace the text in the span element and remove container with inputs again
parent.find('span').text( text.join(",") );
container.remove();
})
parent.find('span').hide();
});
If clicked on Edit the text in the span is split and an input for every entry is created and at the end i add a save link.
If the link is klicked the inputs get joined to an sting and replace the old text in the spawn.
the hide and unhiding of the spawn is optional ;)
When edit is clicked, you can split the content of that span, since it's already comma separated. Then you can take new input and apply it to the span on save. I edited your edit function, and added a new save function.
//existing edit method
$(document).on('click', '.edit', function () {
//hides edit and remove buttons
$(".removeParent, .edit").hide();
//splits span into separate terms
var terms = $(this).siblings("span").html().split(",");
//makes new form
$(this).parents("li").append("<input id='edit1' type='text' value=" + terms[0] + ">" + "<input id='edit2' type='text' value=" + terms[1] + ">" + "<input id='edit3' type='text' value=" + terms[2] + ">" + "<input id='edit4' type='text' value=" + terms[3] + "><input type='button' class='saveEdit' value='Save'>");
});
//additional save method
$(document).on('click', '.saveEdit', function () {
//unhides edit and remove buttons
$(".removeParent, .edit").show();
//makes the new string for the span
var newString = $("#edit1").val()+","+$("#edit2").val()+"," +$("#edit3").val()+","+$("#edit4").val();
//replaces the html of the span with the new string
$(this).siblings("span").html(newString);
//hides new form and save button
$(this).hide();
$("#edit1, #edit2, #edit3, #edit4").hide();
});
I am trying to put a button in the cells of one of the columns and do something when it's clicked.
For example I add these lines to the SlickGrid example 1 (http://mleibman.github.io/SlickGrid/examples/example1-simple.html)
First to the column array I add:
{id: "Report", name: "Report", field: "Report", width: 40, sortable: true, formatter:reportFormatter}
then I add:
function reportFormatter(row, cell, value, columnDef, dataContext) {
return "<input type='button' value='show' id='reportBtn'/>";
}
$('#reportBtn').click(function() {
alert("hello");
});
The buttons appear in the cells but the click event is not being called !
I must be doing something wrong but can't for the life of me figure it out
can anyone help ?
Thanks!
slick.formatters.js
...
"btnForm": buttonsFormatter // add Slick.Formatters
..
function buttonsFormatter(row, cell, value, columnDef, dataContext) {
return "<input type='button' value='"+value+"' id='btnForm' value2='"+row+"' value3='"+cell+"' onClick='fnBtnClick(this);'/>";
}
add your html Script
function fnBtnClick( objBtn ){
alert( "row::[" + objBtn.value2 + "]\n\ncell::[" + objBtn.value3 + "]" );
}
you should use the grid events not button event like below ,
will call the onclick event of the grid ,
check if the clicked field is your button one
do your action
grid.onClick.subscribe(function (e, args) {
//check if your button was clicked
if ($(e.target).hasClass("btn")) {
var item = dataView.getItem(args.row);
///do your action
}
});
Use the precompiled template slick grid example. Add the property eg. ImageTrial, and in the data structure fill the property with the dynamic input button.
<script type=" " id="testtemplate">
<div class="test">
<b><%=ImageTrial%></b>
<b><%=ImageTrial2%></b>
</div>
dataForCell["ImageTrial"] = "<button type=\"button\" onclick=\"alert('a " + 1 + "')\">s</button>";
dataForCell["ImageTrial2"] = "<button type=\"button\" onclick=\"alert('b " + 2 + "')\">b</button>";
Good Luck
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);