So i've been asked for creating a function that compress a string.
I tried to create a javascript function to do that. But it seems, it is not doing anything for the moment. I don't understand why, regardless of the input, my function is not doing anything.
function compression(input) {
var charsToEscape = "#/%&+,!()*':;<=>?";
var escaped = [];
for (var i = 0; i < input.length; i++) {
var testChar = input.substr(i, 1);
if (charsToEscape.indexOf(testChar) > -1) {
escaped.push("%" + testChar.charCodeAt(0).toString(16).toUpperCase());
} else {
escaped.push(testChar);
}
}
return escaped.join("");
}
<label for="input">Input: Uncompressed Link URI</label>
<input type="text" id="input" class="form-control" name="input" value="">
<button onclick="compression(input)" name="button">Compressed </button>
<br><br>
<label for="compression">Output: Compressed Link URI</label>
<input type="text" id="compression" class="form-control" name="compression" value="">
You can see above, the html function is where i put my input, and the output, and the javascript function that is supposed to do the compression.
But for the moment he is not doing anything.
Thank you all in advance for any advice you could provide
1st: You didn't use the value of the input element, but the element itself. So input hase to be replaced with input.value
2nd: You returned a value, but didn't do anything with it.. So you could create a new function that will get the value and put it in the second input
3rd: Your ids' names are too generic. I changed them to be more specific and telling names which will not interfere with other elements in the same page.
function compression(input) {
var charsToEscape = "#/%&+,!()*':;<=>?";
var escaped = [];
for (var i = 0; i < input.value.length; i++) {
var testChar = input.value.substr(i, 1);
if (charsToEscape.indexOf(testChar) > -1) {
escaped.push("%" + testChar.charCodeAt(0).toString(16).toUpperCase());
} else {
escaped.push(testChar);
}
}
return escaped.join("");
}
function insertCompressed(output, value) {
output.value = value
}
<label for="input">Input: Uncompressed Link URI</label>
<input type="text" id="compressionInput" class="form-control" name="input" value="">
<button onclick="insertCompressed(compressionOutput, compression(compressionInput))" name="button">Compressed </button>
<br><br>
<label for="compression">Output: Compressed Link URI</label>
<input type="text" id="compressionOutput" class="form-control" name="compression" value="">
I've created an onCompress function which takes html element as input. The function gets the desired input element, compression and assigns the compressed value to it.
function onCompress(input) {
document.getElementById('compression').value = compression(input.value);
}
function compression(text) {
var charsToEscape = "#/%&+,!()*':;<=>?";
var escaped = [];
for (var i = 0; i < text.length; i++) {
var testChar = text.substr(i, 1);
if (charsToEscape.indexOf(testChar) > -1) {
escaped.push("%" + testChar.charCodeAt(0).toString(16).toUpperCase());
} else {
escaped.push(testChar);
}
}
return escaped.join("");
}
<label for="input">Input: Uncompressed Link URI</label>
<input type="text" id="input" class="form-control" name="input" value="">
<button onclick="onCompress(input)" name="button">Compressed </button>
<br><br>
<label for="compression">Output: Compressed Link URI</label>
<input type="text" id="compression" class="form-control" name="compression" value="">
Related
I have number of input types and buttons....every button on click increment the value in the relevant input types. But rather than creating a separate function for every button i want to do it by loop....where loop will increase in the function name and id......
<input type="number" id="s1"> <button onclick="increment_s1();">Add</button>
<input type="number" id="s2"> <button onclick="increment_s2()">Add</button>
<input type="number" id="s3"> <button onclick="increment_s3">Add</button>
here is JavaSc code
<script>
var i = 1;
for (i = 0; i < 5; i++) {
var data = 0;
document.getElementById("s"+i).innerText = data;
function ['increment_'+i]() {
data = data + 1;
document.getElementById("s"+i).placeholder = data;
i++;
}
}
</script>
You can't program the function name. You can set up a parameter in the function to make a difference. The param would be the identifier and you can put the whole input element id there.
After that, if you want to have the id s1, s2, and so on, you should initialize the i to start from 1 to 5 instead of 0 to less than 5.
Another thing is, you need to understand the role of placeholder and value attributes in input element. The placeholder works only when the value is empty and it doesn't count as the form value.
// This is for handling onclick
function increment(id) {
var elem = document.getElementById(id);
elem.value = parseInt(elem.value) + 1;
}
// This is to initialize the 0 values
for (var i = 1; i <= 5; i++) {
var data = 0;
document.getElementById("s"+i).value = data;
}
<input type="number" id="s1"> <button onclick="increment('s1');">Add</button>
<input type="number" id="s2"> <button onclick="increment('s2')">Add</button>
<input type="number" id="s3"> <button onclick="increment('s3')">Add</button>
<input type="number" id="s4"> <button onclick="increment('s4')">Add</button>
<input type="number" id="s5"> <button onclick="increment('s5')">Add</button>
What if you would like to generate whole input and button with loops? You can get them by adding div and use the innerHTML, i.e.
// This is for handling onclick
function increment(id) {
var elem = document.getElementById(id);
elem.value = parseInt(elem.value) + 1;
}
var divElem = document.querySelector('div');
// Set up empty first
divElem.innerHTML = "";
for(var i=1; i<=5; i++) {
// Create elements here
var innerElem = `<input type="number" id="s${i}" value="0"> <button onclick="increment('s${i}')">Add</button>`;
// Push them all into innerHTML
divElem.innerHTML += innerElem;
}
<div></div>
You can try these two workarounds. Perhaps you may need to learn more about basic HTML elements and their attributes also Javascript.
I would like to know how could I create many <input type=text /> tags with a loop in JS.
I need that loop to be linked to a first input (type=number), which tell to the loops how many input text to create.
function getP () {
var nbP = Number(document.getElementById("nombreP").value);
for (var i = 0; i < nbP; i++) {
var newForm = document.createElement("input[type=text]");
newForm.id = "form"+i
document.body.appendChild(newForm);
}
}
<form method="get">
<input type="number" name="nombrePlat" id="nombreP">
<input type="submit" value="Envoyer" id="ok" onclick="getP()">
</form>
Direct answer to your question:
<script type="text/javascript">
function getP() {
var nbP = +document.getElementById("nombreP").value;
var inputContainer = document.getElementById("inutContainer");
for (var i = 0; i < nbP; i++) {
var newForm = document.createElement("input");
newForm.setAttribute("type", "text");
newForm.setAttribute("id", "form"+i);
inputContainer.appendChild(newForm);
inputContainer.appendChild(document.createElement("br"));
}
}
</script>
<form>
<input type="number" name="nombrePlat" id="nombreP">
<input type="button" value="Envoyer" id="ok" onclick="getP()">
<div id="inutContainer">
</div>
</form>
BUT: this is good question to learn about Javascript and HTML, but bad to create powerfull UI. To implement modern UI in JS/HTML i am strongly recommend to learn more abou next technologies:
https://reactjs.org/ or https://angular.io/ or https://vuejs.org/
I hope it helps:
document.querySelector('#ok').addEventListener('click', getP)
function getP(event) {
let inputsQtt = document.querySelector('input[type=number]').value
for (let i = 0; i < inputsQtt; i++) {
let input = document.createElement("input");
document.body.appendChild(input);
}
}
<form method="get">
<input type="number" name="nombrePlat" id="nombreP">
<input type="button" value="Envoyer" id="ok">
</form>
There are few problems with your code
First: syntax error, you are missing 1 curly bracket } to close function.
And second and more important as you click on button it causes to submit form and refreshes the page.To solve this you just need to change type of button from submit to button.
And also you can not use "input[type=text]" to create element.You can just create an element with following code
function getP () {
var nbP = Number(document.getElementById("nombreP").value);
for (var i = 0; i < nbP; i++) {
var newForm = document.createElement("input");
newForm.id = "form"+i;
newForm.setAttribute("type","text");
document.body.appendChild(newForm);
}
}
Here's a slightly different approach, that involves adding a wrapper container within your form.
function updateForm() {
var parent = document.getElementById('inputs'),
count = document.getElementById('inputCount').value || 0;
parent.innerHTML = '';
for (let i = 0; i < count; i++) {
parent.innerHTML += `<input placeholder="text input ${i+1}" name="form${i+1}" id="form${i+1}" /><br>`;
}
}
<form method="get" name="inputForm">
<input min="0" type="number" name="inputCount" id="inputCount">
<div id="inputs">
<!-- container for dynamic inputs -->
</div>
</form>
<!-- Notice inputs can also be associated to form with `form` attribute -->
<input form="inputForm" type="submit" value="Make" id="ok" onclick="updateForm()">
I am looking for a way to let the users copy e.g. a multi-line address paste it into a webpage where there is one input field for each address line in such a way that not only the first line is pasted, but instead the program automatically jumps to the next field and put line 2 in there and so on.
Below is the code I managed to find, But it's limited to word counts.. In the below code it's 1.. Is there any way which won't limit by word count but by line count
<input type="text" class="text-input" name="box1">
<input type="text" class="text-input" name="box2">
function handleCharacter(event) {
var $input = $(this),
index = getIndex($input),
digit = $input.val().slice(0,1),
rest = $input.val().slice(1),
$next;
if (rest.length > 0) {
$input.val(digit); // trim input value to just one character
$next = $('.text-input[name="chars['+ (index + 1) +']"]');
if ($next.length > 0) {
$next.val(rest); // push the rest of the value into the next input
$next.focus();
handleCharacter.call($next, event); // run the same code on the next input
}
}
}
function handleBackspace(event) {
var $input = $(this),
index = getIndex($input),
$prev;
// if the user pressed backspace and the input is empty
if (event.which === 8 && !$(this).val()) {
$prev = $('.def-txt-input[name="chars['+ (index - 1) +']"]');
$prev.focus();
}
}
function getIndex($input) {
return parseInt($input.attr('name').split(/[\[\]]/)[1], 10);
}
$('.def-txt-input')
.on('keyup', handleCharacter)
.on('keydown', handleBackspace);
Thanks in advance for your help!!!!
I provided a textarea to paste stuff and then split the lines and pasted in other boxes.
<textarea class="def-txt-input" id="mainbox">
</textarea>
<br/>
<input type="text" class="text-input" name="box1">
<input type="text" class="text-input" name="box2">
<input type="text" class="text-input" name="box3">
<input type="text" class="text-input" name="box4">
<input type="text" class="text-input" name="box5">
<input type="text" class="text-input" name="box6">
<script>
function handleCharacter(event) {
var longString = $("#mainbox").val();
var ks = $('#mainbox').val().split("\n");
//e.preventDefault();
var inputs = $(".text-input");
$.each(ks, function(k){
//alert(ks[k]);
//alert(inputs[k].name);
var thisName = inputs[k].name;
//$("[name='box1']").val('hi');
$('[name="' + thisName + '"]').val(ks[k]);
});
console.log(longString);
}
$('.def-txt-input')
.on('keyup', handleCharacter);
// .on('keydown', handleBackspace);
</script>
Obviously, a beginner's question:
How do I get array data to display in an html element using html and javascript?
I'd like to display the user saved array data in a paragraph tag, list tag, or table tag, etc.
[http://www.mysamplecode.com/2012/04/html5-local-storage-session-tutorial.html]
Above is a link to the kindly provided example of localStorage except how to display the array on the html page rather than in the console.log.
Below is the code snip that demonstrates what I'm trying to do.
function saveArrayData() {
console.log("Saving array data to local storage.");
var myArrayObject = [];
var personObject1 = new Object();
personObject1.name = "Array1";
personObject1.age = 23;
myArrayObject.push(personObject1);
var personObject2 = new Object();
personObject2.name = "Array2";
personObject2.age = 24;
myArrayObject.push(personObject2);
var personObject3 = new Object();
personObject3.name = "Array3";
personObject3.age = 25;
myArrayObject.push(personObject3);
localStorage.setItem("persons", JSON.stringify(myArrayObject));
}
function restoreArrayData() {
console.log("Restoring array data from local storage.");
var myArrayObject = JSON.parse(localStorage.getItem("persons"));
for (var i = 0; i < myArrayObject.length; i++) {
var personObject = myArrayObject[i];
console.log("Name: " + personObject.name, "Age: " + personObject.age);
}
}
<label for="name">Name:</label>
<input type="text" data-clear-btn="true" name="name" id="name" value="">
<label for="age">Age:</label>
<input type="text" data-clear-btn="true" name="age" id="age" value="">
<br>
<br>
<input type="button" id="sArray" value="Save Array data" onclick="Javascript:saveArrayData()">
<input type="button" id="rArray" value="Restore Array data" onclick="Javascript:restoreArrayData()">
<p id="displayArrayDataHere"></p>
You should update your code like below:
function restoreArrayData() {
var myArrayObject = JSON.parse(localStorage.getItem("persons"));
$("#displayArrayDataHere").append("<table>");
myArrayObject.forEach(function(personObject) {
$("#displayArrayDataHere").append("<tr><td>"+personObject.name+"</td><td>"+personObject.age+"</td></tr>")
})
$("#displayArrayDataHere").append("</table>");
}
The form code:
<td><form action="cart.php" method="get">
<input type="button" onclick="buttonSubtract1()" name="subtract1" value="-
"/>
<input type="text" size="4" id="qty1" name="quantity1" value="0"/>
<input type="button" onclick="buttonAdd1()" name="add1" value="+"/>
<input type="submit" name="product1" value="Add"/>
The javascript:
var i = 0;
var qty1 = document.getElementById('qty1').value;
function buttonAdd1() {
document.getElementById('qty1').value = ++i;
}
function buttonSubtract1() {
if (qty1 > 0) {
document.getElementById('qty1').value = --i;}
}
I changed the code to increment and de-increment using javascript which worked fine so I tried to make it so that de-incrementation only works if the number is positive but now incrementing is working fine but it is not allowing de-incrementation of any number. Why is this?
You just have to put the var qty1 = document.getElementById('qty1').value; into the subtract function like this:
var i = 0;
function buttonAdd1() {
document.getElementById('qty1').value = ++i;
}
function buttonSubtract1() {
var qty1 = document.getElementById('qty1').value;
if (qty1 > 0) {
document.getElementById('qty1').value = --i;}
}
}
In your Example, you just write the First Value (0) into the Window objekt.
It stays zero until you change it in the window object again.
But if you ask the Value everytime the function is called, you get always the newest number.
Fiddle:
http://jsfiddle.net/9wHU9/