Contenteditable in HTML tables - html

With the code:
<table>
<tr><td contenteditable>My_Name</td><td>Surname</td></tr>
<tr><td contenteditable>My_Name2</td><td>Surname2</td></tr>
</table>
You can edit a cell in an HTML table. My problem is when I edit the cell and press enter, it creates a new line in cell. What I really would like is, if I press enter I go to the cell just below that cell I just edited so that I can edit that cell.
Currently I have to use the mouse to go to the next cell, but if I can press enter and go to the cell, it will help me edit the cells a bit faster. Plus the updated data will be stored in my database, so I also don't want unnecessary space stored in the database.
But I am not sure what I can do. Is there any example I can look at?

I've built a fully editable table "Grid" in JS and HTML before.. and logic behind it simply is as following:
1- in your table after you layout all your cols, add an action col and add a "edit" link in each row that points to an Edit function, in this Edit link pass the row index so.. it will look like that:
<a href='javascript:void(0)' id='EditBtn' onclick='Edit("+ rowIndex +")'>Edit</a>"
2- your Edit function will simple loop on your columns using that rowIndex and replace the text values with a text box tag
"<input type='text' id='nominal' id='editableField' >" + tdTxt + "</input >"
Just avoid making the "Edit" column Editable
now, you should have a fully editable row..
on last thing, is to Add beside the "Edit" link a "Cancel" link that will loop again on the Row columns like the Edit link and Replace the Text tags with a Span or just pure html with the "" original values..
You may wonder how I will have the origianl td values, well in this case we added a hidden field that carrys the td value, so when the user click cancel after edit. we get the cell original value before edit,
hope that helps.

Disclaimer: This code requires JQuery.
Something like this? http://jsfiddle.net/v2Tdn/3/
$('td').keypress(function (evt) {
if (evt.which == 13) {
evt.preventDefault();
var cellindex = $(this).index()
// get next row, then select same cell index
var rowindex = $(this).parents('tr').index() + 1
$(this).parents('table').find('tr:eq(' + rowindex + ') td:eq(' + cellindex + ')').focus()
}
})
*** UPDATE ***
Note, I've updated the jsfiddle to also select the text when you press enter. For the previous example which only focused on the next TD, please use http://jsfiddle.net/v2Tdn/1/ .

Demo showing how to capture and preventDefault action on enter key press.
Here's the code that does the trick:
$('table').bind('keypress', function (e) {
var code = e.keyCode || e.which;
if (code == 13) {
console.log("Enter pressed");
e.preventDefault();
// focus 'td' in next column using jQuery '.focus()'
}
return false;
});

You have to understand that 'contenteditable' is making your markup behaving like a <textarea>. Normally, people press the tab key to skip from a form field to another.
Using jQuery javascript library, you can read the keyboard for enter key, javascript it to 'escape' the edition by setting focus somewhere else, perhaps the next td with contenteditable. :
$(document).ready(function () {
var $editableTd = $('td[contenteditable]');
$editableTd.bind('keypress', function (e) {
var code = e.keyCode || e.which;
if (code == 13) {
var ind = $editableTd.index(this); //check next td to target
$editableTd.eq(ind + 1).focus(); //set focus to it
e.preventDefault(); //do 'nothing'
}
});
});
jsFiddled here

Related

how to toggle appended elements using multiple buttons and pass info to the output JQuery

