How to connect input filed, button, and function JS - javascript

i am learning JS right now, and I don't know how to connect input filed, button, and function. In currently code if I run it i get result of specific string which is in code, so i want to enter random string in input field, and when i click on button get result of that input string.
<input type="text" id="myText" value="String">
<p>Click the "Try it" button</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myText").value;
document.getElementById("demo").innerHTML = x;
let l = str.length;
let k = 0, row, column;
row = Math.floor(Math.sqrt(l));
column = Math.ceil(Math.sqrt(l));
if (row * column < l)
{
row = column;
}
let s = new Array(row);
for (let i = 0; i < row; i++)
{
s[i] = new Array(column);
for (let j = 0; j < column; j++)
{
s[i][j] = 0;
}
}
// convert the string into grid
for (let i = 0; i < row; i++)
{
for (let j = 0; j < column; j++)
{
if(k < str.length)
s[i][j] = str[k];
k++;
}
}
// Printing the grid
for (let i = 0; i < row; i++)
{
for (let j = 0; j < column; j++)
{
if (s[i][j] == 0)
{
break;
}
document.write(s[i][j]);
}
document.write("</br>");
}
}
let str = "GEEKSFORGEEKS";
gridStr(str);
}
</script>

I got it. Now, you have written unnessesary code there.
<body>
<input type="text" placeholder="Enter Any String" id="str-to-grid">
<br>
<button onClick="stringToGrid()">Try It</button>
<p id="grid-placeholder"></p>
<script>
const Input = document.getElementById("str-to-grid")
const Placeholder = document.getElementById("grid-placeholder")
function stringToGrid() {
//first, let's determine the number of rows and columns we can arrange
//Usually, in grid, x = y, meaning sqrt(length)
var dimension = Math.ceil(Math.sqrt(Input.value.length))
//Now let's arrange our string:
var GridView = []
for ( let stringPtr = 0, dimensionPtr = 0; stringPtr < Input.value.length; stringPtr++)
{
GridView.push(Input.value[stringPtr])
if ( (dimensionPtr + 1)%dimension === 0 )
{
GridView.push("<br />")
}
dimensionPtr++;
}
Placeholder.innerHTML = GridView.join("")
}
</script>
</body>
What this code does is everytime you clicked the button, the placeholder
and the value is taken, and the dimension of the grid is calculated to the upperbound square of the length of the string.
Then is a seperate array, each of the string item is placed, and when the row
ends, a br tag is added. this way, a grid view can be created

This is the improved code: (it will work)
<input type="text" id="myText" value="String">
<p>Click the "Try it" button</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myText").value;
document.getElementById("demo").innerHTML = x;
let l = str.length;
let k = 0, row, column;
row = Math.floor(Math.sqrt(l));
column = Math.ceil(Math.sqrt(l));
if (row * column < l)
{
row = column;
}
let s = new Array(row);
for (let i = 0; i < row; i++)
{
s[i] = new Array(column);
for (let j = 0; j < column; j++)
{
s[i][j] = 0;
}
}
// convert the string into grid
for (let i = 0; i < row; i++)
{
for (let j = 0; j < column; j++)
{
if(k < str.length)
s[i][j] = str[k];
k++;
}
}
// Printing the grid
for (let i = 0; i < row; i++)
{
for (let j = 0; j < column; j++)
{
if (s[i][j] == 0)
{
break;
}
document.write(s[i][j]);
}
document.write("</br>");
}
}
let str = "GEEKSFORGEEKS";
gridStr(str);
</script>

Related

.innerHTML edits HTML but doesnt display

