I have an html table with rows, in one of the cells I want to be able to insert an input text inside the cell whenever it is double clicked, and when this input is onblured I want to remove it and see it's value inside the td.
This is my code:
<td dir='ltr' id='test1' class='tLine' nowrap ondblclick='addInput(this);'>sdadfew</td>
function addInput(xxx) {
var id = xxx.id;
var value = document.getElementById(id).innerHTML;
document.getElementById(id).innerHTML = "<input type='text' id='input"+id +"' value='"+value+"' onblur='closeInput("+id+")'/>";
document.getElementById("input"+id).focus();
}
function closeInput(id) {
var value = document.getElementById('input'+id).value;
document.getElementById(id).innerHTML = value;
}
The problem is when I double click the input I get the text of the input inside of it.
How can I prevent this from happening? How can I resolve this issue?
UPDATE:
Inside the input I see this text:
<input type='text' id='input"+id +"' value='"+value+"' onblur='closeInput("+id+")'/>
Sorry for misunderstanding, this is the pure javascript version
javascript code
function closeInput(elm) {
var td = elm.parentNode;
var value = elm.value;
td.removeChild(elm);
td.innerHTML = value;
}
function addInput(elm) {
if (elm.getElementsByTagName('input').length > 0) return;
var value = elm.innerHTML;
elm.innerHTML = '';
var input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('value', value);
input.setAttribute('onBlur', 'closeInput(this)');
elm.appendChild(input);
input.focus();
}
html code
<table>
<tr>
<td dir="ltr" id="test1" class="tLine" nowrap ondblclick="addInput(this)">sdadfew</td>
</tr>
</table>
jquery version still at http://jsfiddle.net/ZLmgZ/
Please have a look at this link
I have added some code on your function.
function addInput(xxx) {
xxx.setAttribute("ondblclick","return false");
var id = xxx.id;
var value = document.getElementById(id).innerHTML;
document.getElementById(id).innerHTML = "<input type='text' id='input"+id +"' value='"+value+"' onblur='closeInput("+id+")'/>";
document.getElementById("input"+id).focus();
}
Let me know if its work for you.
Related
I have some code that displays the JSON and allows the user to edit the text. After editing, I want to allow the user to click a button to save the new input value. Everything works as expected except for grabbing that new input value.
for (let i = 0; i < jsonObject.results.length; i++) {
var row = `<tr scope="row" class="test-row-${jsonObject.results[i].id}">
<td id="fName-${jsonObject.results[i].id}" data-testid="${jsonObject.results[i].id}">${jsonObject.results[i].firstName}</td>
// some code
$(`#save-${jsonObject.results[i].id}`).click(function(){
clickAButton(jsonObject.results[i].id, jsonObject, i);
});
$(`#fName-${jsonObject.results[i].id}`).on('click', editResult)
}
function editResult(){
var testid = $(this).data('testid')
var value = $(this).html()
$(this).unbind()
$(this).html(`<input class="result form-control" data-testid="${testid}" type="text" value="${value}">`)
}
function clickAButton() {
var text = $(`#fName-${jsonObject.results[index].id}`).val();
console.log("text from " + text);
// code
}
the code above displays
text from
How do I get it to display the new user input?
Instead of writing mutliple event handler for all tds and button you can use only one event handler for button and td . So, when td is clicked just remove data-testid attribute from td so that again that event will not get called and to get input value use $(this).closest('tr').find('.result').val() this will give you input value where save button is clicked.
Demo Code :
var jsonObject = {
"results": [{
"id": 1,
"firstName": "sas"
}, {
"id": 2,
"firstName": "cd"
}]
}
for (let i = 0; i < jsonObject.results.length; i++) {
var row = `<tr scope="row" class="test-row-${jsonObject.results[i].id}">
<td id="fName-${jsonObject.results[i].id}" data-testid="${jsonObject.results[i].id}">${jsonObject.results[i].firstName}</td><td><input type='button' id='save-${jsonObject.results[i].id}' value ='save'></td></tr>`
$("table").append(row)
}
$(document).on('click', 'td[data-testid]', function() {
var testid = $(this).data('testid')
var value = $(this).html()
$(this).html(`<input class="result form-control" data-testid = "${testid}" type = "text"
value = "${value}" >`)
//removed data-testid
$(this).removeAttr("data-testid");
})
$(document).on('click', '[id*=save-]', function() {
//use class to find input
var text = $(this).closest('tr').find('.result').val();
console.log("text from " + text);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
</table>
I have the following code
<tr val='question'>
<td>
<input style='width: 500px' type='text' placeholder='Q.Enter your question here for radio button? '>
</tr>
How can i find the value of input box embedded in cell .
function saveUserDefQues(){
var table=document.getElementById("QuestionList");
var surveyquestionform=document.forms[0];
var count=$('#QuestionList tr').length
for (var i = 0; i<count; i++) {
var row = table.rows[i];
if(row.getAttribute('val')==='question')
{
var Cells = row.getElementsByTagName("td");;
}
}
}
document.querySelector('tr[val] > td > input').value;
Array.from(document.querySelectorAll('tr[val] > td > input')).forEach(function(entry, index, entries)
{
entry.value; // you may store the value OR process with it AS you see fit
});
Since you are using Jquery this can be done this way.
replace this line of code
var Cells = row.getElementsByTagName("td");
with
var Cells = $(row).find('td');
var inputValue = Cell.find('input').val(); // gives you value of input
Code Refactoring recommended
I would like to refactor your code as below
HTML
<tr data-val='question'> // use data-* attribute to add custom attributes into tags
<td>
<input style='width: 500px' type='text' placeholder='Q.Enter your question here for radio button? '>
</td> // close your td
</tr>
Script
function saveUserDefQues(){
var surveyquestionform = document.forms[0]; // not sure what this is for, so ill leave it as is.
$('#QuestionList tr[data-val="question"]').each(function(){ //loop all tr's which has the data-val set to question
var inputValue = $(this).find('td input').val(); //get the value of input
console.log(inputValue);
});
}
$("tr[val='question'] > td > input").val()
But first you need to write a valid HTML. </td> closing tag is missing. Also you need to put this tr in a <table>.
See this Plunker
function getResult(){
$( "tr" ).each(function( index ) {
console.log($(this).find('input').attr('placeholder') );
});
}
HTML:
<table id="table">"
</table>
<input type="text" id="text1">
<input type="text" id="text2">
<input type="text" id="text3">
<button onclick="addRow()">Add Row</button>
Add Row Function:
function appendRow() {
var table = document.getElementById("table");
{
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
cell1.innerHTML = "<p onclick=\"bold()\">words</p>;
}
}
Currently empty bold function
function bold() {
}
When the text in a cell is clicked I want to make it bold, however I'm not quite sure how I would do this due to the lack of id values from having dynamically created the content of the cells.
How would I do this?
Try this:
//add parameter into onclick trigger function
cell1.innerHTML = "<p onclick=\"bold(this)\">words</p>";
function bold(obj){
//using the innerHTML to change content
obj.innerHTML = '<b>' + obj.innerHTML + '</b>';
// OR using CSS
obj.style.fontWeight = "bold"; //thx René Roth comments
}
cell1.innerHTML = "<p onclick=\"bold(this)\">words</p>;
Script:
function bold(obj) {
obj..style.fontWeight="bold";
}
I'm currently working on some input forms in JavaScript, and I've edited by script so that once the user enters the number of forces for a problem, new input text fields show up per number, also there is a button which is added at the end of that. The issue is when I try and click this button, I try and use the .map function to start all text field values into it and nothing is happening.
function forceRecording(numofforces,$this){
var addRows='<tr id=newRows>';
for(var i =1; i<=numofforces;i++)
{
var nearTr=$this.closest('tr');
addRows=addRows + "<td>Force " +i+": </td><td><form><input type='text' name='forceItem' id='newR'/></form></td>";
}
addRows=addRows+"<td><div class='button' id='forceButton'> Add! </div></td></tr>";
nearTr.after(addRows);
};
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val()
});
function forceRecording(numofforces,$this){
var addRows='<tr id=newRows>';
for(var i =1; i<=numofforces;i++)
{
var nearTr=$this.closest('tr');
addRows=addRows + "<td>Force " +i+": </td><td><form><input type='text' name='forceItem' id='newR'/></form></td>";
}
addRows=addRows+"<td><div class='button' id='forceButton'> Add! </div></td></tr>";
nearTr.after(addRows);
};
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val()
});
prompt("forces");
});
As you can see my forceRecording function is working and creates a new row with new text input fields per the numofforces but once I try clicking the forceButton to enter the values into my forces array nothing happens. Any idea what could be causing this?
You are missing the closing paranthesis around your code here
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){return $(this).val()
});
It should be like this
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val();
});
});
And don't use the id instead use a class name
$('#forceButton').click(function(){
forces=$(".newR").map(function(){
return $(this).val();
});
});
Apply the class to input field like this
<input type="text" name="forceItem" class="newR"/>
I have absolutely no idea what you're trying to achieve, but maybe this will help:
function forceRecording(numofforces, $this) {
var addRows = '<tr id="newRows">';
for (var i = 1; i <= numofforces; i++)
addRows += '<td>Force ' + i + ': </td><td><input type="text" name="forceItem" /></td>';
addRows += '<td><input type="button" class="button" id="forceButton" value="Add!" /></td></tr>';
$this.closest('tr').after(addRows);
}
$('#forceButton').click(function() {
forces = $(this).parent().parent().filter('input[name="forceItem"]').map(function() { return $(this).val(); });
});
I want to add some html data to the end of a div container.
Currently, I do it with using innerHtml:
<script language="javascript">
var addid = 0;
function addInput(id){
var docstyle = document.getElementById('addlist').style.display;
if(docstyle == 'none')
document.getElementById('addlist').style.display = '';
addid++;
var text = "<div id='additem_"+addid+"'><input type='text' size='100' value='' class='buckinput' name='items[]' style='padding:5px;' /> <a href='javascript:void(0);' onclick='addInput("+addid+")' id='addlink_"+addid+"'>add more</a></div>";
document.getElementById('addlist').innerHTML += text;
}
</script>
<div id="addlist" class="alt1" style="padding:10px;">
New list items are added to the bottom of the list.
<br /><br />
</div>
The problem is that the value that was entered in the input fields is removed once another input field is added.
How can I add content without and keep the entered data?
PS: I do not use jquery.
innerHTML changes reset form elements. Instead use appendChild. See this demo http://jsfiddle.net/5sWA2/
function addInput(id) {
var addList = document.getElementById('addlist');
var docstyle = addList.style.display;
if (docstyle == 'none') addList.style.display = '';
addid++;
var text = document.createElement('div');
text.id = 'additem_' + addid;
text.innerHTML = "<input type='text' value='' class='buckinput' name='items[]' style='padding:5px;' /> <a href='javascript:void(0);' onclick='addInput(" + addid + ")' id='addlink_" + addid + "'>add more</a>";
addList.appendChild(text);
}
Take a look at this http://reference.sitepoint.com/javascript/Node/appendChild
So something like
document.getElementById('addlist').appendChild(text);