I have asked kind of a similar question before : how to toggle using multiple buttons and pass info to the output JQuery
It was answered well, but this time I am using a different approach in the code thus a new question.
I am trying to toggle info and append a div using three different buttons.
Here is The code https://jsfiddle.net/YulePale/nruew82j/40/
JavaScript
document.getElementById("brazil").addEventListener('click', function(e){
if(e.currentTarget.dataset.triggered) return;
e.currentTarget.dataset.triggered = true;
AppendFunction();
function AppendFunction() {
var para = document.createElement("p");
var homeTeam = document.getElementById("brazil").value
para.innerHTML = 'This is the national team of ' + `${homeTeam}` + ':'
<br> <input type="text" value="${homeTeam}" id="myInput"><button
onclick="myFunction()">Copy text</button>';
var element = document.getElementById("gugu");
element.appendChild(para)
}
})
document.getElementById("draw").addEventListener('click', function(e){
if(e.currentTarget.dataset.triggered) return;
e.currentTarget.dataset.triggered = true;
AppendFunction();
function AppendFunction() {
var para = document.createElement("p");
var homeTeam = document.getElementById("draw").value
para.innerHTML = 'This two teams have played each other 4 times ' +
`${homeTeam}` + ':' <br> <input type="text" value="${homeTeam}" id="myInput">
<button onclick="myFunction()">Copy text</button>';
var element = document.getElementById("gugu");
element.appendChild(para)
}
})
document.getElementById("russia").addEventListener('click', function(e){
if(e.currentTarget.dataset.triggered) return;
e.currentTarget.dataset.triggered = true;
AppendFunction();
function AppendFunction() {
var para = document.createElement("p");
var homeTeam = document.getElementById("russia").value
para.innerHTML = 'This is the national team of ' + `${homeTeam}` + ':'
<br> <input type="text" value="${homeTeam}" id="myInput"><button
onclick="myFunction()">Copy text</button>';
var element = document.getElementById("gugu");
element.appendChild(para)
}
})
PS: I don't know why the javascript code is not working in fiddle yet it is working on my computer.
If you look at the code I am basically trying to toggle a div with info on various teams. If it is Brazil the div comes with info on Brazil if Russia, info on Russia.
The problem with my current code is that it keep on appending the divs instead of
toggling them. How can I toggle them? like this: https://jsfiddle.net/YulePale/7jkuoc93/
Instead of having them append another div each time I click a different button?
............................................................................................
PS: EDIT & UPDATE:
#Twisty, I forked the code from your fiddle and tried to implement it when working with more than one row of buttons. The code works well but I was unable to append a different and separate element for each row each time I click on a button on that row.
I tried putting the appended element as a class:
Here is the code: https://jsfiddle.net/YulePale/a9L1nqvm/34/
Also tried putting it as an id:
Here is the code: https://jsfiddle.net/YulePale/a9L1nqvm/38/
How can I put it in a way that each row appends it's own separate element and I would also like users to be able to copy using the copy button without the element disappearing. How do I make it in such a way that the element only disappears only when I click outside the respective:
<div class="col.buttonCol " id="buttons-div">
and also disappears when I click another row of buttons?
Also in your answer you said you would have used text boxes instead of appending this way. I checked the modals out and they all appear on the browser like alerts can you please point me to a resource that show how you can use a modal that works like an appending element instead of one that acts as an alert? Thank you.
Here is the link to the modals I saw: https://getbootstrap.com/docs/4.0/components/modal/
I converted all your JavaScript to jQuery since you posted this in the jquery-ui, I am assuming you want to work with jQuery.
I will often organize my functions first and then the interactive actions.
JavaScript
$(function() {
function myFunction() {
//Do Stuff
}
function AppendFunction(id) {
var para = $("<p>");
var home = $("#" + id).val();
para.append("This is the national team of " + home + ":", $("<br>"), $("<input>", {
type: "text",
value: home,
id: "myInput"
}), $("<button>").html("Copy Text").click(myFunction));
$("#gugu").html(para);
}
function emptyOnDocumentClick(event) {
var action = $(".triggered").length;
$(".triggered").removeClass("triggered");
return !action;
}
$("#brazil, #russia").on('click', function(e) {
if ($(this).hasClass("triggered")) {
return;
}
$(this).addClass("triggered");
var myId = $(this).attr("id");
AppendFunction(myId);
});
$(document).on("click", function(e) {
if (emptyOnDocumentClick(e)) {
$("#gugu").html("");
}
});
});
Working Example: https://jsfiddle.net/Twisty/nruew82j/91/
The basic concept here is a dialog and if it were me, I would use a dialog box either from BootStrap or jQuery UI. You're not doing that, so we're create the content and append it to a specific <div>. Then, like in your previous question, you just detect a click on the document and decide what that will do. In this case, I emptied the content of the <div> that we'd previously appended content to.
Hope that helps.

Toggle switch to pass unchecked value