so I have a bit of code that generates a few spans for display of a few range inputs but when the span is edited it shows as if it were edited in the console but not the page
for (var i = 0; i < 5; i++) {
text = document.createElement('span')
span[pos][i] = text;
console.log(text)
div.innerHTML += list[i]
text.setAttribute("id",`${pos}0${i}`)
div.appendChild(text);
div.appendChild(space);
}
div.appendChild(document.createElement('p'))
for (var i = 0; i < 5; i++) {
space = document.createElement('span')
space.setAttribute("style","padding-left: 40px")
slider = document.createElement('input')
range[pos][i] = slider;
slider.setAttribute("type","range")
slider.setAttribute("id",`${pos}1${i}`)
div.appendChild(slider);
div.appendChild(space);
console.log(div, i)
}
for (var i = range.length - 1; i >= 0; i--) {
for (var j=0; j<5; j++) {
span[i][j].innerHTML = range[i][j].value;
//console.log(j)
}
}
I don't understand what you are going to do with the 5 sliders?
var range = [];
var span = [];
function init() {
var div = document.createElement('div');
for (var i = 0; i < 5; i++) {
var text = document.createElement('span');
span[i] = text;
console.log(text);
//div.innerHTML += list[i]
text.setAttribute("id",`txt0${i}`);
div.appendChild(text);
var space = document.createElement('span');
div.appendChild(space);
}
div.appendChild(document.createElement('p'))
for (var i = 0; i < 5; i++) {
var space = document.createElement('span');
space.setAttribute("style","padding-left: 40px");
var slider = document.createElement('input');
range[i] = slider;
slider.setAttribute("type","range");
slider.setAttribute("id",`slider1${i}`);
div.appendChild(slider);
div.appendChild(space);
console.log(div, i)
}
for (var i = range.length - 1; i >= 0; i--) {
for (var j=0; j<5; j++) {
span[i].innerHTML = range[i].value;
//console.log(j);
}
}
document.body.appendChild(div);
}
<body onload="init()">
</body>

Translate web page using javascript

I tried to translate my web page using js but my code is not working here my code
<div class="navLan">
EN
<!-- <hr> -->
RU
<!-- <hr> -->
UZ
</div>
where user select languages and i used key to give attr to the element like this
<div class="listGroup">
<a href="#row3" class="hvr-grow nav-link lang" key='about'>About</a>
Courses
<a href="#row5" class="nav-link lang" key='reg'>Registration</a>
<a href="#row6" class="nav-link lang" key='news'>News</a>
<a href="#row7" class="nav-link lang" key='feedback'>Feedback</a>
<a href="#row8" class="nav-link lang" key='contact'>Contacts</a>
<div class="hr"></div>
</div>
at the end of the code in script tag i gave translation like this
var arrLang = {
'menu-item_en': {
'about':'About',
'courses':'Courses',
'reg':'Registration',
'news':'News',
'feedback':'Feedback',
'contact':'Contacts'
},
'menu-item_ru': {
'about':'About',
'courses':'Courses',
'reg':'Registration',
'news':'News',
'feedback':'Feedback',
'contact':'Contacts'
},
'menu-item_uz': {
'about':'Biz Haqimizda',
'courses':'Kurslar',
'reg':'Ro\'yxatdan o\'tmoq',
'news':'Yangiliklar',
'feedback':'Fikr-Mulohaza',
'contact':'Aloqa'
}
}
finally my js file here
function change_language(id) {
var lang = id;
document.cookie = "lang=" + lang + ";";
var elementss = document.getElementsByClassName('lang');
var placeholders = document.getElementsByClassName('placeholders');
if (document.cookie.split(';').filter(function (item) {
return item.indexOf('lang=menu-item_en') >= 0
}).length) {
for (let i = 0; i < elementss.length; i++) {
elementss[i].innerHTML = arrLang['menu-item_en'][elementss[i].getAttribute('key')];
}
for (let g = 0; g < placeholders.length; g++){
placeholders[g].setAttribute('placeholder', arrLang['menu-item_en'][placeholders[g].getAttribute('key')]);
}
} else if (document.cookie.split(';').filter(function (item) {
return item.indexOf('lang=menu-item_uz') >= 0
}).length) {
for (let i = 0; i < elementss.length; i++) {
elementss[i].innerHTML = arrLang['menu-item_uz'][elementss[i].getAttribute('key')];
}
for (let g = 0; g < placeholders.length; g++){
placeholders[g].setAttribute('placeholder', arrLang['menu-item_uz'][placeholders[g].getAttribute('key')]);
}
} else {
for (let i = 0; i < elementss.length; i++) {
elementss[i].innerHTML = arrLang['menu-item_ru'][elementss[i].getAttribute('key')];
}
for (let g = 0; g < placeholders.length; g++){
placeholders[g].setAttribute('placeholder', arrLang['menu-item_ru'][placeholders[g].getAttribute('key')]);
}
}
};
(function () {
var elementss = document.getElementsByClassName('lang');
var placeholders = document.getElementsByClassName('placeholders');
var inputs = document.getElementsByClassName('inputs');
if (document.cookie.split(';').filter(function (item) {
return item.indexOf('lang=menu-item_en') >= 0
}).length) {
for (let i = 0; i < elementss.length; i++) {
elementss[i].innerHTML = arrLang['menu-item_en'][elementss[i].getAttribute('key')];
}
for (let g = 0; g < placeholders.length; g++){
placeholders[g].setAttribute('placeholder', arrLang['menu-item_en'][placeholders[g].getAttribute('key')]);
}
for (let j = 0; j < inputs.length; j++){
inputs[j].setAttribute('value', arrLang['menu-item_en'][inputs[j].getAttribute('key')]);
}
} else if (document.cookie.split(';').filter(function (item) {
return item.indexOf('lang=menu-item_uz') >= 0
}).length) {
for (let i = 0; i < elementss.length; i++) {
elementss[i].innerHTML = arrLang['menu-item_uz'][elementss[i].getAttribute('key')];
}
for (let g = 0; g < placeholders.length; g++){
placeholders[g].setAttribute('placeholder', arrLang['menu-item_uz'][placeholders[g].getAttribute('key')]);
}
for (let j = 0; j < inputs.length; j++){
inputs[j].setAttribute('value', arrLang['menu-item_uz'][inputs[j].getAttribute('key')]);
}
} else {
for (let i = 0; i < elementss.length; i++) {
elementss[i].innerHTML = arrLang['menu-item_ru'][elementss[i].getAttribute('key')];
}
for (let g = 0; g < placeholders.length; g++){
placeholders[g].setAttribute('placeholder', arrLang['menu-item_ru'][placeholders[g].getAttribute('key')]);
}
for (let j = 0; j < inputs.length; j++){
inputs[j].setAttribute('value', arrLang['menu-item_ru'][inputs[j].getAttribute('key')]);
}
}
})();
anyone can correct me please?
Most likely when HTML is rendering you probably don't have change_language function, so onclick="change_language(this.id)" binds anything to onclick. Let's try to add addEventListener using javascript.
Here is a working example: https://jsfiddle.net/jugrae2z/

