Click button to Edit Table titles - javascript

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

Related

show hide field depend on select value sharepoint online

I have a list of 2 columns, the first one is "City" which is choice type.the second column is "Other" which is a single line of text.
when the user chooses "other " in City I want "OtherCity "column appears, if he chooses another choice, I want to hide.
I write the code using simple javascript, I do not want to use any library just simple code in javascript.
<script type="text/javascript">
function mySelectfunction(){
getValue = document.getElementById("City").value;
if(getValue == "other"){
document.getElementById("OtherCity").style.display ="none";
}else{
document.getElementById("OtherCity").style.display ="block";
}
}
</script>
but it does not work. can you help make it work?
*another question: if the second column which I want to hide type is "lookup " will the code be different?
My test code for your reference,and Choice and lookup column do not need to change the code.
Add a script editor in NewForm,and insert the code into it(replace the column name).
<script src="https://cdn.bootcss.com/jquery/3.4.0/jquery.js"></script>
<script src="https://xxxx.sharepoint.com/sites/dev/SiteAssets/sputility.js">
</script>
<script>
$(document).ready(function () {
// Get a single select dropdown field
var relacionField = SPUtility.GetSPField('CityLookUp');
// create a function to show or hide Rates based on Rate value
var showOrHideField = function() {
var relacionFieldValue = relacionField.GetValue();
// Hide the Rates field if the selected value is Especial
if(relacionFieldValue === 'other') {
SPUtility.ShowSPField('Other')
}
else {
SPUtility.HideSPField('Other')
}
};
// run at startup (for edit form)
showOrHideField();
// make sure if the user changes the value we handle it
$(relacionField.Dropdown).on('change', showOrHideField);
});
</script>
You can download sputility.js here: https://archive.codeplex.com/?p=sputility
Updated:
Did the code above report any error?
JavaScript code:
ExecuteOrDelayUntilScriptLoaded(show,"sp.js");
function show () {
//Get the select element corresponding to column
var selectElement=document.getElementById('CityLookUp').parentNode.parentNode.childNodes[3].childNodes[3].childNodes[0];//chnage coulmn name
//get tr the hidden column located
var trElement=document.getElementById('Other').parentNode.parentNode;//change column name
//hide tr when we get into page,if the default value is 'other' ,do not need this
trElement.style.display='none';
//select change event
selectElement.onchange = function () {
var index = selectElement.selectedIndex;
//get option value
var value = selectElement.options[index].text;
if(value==='other'){
//show tr element
trElement.style.display='';
}else{
//hide tr element
trElement.style.display='none';
}
}
}
The code idea is to find the corresponding select element and decide whether to hide the tr element where column other is located according to the value of option.
Tip: Our page dom structure may be different, so you may need to modify the code according to your page dom structure. You could view your page dom structure by Developer tool.
Test result:

Assigning classes or ids to button created dynamically using jquery

I am creating several buttons dynamically. I am trying to assign each on a different class or id so when it is clicked on it will have a different output. How would I add an value at the end of each class or id name to give each button a unique class or id name?
Here is my code
socket.on('usernames', function(data){
var $contentWrap = $("#contentWrap").empty();
for(i=0; i <data.length; i++){
$input = $('<input type="button" style="width:200px" class= "button"/></br>');
$input.val(data[i]);
$input.appendTo($("#contentWrap"));
}
});
Can I created an on click event for the all button that I created. So far I created an on click even, but it only works for the first button.
Here is my code
$(document.body).on('click','.button', function(e) {
console.log($('.button').val());
});
Use $(this).val() instead of $('.button').val(). this will refer clicked button.
$(document.body).on('click','.button', function(e) {
console.log($(this).val());
});
socket.on('usernames', function(data){
var $contentWrap = $("#contentWrap").empty();
for(i=0; i <data.length; i++){
$input = $('<input type="button" id="btn"'+i+' style="width:200px" class= "button"/></br>');
$input.val(data[i]);
$input.appendTo($("#contentWrap"));
}
});
Problem: Is with this part of code console.log($('.button').val()); The part $('.button') selects all the buttons , But when you say .val() it defaults to the first one out of the collection. Hence you see the same output on all the button clicks.
Solution: Change the code to log the current clicked button value by using $(this).val(). this will refer to the element that triggered the event.
So the final line of code should be
console.log($(this).val());

multiselect behavior in single select jqGrid

I have a page with a jqGrid in it. Is has to be multiselect:false because I have to allow only one row to be selected, but I also need to select multiple rows (i.e. I want to have many rows marked but only one active).
So I've created a grid whith multiselect:false and a checkbox row with formatter: 'checkbox'
I've also created a master checkbox in the collumn header (the 'name' of the collumn in the colNames is <input id="cbSelectAll" type="checkbox">)
To change all the rows at once when the header is clicked I've created the function:
$('#cbSelectAll').click(function (e) {
var valor = $(this).is(':checked');
$.each($('#grid input[type="checkbox"]'), function (idx, elm) {
var id = $(elm).closest('tr').attr('id');
var cb = $('#' + id + ' td').children().first();
$(cb).attr('checked', valor);
selectedRows[id] = valor;
});
/* other non relevant code */
});
Now that's my problem.
This function works nicelly when I try to unselect the checkbox's but when i try to select then it only works in the first time. On the subsequent clicks the checked attribute is changed but the box is not visually changed.
Instead of attr, try using prop
Please have a look at this similar issue

How to automatically generate new input fields by filling previous?

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.

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