I have been looking for a way to dynamically change the length of the input field in a HTML form.
I have come across the following:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Example</title>
<script type="text/javascript">
window.onload = function() {
thelink = document.getElementById('MyLink');
linksize = thelink.value.length;
if (linksize < 10) thelink.size = 10;
if (linksize > 50) thelink.size = 50;
}
</script>
</head>
<body>
<input id="MyLink" type="text" value="http://www.domain.com/this/is/a/very/long/link/example" />
</body>
</html>
How would i adapt this to work for every input field on my very large form?
Thanks
For your case, I would give the required minimum and maximum as data-*= attributes,
For example:
<input id="MyLink" data-min="10" data-max="50" type="text" value="http://www.domain.com/this/is/a/very/long/link/example" />
Then iterate through the inputs in your form, drawing from the data attributes, and checking for the required length.
You can collect elements in a collection, either take them from the whole document or some its containing element. You can use e.g. getElementsByTagName('input');, getElementsByName('myInput'); or getElementsByClassName('shapable_input'); methods, if tags have set the corresponding attribute:
<input name="myInput" class="shapable_input" value="...." />
and then all collected tags can be tested in the loop:
window.onload = function() {
var links = document.getElementsByTagName('input');
//var linksc = links.getElementsByClassName('link');
var i, thelink, linksize;
for (i = 0; i < links.length; i++) {
thelink = links[i];
linksize = thelink.value.length;
if (linksize <= 10) {
thelink.size = 10;
}
if (linksize > 10) {
thelink.size = 50;
}
}
};
example
Related
I have a table generated from a textarea filled by users, but some of the time, a cell stays empty (and that's all right).
The thing is that the .innerHTML of that cell is also my var y in a script and when that cell is empty (therefore, undefined), my var y becomes UNDEFINED too (the value, not a string), which makes my whole script fail.
Here's a snippet to show the problem:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body><center>
</center></body>
<!--------- script that generates my table from text areas -->
<script>
function generateTable() {
$('#excel_table1').html("");
var n=1;
var rows=[];
var lng=0;
var maxligne=0;
$('textarea').each(function(){
var data = $(this).val();
if (data !=''){
var rowData = data.split("\n");
rows[n] = rowData;
lng = rowData.length;
if(lng > maxligne)
{
maxligne=lng
}
n++;
}
}
)
var table = $('<table />');
k=0;
while (k < maxligne) {
var row = $('<tr />');
for(var i = 1; i < rows.length; i++)
{
var singleRow = rows[i];
if(singleRow[k]!= undefined){
row.append('<td>'+singleRow[k]+'</td>')
} else {
row.append('<td></td>')
}
}
table.append(row);
k++;
}
$('#excel_table1').append(table);
}
</script>
<textarea placeholder="data 2 Here" name="data1" style="width:100px;height:40px;"></textarea>
<textarea placeholder="data 2 Here" name="data2" style="width:200px;height:40px;"></textarea>
<textarea placeholder="fild not required" name="data3" style="width:200px;height:40px;"></textarea>
<br>
<input id=bouton1 type="button" onclick="javascript:generateTable()" value="GenerateTable"/>
<div id="excel_table1"></div>
<!--------- script that get the data from cells to show it in <H2> -->
<script type="text/javascript">
function buttonTEST()
{
$('#displayCell').html("");
var x = document.getElementById('excel_table1').getElementsByTagName('tr')[0].cells[1].innerHTML;
var y = document.getElementById('excel_table1').getElementsByTagName('tr')[0].cells[2].innerHTML;
if (y === undefined) {
y = " ";
}
document.getElementById('displayCell').innerHTML = x +" "+ y;
}
</script>
<br/><br/>
<h2 id="displayCell"></h2>
<br/><br/>
<input id="Button2" type="button" onclick="buttonTEST()" value="TEST ME"/>
As you can see, if you generate a table with only to columns (which is supposed/needs to happen sometimes), we get this error from the console because we're trying to get "innerHTML" from a undefined:
index.html:120 Uncaught TypeError: Cannot read property 'innerHTML' of undefined
A little specification: When that cell is=undefined , I need it to stay undefined, I only want to change the fact that my var y also becomes undefined.
So I thought that changing the value of var y (and not the value of that cell, otherwise, the 3rd column, supposed to be empty, would be created just because of an blank space) to a blank space would resolve the problem, but I don't seem to get it right (write it in a correct manner).
Any ideas?
Try
var x = document.getElementById('excel_table1').rows[0].cells[0].innerHTML;
var y = document.getElementById('excel_table1').rows[0].cells[1].innerHTML;
using rows instead of getElementsByTagName is cleaner.
Also note that the indexes for cells start from zero not 1, you probably only have 2 cells in your first row, but .cells[2].innerHTML tries to get the innerHTML of the 3rd cell which does not exist.
As others have pointed out, you're already using jQuery, so the easiest way to get the cell contents is to use a css selector to find the cells using the $ function, then call .html() to get the contents. A direct conversion of your current code to this approach could be:
var x = $('#excel_table1 tr:nth-child(1) td:nth-child(2)').html();
var y = $('#excel_table1 tr:nth-child(1) td:nth-child(3)').html();
This works in a way so that the $ function returns a jQuery object, which is essentially a set of elements, which can potentially be empty. Most jQuery functions are then designed to fail gracefully when called on an empty set. For instance, html will return undefined when invoked on an empty set, but it will not fail.
Note that it is not very robust to use the selector above, as it is obviously sensitive to the placement of the cells. It would be more maintainable to assign a class attribute to the cells that describes their content, and then select on that, e.g. something like
var name = $("#excel_table1 tr:nth-child(1) td.name").html()
So here's the answer that worked for me:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body><center>
</center></body>
<!--------- script that generates my table from text areas -->
<script>
function generateTable() {
$('#excel_table1').html("");
var n=1;
var rows=[];
var lng=0;
var maxligne=0;
$('textarea').each(function(){
var data = $(this).val();
if (data !=''){
var rowData = data.split("\n");
rows[n] = rowData;
lng = rowData.length;
if(lng > maxligne)
{
maxligne=lng
}
n++;
}
}
)
var table = $('<table />');
k=0;
while (k < maxligne) {
var row = $('<tr />');
for(var i = 1; i < rows.length; i++)
{
var singleRow = rows[i];
if(singleRow[k]!= undefined){
row.append('<td>'+singleRow[k]+'</td>')
} else {
row.append('<td></td>')
}
}
table.append(row);
k++;
}
$('#excel_table1').append(table);
}
</script>
<textarea placeholder="data 2 Here" name="data1" style="width:100px;height:40px;"></textarea>
<textarea placeholder="data 2 Here" name="data2" style="width:200px;height:40px;"></textarea>
<textarea placeholder="fild not required" name="data3" style="width:200px;height:40px;"></textarea>
<br>
<input id=bouton1 type="button" onclick="javascript:generateTable()" value="GenerateTable"/>
<div id="excel_table1"></div>
<!--------- script that get the data from cells to show it in <H2> -->
<script type="text/javascript">
function buttonTEST()
{
$('#displayCell').html("");
var x = $('#excel_table1 tr:nth-child(1) td:nth-child(2)').html();
var y = $('#excel_table1 tr:nth-child(1) td:nth-child(3)').html();
if (y ===undefined)
{document.getElementById('displayCell').innerHTML = x ;}
else
{document.getElementById('displayCell').innerHTML = x +" "+ y;}
}
</script>
<br/><br/>
<h2 id="displayCell"></h2>
<br/><br/>
<input id="Button2" type="button" onclick="buttonTEST()" value="TEST ME"/>
I am trying to figure out a way to count words that are placed in multiple paragraph blocks in javascript. Right now I have a button that is connected to a function and that function is linked to an ID in the paragraph. Here is my code
function processText(elements) {
var count = 0;
for (var i = 0; i < elements.length; i++) {
count += elements[i].textContent.split(/\s/).length;
}
return count;
}
var wordsInParagraphs = processText(document.getElementsByTagName("data"));
<!DOCTYPE html>
<html>
<head>
<meta name="title" content="The Cask of Amontillado--Edgar Allan Poe (1809-1849)">
</head>
<body>
<p><button 1="processText(elements);">Process</button></p>
<p id="data"></p>
</body>
Is this what you're looking for? You just need to call the function on click and grab all the elements you want to count, you have the rest there (I'm using split instead of regex).
function processText() {
var elements = document.querySelectorAll(".data");
var count = 0;
for (var i = 0; i < elements.length; i++) {
count += elements[i].textContent.split(" ").length;
}
console.log(count)
}
<!DOCTYPE html>
<html>
<head>
<meta name="title" content="The Cask of Amontillado--Edgar Allan Poe (1809-1849)">
</head>
<body>
<p><button onclick="processText();">Process</button></p>
<p class="data">text in paragraph one</p>
<p class="data">text in paragraph two</p>
</body>
The markup has some problems, for example, 1="processText(elements);" probably you meant onClick="processText(elements);", however, you're passing a param called elements. Further, you have a tag with id="data" and you're trying to look for tag name those elements.
A better approach is using the function addEventListener for a better logic and you should mark those paragraphs using a class name class="data". Finally, for splitting by spaces use this regex /\s+/
function processText(elements) {
var count = 0;
for (var i = 0; i < elements.length; i++) {
count += elements[i].textContent.split(/\s+/).length;
}
return count;
}
document.getElementById('myButton').addEventListener('click', function() {
var wordsInParagraphs = processText(document.getElementsByClassName("data"));
document.getElementById('total').textContent = wordsInParagraphs;
});
<p><button id='myButton'>Process</button></p>
<p class="data">Ele from Stack</p>
<p class="data">Ele from Venezuela</p>
<p id='total'></p>
The html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="scripts.js"></script>
</head>
<body>
<button id = "button1" type="button" onclick="filterValues();">Submit</button>
</body>
</html>
My javascript:
var checkingValues = ["Cat", "Dog", "Horse", "Tree"];
var createCheckboxes;
var saveValues;
document.write("Choose from the options below: </br> </br>");
for (var i = 0; i < checkingValues.length; i++) {
createCheckboxes = document.createElement("INPUT");
var checkbox = createCheckboxes.setAttribute("type", "checkbox");
createCheckboxes.setAttribute("value", checkingValues[i]);
var checkBoxText = document.body.appendChild(createCheckboxes) + document.write(createCheckboxes.value +"</br>");
}
//try to save checked values
if(createCheckboxes.checked){
saveValues = checkbox;
}
function filterValues() {
document.write(saveValues);
}
My idea is to generate a checkbox and print(filter) the selected items from the checkbox by saving the selected items in to a new array and just print them on a cick. I feel i need to make a simple if statement for that but i cant seem to write the values in the global saveValues variable. I know that is not the smartest way to do it but i want to know how to do it. I want to use pure JS.
Thanks.
If you're restricted to pure Javascript, you could always do the following:
var inputs = document.getElementsByTagName('input');
for(var i=0; i < inputs.length; i++){
if(inputs[i].type == 'checkbox' && inputs[i].checked) {
//print
console.log(inputs[i].value);
}
}
That will get all checked checkboxes on the page and print their values. Instead of printing to the console you could do some other logic, or add the checkbox to a second array for later use.
Try this,
function filterValues() {
for (var i = 0; i < checkingValues.length; i++) {
if(createCheckboxes.checked){
saveValues = checkbox;
}
}
document.write(saveValues);
}
Hi guys i'm kinda new to javascript and for a while now, i've been struggeling with something that shouldnt be that hard. The thing that i'm trying to execute is to get user input stored in an array, and then get it to print the collected info into a specific div (later on i'm gonna try to create a table using the DOM and store the input there). But i cant get it to work, below is my code :) any suggestions?
JavaScript
function submitInfo(){
var nameInput = document.getElementById("name").value;
var ageInput = document.getElementById("age").value;
var fsInput = document.getElementById("fightingStyle").value;
var weightInput = document.getElementById("weight").value;
myArray[0]=nameInput;
myArray[1]=ageInput;
myArray[2]=fsInput;
myArray[3]=weightInput;
for(var i = 0; i<myArray.lenght; i++){
document.getElementById("theResult").innerHTML=myArray[i];
}
}
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="inl2a.css" />
<script type="text/javascript" src="inl2a.js"></script>
<title>Inlämning 2a</title>
</head>
<body>
<div id="inputFields">
<h3>Submit your fighters information:</h3>
Name:<br><br>
<input id="name" type="text" /><br><br>
Age:<br><br>
<input id="age" type="text" /><br><br>
Fighting style:<br><br>
<input id="fightingStyle" type="text" /><br><br>
Weight:<br><br>
<input id="weight" type="text" /><br><br>
<input id="button" value="Submit" type="button" onclick="submitInfo();" /><br><br>
</div>
<div id="theResult">
</div>
</body>
</html>
function submitInfo(){
var myArray = []; // problem 1
var nameInput = document.getElementById("name").value;
var ageInput = document.getElementById("age").value;
var fsInput = document.getElementById("fightingStyle").value;
var weightInput = document.getElementById("weight").value;
myArray[0]=nameInput;
myArray[1]=ageInput;
myArray[2]=fsInput;
myArray[3]=weightInput;
for(var i = 0; i<myArray.length; i++){ // problem 3
document.getElementById("theResult").innerHTML+=myArray[i]; // problem 2
}
}
you haven't initialized the array anywhere
you overwrite the innerHTML property so only the last value remains
you have a typo: lenght instead of length
You can also set the values directly in the array and no longer use the intermediary variables. Also, you can get theResult element once, outside of the loop:
function submitInfo(){
var myArray = []; // problem 1
myArray.push(document.getElementById("name").value);
myArray.push(document.getElementById("age").value);
myArray.push(document.getElementById("fightingStyle").value);
myArray.push(document.getElementById("weight").value);
var element = document.getElementById("theResult");
for(var i = 0; i<myArray.length; i++){
element.innerHTML += myArray[i]; // problem 2
}
}
suppose user inputs are title and name, then
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
You could put all of these in one array:
var m = [ title, name ];
then for title use,
document.getElementById(your_divID).innerText=m[0];
you can use textContent instead of innerText for mozilla support.
I'm really newbie at Web Development and I'm trying to change the text of some inputs, with Javascript. Here is a example of what my code have to do
<!DOCTYPE html>
<html>
<body>
<p>Click the button to replace "R$" with "" in the field below:</p>
<input id="demo" value="R$ 1223,43"></input>
<input id="demo1" value="R$ 134523,67"></input>
<input id="demo2" value="R$ 12453,41"></input>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var x=document.getElementByTagName("input")
for(var i = 0; i < x.length; i++) {
var str=x[i].innerHTML;
var n=str.replace(",",".");
var n1 = n.replace("R$ ","");
document.getElementById("demo").innerHTML=n1;
}
}
</script>
</body>
</html>
So, I want to withdraw the "R$" and replace "," to "." for some math operations. And I have to do this with all inputs in my code.
You were nearly there, replacing a few things to make it look similar to this:
function myFunction() {
var x = document.getElementsByTagName("input"); // ; was missing and you used getElementByTagName instead of getElementsByTagName
for (var i = 0; i < x.length; i++) {
var str = x[i].value; // use .value
var n = str.replace(",", ".");
var n1 = n.replace("R$ ", "");
//document.getElementById("demo").innerHTML=n1; // use x[i] again instead
x[i].value = n1; // and again use .value
}
}
DEMO - Running updated code
These are the needed steps - at least step 1 through 3
moved the script to the head where it belongs
changed getElementByTagName to getElementsByTagName, plural
get and change x[i].value
chained the replace
DEMO
<!DOCTYPE html>
<html>
<head>
<title>Replace example</title>
<script>
function myFunction() {
var x=document.getElementsByTagName("input"); // plural
for(var i = 0; i < x.length; i++) {
var str=x[i].value;
x[i].value=str.replace(",",".").replace("R$ ","");
}
}
</script>
</head>
<body>
<p>Click the button to replace "R$" with "" in the field below:</p>
<input id="demo" value="R$ 1223,43"></input>
<input id="demo1" value="R$ 134523,67"></input>
<input id="demo2" value="R$ 12453,41"></input>
<button onclick="myFunction()">Try it</button>
</body>
</html>
First of all, use .value instead of .innerHTML. .innerHTML referes to text within the opening and closing of the tag.
Secondly, correct the spellings at var x=document.getElementByTagName("input")
it should be getElementsByTagName
this function should do what you want:
function myFunction()
{
var eles=document.getElementsByTagName("input");
for(var i = 0; i < eles.length; i++)
{
if(eles[i].type != 'text') continue; // inputs that aren't of type text dont make sense here
var str = eles[i].value;
str=str.replace(",",".");
str=str.replace("R$ ","");
eles[i].value=str;
}
}