Return parent and his childrens from column and row

I have two functions that return column children and row children, how can I return the parents and their children’s separately, I mean each parent with his childrens.
function cols() {
var c = document.querySelectorAll('.row');
for (var i = 0; i < c.length; i++) {
for (var j = 0; j < c.length; j++) {
c[j].children[i].style.backgroundColor = "orange";
alert(c[j].children[i] / 3 );
}
}
}
cols();
function rows() {
var c = Array.prototype.slice.call(document.querySelectorAll('.row'));
for (var i = 0; i < c.length; i++) {
for (var j = 0; j < c.length; j++) {
c[i].children[j].style.borderColor = "red";
alert(c[i].children[j]);
}
}
}
rows();
fiddle:
I would do it like this:
window.onload=function(){
rows=document.getElementsByClassName("row");
rows.forEach(function(row){
colums=row.children;
colums.forEach(function(col){
alert(col,row);
});
});
}

a dynamic js table not working

this code for javascript not working.can any one help me with this.i've tried a lot but couldn't find out what's wrong here!!checked every line .i dont know if the code is wrong or there is any problem with my browser
<html>
<head>
<title>table dynamic</title>
<style>
tr{width:100%;height:100%;border:1px solid black;}
td{height:33%;width:33%;padding:10px;}
.tableShape{
width:300px;
height:300px;
font-size:30px;
text-align:centre;
color:red;
}
table{border:1px solid black;padding:10px;}
</style>
</head>
<body>
<script>
var i, j;
var arr = new Array(3);
for (i = 0; i < 3; i++) {
arr[i] = new Array(3);
}
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
arr[i][j] = 1;
}
}
function tabs() {
var k, t;
var m = document.createElement("table");
m.setAttribute('class', "tableShape");
for (k = 0; k < 3; k++) {
var p = m.insertRow(k);
for (t = 0; t < 3; t++) {
var s = p.insertCell(t);
s.innerHTML += arr[i][j];
}
}
}
window.onLoad = tabs();
</script>
</body>
</html>
You have to append your created element to the DOM:
function tabs() {
var k, t;
var m = document.createElement("table");
m.setAttribute('class', "tableShape");
for (k = 0; k < 3; k++) {
var p = m.insertRow(k);
for (t = 0; t < 3; t++) {
var s = p.insertCell(t);
s.innerHTML += arr[i][j];
}
}
document.body.appendChild(m);
}
When you create DOM elements in javascript, they are created in memory detached from DOM, to see them you have to append it to some node in DOM.
document.body.appendChild(m);
You are doing a nested operation using variables k and t so use it inside the loop
s.innerHTML+=arr[k][t];
Here is a fiddle http://jsfiddle.net/AmH22/1/

