I am not sure what it is called, but I want to be able to click on e.g. a div
containing a number, and then it will change into a input text field, with the val
You can do the following:
Have a click event and create a textbox on the fly which takes the text inside the div as a value.
The have a blur even which binds to that textbox and makes an AJAX call and in its success change the div text
Lets say your HTML is like:
<div id="fullname">Amazing Spider man</div>
And your JS code will be like:
$('#fullname').click(function(){
var name = $(this).text();
$(this).html('');
$('<input></input>')
.attr({
'type': 'text',
'name': 'fname',
'id': 'txt_fullname',
'size': '30',
'value': name
})
.appendTo('#fullname');
$('#txt_fullname').focus();
});
$(document).on('blur','#txt_fullname', function(){
var name = $(this).val();
$.ajax({
type: 'post',
url: 'change-name.xhr?name=' + name,
success: function(){
$('#fullname').text(name);
}
});
});
This is demostrated in this jsfiddle
There is jEditable: http://www.appelsiini.net/projects/jeditable
However, X-editable looks much nicer: http://vitalets.github.io/x-editable/
HTML5 has a contentEditable
attribute with pretty good browser support, so you may want to explore this first if it aligns with your situation and if you want to do no-jquery. Simply putting contentEditable="true"
in a div will make it clickable and editable (basic text).
To make practical use of the editable element, you'll need to use JS to watch the element and trigger an action when there's input. In the OP's case, in JS they would place the newly-edited content somewhere (like an array) ready for an ajax function to send it out to an external database. More info here and here.
Also, here's a plugin that takes it further and gives more WYSIWYG controls for these fields.
Anyways, here's a sample code, no plugins, no jquery:
var myEditableElement = document.getElementById('myContent');
myEditableElement.addEventListener('input', function() {
console.log('An edit input has been detected');
console.log(myEditableElement.innerHTML);
});
<div id="myContent" contentEditable="true">This is an editable element. Click and type something!</div>
You named the whole process already.
First, assign all of your numbers or fields with some class.
<div class="editable">value</div>
Then, assign that class a click event.
$('.editable').click(function(){
//replace element with input element containing the value
//attach an onblur event to the new element
$(newelement).blur(function(){
//use $.ajax to send the element's value to your server
//remove the input element and then replace the previous element with the new value
});
});
It is called jQuery edit in place. There are a number of plugins available from jQuery for that.
Why not just stay with one input field, and change the field styles on blur. You can take everything away so it doesnt look like an input, that way there's no need to change back and forth. Make an Ajax call on blur.