i am tyring to insert textboxes to create empty rows but i want first textbox should be of 50px only
i am creating them onclick event of a button using DOM approach
how to define the width with respect to following approach
j is a variable being handled somewhere & cols is no: of columns to be created
for(var t=1;t<=cols;t=t+1)
{
var cell = row.insertCell(t);
var element = document.createElement("input");
element.type = "text";
element.id= 'text['+j+']['+(t)+']';
element.name= 'text['+j+']['+(t)+']';
element.value="";
cell.appendChild(element);
}
some times it may works
element.style.width = width + 'px';
try it once in case the above suggestions fails
or by using this,
element.setAttribute("style","width:50px");
Try the following:
In CSS:
.firsttext
{
width: 50px;
}
In Javascript:
if (t==1)
{
element.className = "firsttext";
}
Related
I wrote a html/php page in order to update database content. The page has several forms (one for each db row I need to edit), and every form has several textarea fields.
I would like to fit every textarea's height to its content (as retrieved from db), using pure JavaScript (no jQuery).
I've found the following JS function:
function autoResize() {
this.style.height = 'auto';
this.style.height = this.scrollHeight + 'px';
}
But how can I use it for every textarea field in the page? Is there a better way to achieve the goal?
Thanks!
UPDATED
Maybe this is a good solution:
var els = document.querySelectorAll('textarea');
Array.from(els).forEach((el) => {
var offset = el.offsetHeight - el.clientHeight;
el.style.height = 0;
el.style.height = el.scrollHeight + offset + 'px';
el.addEventListener('input', function() {
el.style.height = el.scrollHeight + offset + 'px';
});
});
Could it be done in a better way?
Check out this snippet:
<script>
var content = document.getElementsByClassName('db-content');
for(var i=0; i<content.length; i++){
content[i].style.height = 'auto';
content[i].style.height = content[i].scrollHeight + 'px';
}
</script>
You have to apply same class to all <textarea> (db-content in the above snippet) and add this script after them. In the script we are looking for all of those <textarea> by their class name and storing them in an array. Next we loop through the array and apply style to all <textarea>.
I am trying to do append() function. i have a table of data. i run a loop to first remove text in cell then i will append a new tag.this usecase is to create a progress bar. for an example
data sample inside cell is e.g 39% 39% 82% etc etc
let cf_percent;
let cf_regex;
for(let i = 0 ;i < tbl[0].length;i++){
cf_percent = tbl[0][i].innerHTML
cf_regex = cf_percent.replace(/[`~%]/gi, '');
console.log(cf_regex)
//Clear fields
tbl[0][i].innerHTML = ''
tbl[0][i].append('<p>Textfield</p>');
}
It should return texfield but instead, it is returning '<p> textfield </p>' in table cell.it should return textField. i have tried .html() but this does not work for this usecase.
in d3.js append function appends a new element with the specified name as the last child of each element in the current selection, returning a new selection containing the appended elements.
So to append p element use: tbl[0][i].append("p") and to set text use .text() further: e.g.
tbl[0][i].append("p").text("Textfield")
I will suggest to use:
let cf_percent;
let cf_regex;
for(let i = 0 ;i < tbl[0].length;i++){
cf_percent = tbl[0][i].innerHTML
cf_regex = cf_percent.replace(/[`~%]/gi, '');
console.log(cf_regex)
//Clear fields
tbl[0][i].innerHTML = ''
tbl[0][i].innerHTML += `<p>Textfield</p>`;
}
You have 2 options. The first is along what you are trying to do where you set the innerHTML to a string. The second is actually generating an element and then appending it. Your current scenario seems to be mixing the two.
const div1 = document.getElementById('sample1'),
div2 = document.getElementById('sample2'),
p = document.createElement('p');
div1.innerHTML = '<p>This set the innerHTML</p>';
p.innerText = 'This is a p appended to a div';
div2.appendChild(p);
#sample1 {
background-color: red;
}
#sample2 {
background-color: yellow;
}
<div id="sample1"></div>
<div id="sample2"></div>
I have some buttons that look like this.
It is a "whitelist" of websites. I'd like for the button to remove the corresponding site from the whitelist.
However, since these buttons are generated with each addition of a site (entered by the user), I don't know how to get the ElementID to use in my function.
Here is where the button is generated:
var cellWebsite = document.createElement("td");
var website = document.createTextNode(array[i]);
//append cell text to cell, then cell to row (like setting a "stage")
cellWebsite.appendChild(website);
row.appendChild(cellWebsite);
//create a cell & cell text for BUTTON
var cellDelete = document.createElement("td");
var button = document.createElement("BUTTON"); //has its own element
var text = document.createTextNode("x");
button.appendChild(text);
cellDelete.appendChild(button);
row.appendChild(cellDelete);
How do I get the ID so I can write a function for when the X button is clicked? Within that function, how can I get the website that corresponds to that button?
I'm making a Chrome Extension and using chrome's local storage, if it matters.
The easiest way is to add an event listener the button variable like so:
const btn = document.createElement('button');
btn.innerText = "Click me!";
btn.addEventListener('click', function(event) {
console.log('Fired!');
});
I cannot seem to comment since I need 50 rep. for it, but can't you give it an increment? With each add just increment the ID or name with 1, and then u could target the ID or name.
Check the inspection view of your browser and see if id and other attributes are set.
If this didn't work, make use of the form id attribute the index of the element as፡
var x = document.getElementById("myForm").elements[0].value;
If no id provided for form:
var x = document.forms[0].id;
Or
var x = document.forms.item(0).id;
When your element is dynamically created, You should event delegation to handle event.
Event delegation allows you to avoid adding event listeners to specific nodes; instead, the event listener is added to one parent. That event listener analyzes bubbled events to find a match on child elements.
Example:
var counter = -1;
function addRow() {
counter++;
var table = document.getElementById( 'myTable' ),
row = table.insertRow( counter ),
cell = row.insertCell( 0 ),
cellDelete = row.insertCell( 1 ),
button = document.createElement( 'button' ),
text = document.createTextNode( 'X' );
cell.innerHTML = 'wikipedia.org ' + counter;
button.appendChild( text );
cellDelete.appendChild( button );
button.addEventListener( 'click', function ( e ) {
table.deleteRow( e.target.parentNode.parentNode.rowIndex );
counter--
} )
}
body {
margin: 0
}
table {
width: 100%
}
td {
padding: 8px;
border-bottom: 1px solid #ddd
}
td:nth-child(even) {
text-align: right
}
tr:nth-child(odd) {
background-color: #efefef
}
<button type="button" onclick="addRow()">Add new row</button>
<br>
<table id="myTable"></table>
I am making a todo list so I am adding new input tags with checkboxes on them so I can check off a to do list item. I am having trouble modifying the css so that the text displays a line through it when it is checked.
The check function works and it runs but I am unable to put a line through the specific html element.
var add = function() {
var task = $("#taskTextBox").val(); // references the value inside #task
if(task != ""){
inc++;
var itemName = "item" + inc;
var newObj = $("#list").append("<input id="+itemName+" type=checkbox class="+itemName+">"+task+"<br></br>");// makes a new <p> element
$("#taskTextBox").val(""); // empties out #task
var newHeight = $("#list").height() + 40;
$("#list").css({"height": newHeight});
addAttributes();
$("input[class=" + itemName + "]").change(function () {
if ($(this).prop("checked")) {
$("input[class=" + itemName + "]").css({'text-decoration': 'line-through'});
} else{
$("#list").css({"text-decoration": "none"});
}
});
}};
EDIT:
I forgot to mention that your code is not working because you are adding your class to the input which is just affecting the checkbox style not the text following it.
For my code to work you just need to modify this line, adding a span to wrap your task. You do not need the change function anymore.
var newObj = $("#list").append("<input id="+itemName+" type=checkbox class="+itemName+"><span>"+task+"</span><br></br>");// makes a new <p> element
SOLUTION:
You can achieve this with plain CSS using :checked pseudo-class and using a span or any other tag that can be used as a selector directly following your input:
JSFiddle
CODE SNIPPET:
.example:checked + span {
text-decoration: line-through;
}
<input class="example" type="checkbox"><span>Eggs</span>
<input class="example" type="checkbox"><span>Milk</span>
I'm working on a web app where I need to add a number of input boxes one after the other in order to get commands from the user. I add them using JavaScript to a div with a unique ID to each. The problem I have is once I press enter and the JavaScript function is called to add the next one, the previous input box empties out, and I don't know why.
Here is sample code:
var i = 0;
add_input();
function add_input() {
i++;
document.getElementById('main').innerHTML += "<p>> <input type='text' style='width:90%' id='input" + i + "' onkeypress='press_key(event, this)'></p>";
document.getElementById('input' + i).focus();
}
function press_key(e, t) {
if (e.keyCode == 13) {
add_input();
}
}
<div id='main'></div>
innerHTML will override all existing content and replace them with new ones. You should create a new input element and use insertNode instead.
The addition assignment operator will add the right hand value to the left hand value and then assign the resultant value to the left hand side.
For a quick example:
x += y;
// is equivalent to
x = x + y;
In your code you are basically taking the existing HTML, adding a new chunk of HTML and then assigning that new HTML to the original element replacing the existing HTML. Since the value is not set in the HTML but stored in the DOM it is lost as soon as you assign new HTML to the element (which is when the browser renders it to the DOM replacing the previous DOM).
You could use insertNode as mentioned above or set the HTML attribute to store the value first as the below example shows. However note that this solution is purely to show why the values are disappearing. Doing it this way has an issue that if any of the previous input values are changed only the original value for those inputs would be preserved.
var i = 0;
add_input();
function add_input() {
var curInput = document.getElementById('input' + i);
if (curInput) {
curInput.setAttribute('value', curInput.value);
}
++i;
document.getElementById('main').innerHTML += "<p>> <input type='text' style='width:90%' id='input" + i + "' onkeypress='press_key(event, this)'></p>";
document.getElementById('input' + i).focus();
}
function press_key(e, t) {
if (e.keyCode == 13) {
add_input();
}
}
<div id='main'></div>
innerHTML overwrites all html from the selected element including any user/javascript actions performed on the given html. Thus your input values will be erased with the new html. You are going to want to create an element and then use appendChild. This will maintain the state of your current html elements.
var i = 0;
function add_input()
{
i++;
var input = document.createElement('input');
input.onkeypress=press_key;
input.id = 'input' + i;
document.body.appendChild(input);
input.focus();
}
function press_key(e)
{
//`t` argument is no longer used. Use `this` instead.
if (e.keyCode == 13)
{
add_input();
}
}
<html>
<head>
<script>
</script>
</head>
<body onload='add_input()'>
<div id='main'>
</div>
</body>
</html>
As stated above, your other values disappear due to the inner workings of "innerHTML". In fact, when you do string.innerHTML += string it will replace the HTML for it (meaning what was there before is totally gone and is de-facto replaced with fresh new HTML).
What you want to use is probably appendChild().
With little rewriting I have managed to make your code work:
http://jsfiddle.net/gs1s0fsx/
var i = 0;
function add_input() {
i++;
var main = document.getElementById('main'),
p = document.createElement("p"),
arrow = document.createTextNode('>'),
el = document.createElement('input');
el.type = "text";
el.style = "width:90%";
el.id = "input" + i;
el.addEventListener("keypress", press_key);
main.appendChild(p);
main.appendChild(arrow);
main.appendChild(el);
el.focus();
}
function press_key(e, t) {
if (e.keyCode == 13) {
add_input();
}
}
add
<div id='main'></div>
Hope this helps.