how to get the textbox value within table in alert message using javascript

This is the table created dynamically using javascript, I want to show this textbox value in alert message using GetCellValues() function.
function makeTable()
{
row=new Array();
cell=new Array();
row_num=20;
cell_num=4;
tab=document.createElement('table');
tab.setAttribute('id','newtable');
tbo=document.createElement('tbody');
tbo.setAttribute('id','tabody');
for(c = 0;c < row_num; c++)
{
row[c]=document.createElement('tr');
for(k = 0; k < cell_num; k++)
{
cell[k] = document.createElement('td');
if (k > 0)
{
cont=document.createElement("input");
cont.setAttribute('type','text');
cell[k].appendChild(cont);
row[c].appendChild(cell[k]);
}
else
{
cont=document.createTextNode("0" + (c+1));
cell[k].appendChild(cont);
row[c].appendChild(cell[k]);
}
}
tbo.appendChild(row[c]);
}
tab.appendChild(tbo);
document.getElementById('mytable').appendChild(tab);
mytable.setAttribute("align", "top-left");
}
Please check the GetCellValues() function, this function is not showing the textbox value in alert message.
function GetCellValues()
{
row=new Array();
cell=new Array();
row_num=20;
cell_num=4;
tab = document.getElementsByTagName('table');
tbo = tab.getElementsByTagName('tbody');
for(c = 0;c < row_num; c++)
{
row = tbo.getElementsByTagName('tr');
for(k = 0; k < cell_num; k++)
{
cell = row.getElementsByTagName('td');
{
cont=cell.getElementsByTagName('input');
{
alert(cont.value);
}
}
}
}
}
I think you need some modification in GetCellvalues function as tab.getElementsByTagName('tbody'); will not get elements having tag name tbody for thi you should use document.getElementsByTagName.
you can check working demo of you code here
If you are getting an alert box with [object HTMLCollection] message in it, then you need to use
alert(cont[0].value) in place of alert(cont.value) at the end of your GetCellValues function.
getElementsByTagName returns collection, you need to iterate through it or assume the first element - apply to row, cell, e.g.
var rows = tbo.getElementsByTagName('tr');
for (var c = 0; c < row_num; c++) {
row = rows[c];
var cells = row.getElementsByTagName('td');
for (var k = 0; k < cell_num; k++) {
cell = cells[k];
// and so on
}
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<table id="mytable"></table>
<input type="button" onclick="GetCellValues(20, 4);" value="click me" />
<script type="text/javascript">
function makeTable() {
row = new Array();
cell = new Array();
row_num = 20;
cell_num = 4;
tab = document.createElement('table');
tab.setAttribute('id', 'newtable');
tbo = document.createElement('tbody');
tbo.setAttribute('id', 'tabody');
for (c = 0; c < row_num; c++) {
row[c] = document.createElement('tr');
for (k = 0; k < cell_num; k++) {
cell[k] = document.createElement('td');
if (k > 0) {
cont = document.createElement("input");
cont.setAttribute('type', 'text');
cont.setAttribute('value', '');
cell[k].appendChild(cont);
row[c].appendChild(cell[k]);
}
else {
cont = document.createTextNode("0" + (c + 1));
cell[k].appendChild(cont);
row[c].appendChild(cell[k]);
}
}
tbo.appendChild(row[c]);
}
tab.appendChild(tbo);
document.getElementById('mytable').appendChild(tab);
mytable.setAttribute("align", "top-left");
}
makeTable();
function GetCellValues(row_num, cell_num) {
var arrInput = document.getElementsByTagName('input');
var index = (row_num - 1) * (cell_num - 1);
alert(arrInput[index].value);
}
</script>
</body>
</html>
A shortcut approach would be to use ID attribute of tag.
Sample TD tag with ID:
<td id="1_1">1st row 1st column</td><td id="1_2">1st row 2nd column</td>
Javascript to get TD with ID:
var row_len=1,col_len=2;
for (r = 0; r< row_len; r++) {
for (c = 0; c < coll_len; c++) {
alert(document.getElementById(r+'_'+c));
}
}

Categories

Resources