I'm using a checkbox to create a toggle switch as shown in this tutorial
The switch lives in a form where questions can be added dynamically. On submission the form posts as array of each answer back to the page to be processed however as the off switch doesn't pass a value back to the form the answers get out of sync with the answers for the other text fields. Is there any way to set a value for the off switch, i.e. when a check box is left unchecked?
I've tried to use the following to set my off checkboxes to off however it just seems to animate all the switches to on on form submission, anyone any ideas as to what I'm doing wrong?
$('form').submit(function(e){
var b = $("input:checkbox:not(:checked)");
$(b).each(function () {
$(this).val(0); //Set whatever value you need for 'not checked'
$(this).attr("checked", true);
});
return true;
});
You probably want to use Javascript to set a value for each checkbox "switch" in one of two ways:
Option 1: in the html of the switch elements/checkboxes, set the value attribute to zero by default. Then add a javascript click handler for the toggle to check its current value and toggle to the opposite state/value.
Option 2: add Javascript to the form's submit handler (on submit) that checks for any switch elements which have no values and set them to zero before processing form.
Either way should pass a value at all times, and your form should be able to keep track of all input states.
This snippet did the trick, as Anson suggested this finds all the checkboxes and sets them to either on or off on form submission:
$('form').submit(function () {
$(this).find('input[type="checkbox"]').each( function () {
var checkbox = $(this);
if( checkbox.is(':checked')) {
checkbox.attr('value','1');
} else {
checkbox.after().append(checkbox.clone().attr({type:'hidden', value:0}));
checkbox.prop('disabled', true);
}
})
});

Tab index not working for some elements

I have form in which I have data picker, and select2 (customize drop down to search) and many inputs, text area fields when I press tab button to move the next field its working fine but when next field is date picker or select2 then tab index is not working I want generically solution and in all browsers.
currently i am doing static solution like to get id of one div then Prop tab index with 1 value.
$scope.focusFunctionZipV = function(Id){
var div = '#' + Id;
$(div).prop('tabindex', '1');
$(div).select2('open');
//zipV is a div having zip code with select2
if(div == '#zipV'){
$('.datepicker-simple').prop('tabindex', '0');
}
}
You should get the id select2 ID then on close event refer focus to next field.
$('#currentDiv').select2().on("select2:close", function (e) {
$('#nextDiv').focus()
});
and for date picker
$('#ID').datepicker({
onSelect: function(dateText, inst) {
$('#nextIDdiv').focus();
}
});
and for simple input fields tab is working fine.

How do you tab through text in html text input?

So I need a way of being able to tab to the next line in an html text input without it skipping to the next html input, is this possible?
You can do it by Jquery:
Activating next input field in form on enter
Focus on next input field inside table with enter key press
focusNextInputField With jsfiddle demo
Easiest one is:
$("input").change(function() {
var inputs = $(this).closest('form').find(':input');
inputs.eq( inputs.index(this)+ 1 ).focus();
});
If these solutions doesn't help then provide your code, so that it will be easier to understand.
If you really are trying to MAKE a textarea field where users can tab, you don't need jQuery.
See this jsFiddle : http://jsfiddle.net/2wAzx/13/
function enableTab(id) {
var el = document.getElementById(id);
el.onkeydown = function(e) {
if (e.keyCode === 9) { // tab was pressed
// get caret position/selection
var val = this.value,
start = this.selectionStart,
end = this.selectionEnd;
// set textarea value to: text before caret + tab + text after caret
this.value = val.substring(0, start) + '\t' + val.substring(end);
// put caret at right position again
this.selectionStart = this.selectionEnd = start + 1;
// prevent the focus lose
return false;
}
};
}
// Enable the tab character onkeypress (onkeydown) inside textarea...
// ... for a textarea that has an `id="my-textarea"`
enableTab('my-textarea');
Also, if that is your question, i'd recommend marking it as a duplicate since it has been asked more than once on SO...

How do i make a button that can count when a user clicks it?

I am new to coding and I would like to make a button that increment the count by 1 when a user clicks on it. I also would like to know how can I restrict it to be clicked only once. It is similar to the facebook like button but I want to create my custom button that would do the same thing but will just be shown in my website.
Here is the thing, using jQuery. The HTML part would be as under
<button>Click Me</button>
The jQuery code, that would be added to the <script> tag in <head> section.
var click = "1"; // set the variable
$('button').click(function () { // click on button
$(this).text('Clicked ' + click + ' times'); // write the variable value in it
click ++; // increment the variable
}
http://jsfiddle.net/afzaal_ahmad_zeeshan/jRXBr/4/ (For testing; as per Pippin's suggestion)
To disable it, use
$('button').click(function () { // click on button
$(this).prop('disabled', true); // set its disabled property to true
}
http://jsfiddle.net/afzaal_ahmad_zeeshan/jRXBr/1/ (For testing)
You can test the codes, using the fiddles that I have created, and you will understand how they work! :)