I am trying to get the text in a multiple text box as the user types in it (jsfiddle playground):
function Input1(a) {
document.getElementById("Input11").innerHTML = a.value;
document.getElementById("Input12").innerHTML = a.value;
document.getElementById("Input13").innerHTML = a.value;
}
function Input2(b) {
document.getElementById("Input21").innerHTML = b.value;
document.getElementById("Input22").innerHTML = b.value;
document.getElementById("Input23").innerHTML = b.value;
}
And Result as
<span id="text-box">
<input class="textbox-value" type="text" name="Jname" placeholder="Input1" onkeyup="Input1(this);">
</span><br><br>
<span id="Input11">Input11</span><br>
<span id="Input12">Input12</span><br>
<span id="Input13">Input13</span><br><br>
<span id="text-box">
<input class="textbox-value" type="text" name="Jbname" placeholder="Input2" onkeyup="Input2(this);">
</span><br><br>
<span id="Input21">Input21</span><br>
<span id="Input22">Input22</span><br>
<span id="Input23">Input23</span><br><br>
The above code is working fine.
But I want to Display each "onkeyup" input multiple times on-page. So here I need to update the function and span id (As if I use the same id then it will not display anything after 2nd call)
Please help me to reformat the above JavaScript and HTML so Just Define function for input and display it on all HTML span id without changing span id each time...
you can use class instead of id and use querySelectorAll to select all elements here is sample code
function Input1(a) {
const elements = document.querySelectorAll(".Input1");
elements.forEach((e)=>{
e.innerHTML = a.value;
})
}
function Input2(b) {
const elements = document.querySelectorAll(".Input2");
elements.forEach((e)=>{
e.innerHTML = b.value;
})
}
<html>
<body><span id="text-box">
<input class="textbox-value" type="text" name="Jname" placeholder="Input1" onkeyup="Input1(this);">
</span><br><br>
<span class="Input1">Input11</span><br>
<span class="Input1">Input12</span><br>
<span class="Input1">Input13</span><br><br>
<span id="text-box">
<input class="textbox-value" type="text" name="Jbname" placeholder="Input2" onkeyup="Input2(this);">
</span><br><br>
<span class="Input2">Input21</span><br>
<span class="Input2">Input22</span><br>
<span class="Input2">Input23</span><br><br>
</body>
</html>
you can do somthing like that:
document.querySelectorAll('div.text-box').forEach( (box,i) =>
{
let
intxt = box.querySelector('input')
, spTxts = box.querySelectorAll('span')
;
intxt.mane = `Jname${++i}`
intxt.placeholder = `Input${i}`
intxt.onkeyup = () => spTxts.forEach(sp=>sp.textContent = intxt.value)
})
.text-box {
margin : 20px 0 15px 0;
}
.text-box input {
width : 100%;
font-size : 13px;
padding : 5px;
margin-top : -5px;
margin-bottom : 1em;
box-shadow : 1px 5px 7px #75757578;
}
.text-box span {
display : block;
}
<div class="text-box">
<input type="text">
<span>...</span>
<span>...</span>
<span>...</span>
</div>
<div class="text-box">
<input type="text">
<span>...</span>
<span>...</span>
<span>...</span>
</div>
<div class="text-box">
<input type="text">
<span>...</span>
<span>...</span>
<span>...</span>
</div>
<div class="text-box">
<input type="text">
<span>...</span>
<span>...</span>
<span>...</span>
</div>
this is the best for you!
function Input(a, n) {
var spans = document.querySelectorAll('#tb' + n + ' span')
spans.forEach(function(span){
span.innerHTML = a.value;
})
}
.textbox-value {
width: 100%;
font-size: 13px;
padding: 5px;
margin-top: -5px;
box-shadow: 1px 5px 7px #75757578;
}
<html>
<body>
<div id="tb1" class="text-box">
<input class="textbox-value" type="text" name="Jname" placeholder="Input1" onkeyup="Input(this, '1');" />
<br><br>
<span>Input11</span><br>
<span>Input12</span><br>
<span>Input13</span><br>
</div>
<br>
<div id="tb2" class="text-box">
<input class="textbox-value" type="text" name="Jbname" placeholder="Input2" onkeyup="Input(this, '2');">
<br><br>
<span>Input21</span><br>
<span>Input22</span><br>
<span>Input23</span><br>
</div>
<br>
</body>
</html>
Related
I have a HTML form with several textareas.
I need to limit the number of characters for each area.
I want to shouw a counter.
I found this on the web:
$('textarea').keyup(function() {
var characterCount = $(this).val().length,
current = $('#current'),
maximum = $('#maximum'),
theCount = $('#the-count');
current.text(characterCount);
});
#the-count {
float: right;
padding: 0.1rem 0 0 0;
font-size: 0.875rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<h1>Displaying The Character Count of a Textarea</h1>
<textarea name="the-textarea" id="the-textarea" maxlength="300" placeholder="Start Typin..."autofocus></textarea>
<div id="the-count">
<span id="current">0</span>
<span id="maximum">/ 300</span>
</div>
</div>
MY PROBLEM:
It works for 1 textarea but then stop to work when having several text areas. How to transform the javascript function in order to make it work for any text area and counters in the page?
You need to do querySelectorAll on all the inputs and then attach a oninput event listener, like this:
var textareas = document.querySelectorAll('textarea');
textareas.forEach(textarea => {
textarea.addEventListener('input', function() {
var charCount = textarea.value.length;
var count = textarea.nextElementSibling;
count.innerHTML = charCount + ' /300';
})
})
#count {
float: right;
padding: 0.1rem 0 0 0;
font-size: 0.875rem;
}
<div class="wrapper">
<h1>Displaying The Character Count of a Textarea</h1>
<div>
<textarea name="textarea" maxlength="300" placeholder="Start Typin..." autofocus></textarea>
<div id="count">0 / 300</div>
</div>
<div>
<textarea name="textarea" maxlength="300" placeholder="Start Typin..." autofocus></textarea>
<div id="count">0 / 300</div>
</div>
<div>
<textarea name="textarea" maxlength="300" placeholder="Start Typin..." autofocus></textarea>
<div id="count">0 / 300</div>
</div>
</div>
In pure Javascript.
ID's should be unique. Give different id's. It will work.
CSS:
#textCount, #textCount1 {
padding: 0.1rem 0 0 0;
font-size: 0.875rem;
}
HTML:
<div class="wrapper">
<h1>Displaying The Character Count of a Textarea</h1>
<textarea id="textarea1" maxlength="300" placeholder="Start Typin..."></textarea>
<div id="textCount1">
<span id="current1">0</span>
<span id="maximum1">/ 300</span>
</div>
<textarea id="textarea2" maxlength="300" placeholder="Start Typin..."></textarea>
<div id="textCount2">
<span id="current2">0</span>
<span id="maximum2">/ 300</span>
</div>
</div>
javascript:
$('#textarea1').keyup(function() {
var characterCount = $(this).val().length,
current = $('#current1'),
maximum = $('#maximum1'),
theCount = $('#textCount1');
current.text(characterCount);
});
$('#textarea2').keyup(function() {
var characterCount = $(this).val().length,
current = $('#current2'),
maximum = $('#maximum2'),
theCount = $('#textCount2');
current.text(characterCount);
});
Multiple Textareas with different maxLength value.
id issue also resolved by making it class
Make modification from other answer.
JSFiddle
Code
HTML
<div class="wrapper">
<h1>Displaying The Character Count of a Textarea</h1>
<div>
<textarea name="textarea" maxlength="450" placeholder="Start Typin..." autofocus> </textarea>
<div class="count">0 / 450</div>
</div>
<div>
<textarea name="textarea" maxlength="400" placeholder="Start Typin..." autofocus></textarea>
<div class="count">0 / 400</div>
</div>
<div>
<textarea name="textarea" maxlength="500" placeholder="Start Typin..." autofocus></textarea>
<div class="count">0 / 500</div>
</div>
</div>
Javascript
let textareas = document.querySelectorAll('textarea');
textareas.forEach(textarea => {
textarea.addEventListener('input', function() {
let charCount = textarea.value.length;
let count = textarea.nextElementSibling;
let maxLength = textarea.maxLength;
count.innerHTML = charCount + ' / ' + maxLength;
})
})
I have a form that calculates price per square meters of ceiling.
And ion range slider as input, then it calculates price and outputs data to inputs. But I need to change inputs with span or div. Any suggestions?
Here is the html:
<form id="calc">
<div id="1">
<p>
<input id="rel" oninput="
var v = this.value;
this.form.new.value = isNaN(v) ? '' : (v * 450).toFixed (0);
var v = this.value; this.form.new2.value = isNaN(v) ? '' : (v * 650).toFixed (0)"
style="display: none;">
</p>
<p><p>
<span class="small">from </span>
<span class="new"></span>
<input type="text" disabled="disabled" name="new" size="2" maxlength="4" value="0" >
<span class="small">to </span><input type="text" disabled="disabled" name="new2" size="2" maxlength="4" value="0">
<div class="result" id="result">
</div>
</p>
</div>
</form>
and here you can find how it works http://jsfiddle.net/khvoroffski/50apyyr5/
Please make a good look at this example , I made you func you make design (css) .
/*Chrome*/
#media screen and (-webkit-min-device-pixel-ratio:0) {
input[type='range'] {
overflow: hidden;
width: 10px;
-webkit-appearance: none;
background-color: #9a905d;
}
input[type='range']::-webkit-slider-runnable-track {
height: 10px;
-webkit-appearance: none;
color: #13bba4;
margin-top: -1px;
}
input[type='range']::-webkit-slider-thumb {
width: 10px;
-webkit-appearance: none;
height: 10px;
cursor: ew-resize;
background: #434343;
box-shadow: -10px 0 0 0px #43e5f7;
}
}
/** FF*/
input[type="range"]::-moz-range-progress {
background-color: #43e5f7;
}
input[type="range"]::-moz-range-track {
background-color: #9a905d;
}
/* IE*/
input[type="range"]::-ms-fill-lower {
background-color: #43e5f7;
}
input[type="range"]::-ms-fill-upper {
background-color: #9a905d;
}
<script>
function E (ele) {return document.getElementById(ele)}
function CALC ( value_ ) {
var SPAN = E("SliderValue")
var FROM = E("FROM")
var TO = E("TO")
var currentValue = E("SliderValue")
var WIDTH_OF_SLIDER = E("rel")
var positionInfo = WIDTH_OF_SLIDER.getBoundingClientRect();
var width_IN_PIX = positionInfo.width;
FROM.value = isNaN(value_) ? '' : (value_ * 450).toFixed (0);
TO.value = isNaN(value_) ? '' : (value_ * 650).toFixed (0);
currentValue.innerHTML = value_ + ""
var COEFICIJENT = width_IN_PIX / 100
currentValue.style.left = ( value_ * COEFICIJENT ) + "px"
}
</script>
<form id="calc"
>
<div id="1">
<p>
<input id="rel"
oninput="CALC(this.value)"
type="range"
maxValue="50"
minValue="5"
value="0"
step="1"
style="width:100%;background-color:red;" >
</p>
<span class="small" >from </span>
<span id="SliderValue" style="position:absolute;left:0;" > </span>
<input type="text" id="FROM" value="0" />
<span class="small">to </span>
<input type="text" id="TO" value="0" />
<div class="result" id="result" > </div>
</div>
</form>
Creating Dynamic new fields seems to clear the already existing fields
Also not trying to have multiple elements with the same id hence why i don't believe appendChild will work. Perhaps you can find a way to do that while creating different IDs?
Any help welcomed =)
var template;
var a = 1;
window.onload = function() {
template = document.querySelector("#wrapper").innerHTML;
document.querySelector("#more_fields").addEventListener("click", function(e) {
e.preventDefault(); // tell the browser to not send the form
document.getElementById('wrapper').innerHTML += template; // add next segment
document.querySelector("#wrapper > label:last-of-type").innerHTML = "Segment " + (++a) + ":";
});
}
.form-group {
display: inline
}
#wrapper > label {
margin: 0 0 10px 210px;
}
.segment {
display: inline-block;
margin: 0 0 1em
}
.form-group > label {
margin: 0 0 10px 20px;
}
.form-group > input {
width: 15%
}
<div class="container">
<h2>Form</h2>
<form>
<div id="room_fields">
<div class="content" id="wrapper">
<label style:>Segment 1:</label>
<div class="segment">
<div class="form-group">
<label>IN:</label>
<input name="seg-in[]" type="text">
</div>
<div class="form-group">
<label>OUT:</label>
<input name="seg-out[]" type="text">
</div>
<div class="form-group">
<label>Duration:</label>
<input name="seg-dur[]" type="text">
</div>
</div>
</div>
</div>
<br><br>
<div style="text-align: right;">
<button id="more_fields">+</button>
</div>
<br>
<br>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
innerHTML will not include the current value entered IIRC but it's still strange that doing += operation will remove the existing value.
However, insertAdjacentHTML() should work as expected.
var template;
var a = 1;
window.onload = function() {
template = document.querySelector("#wrapper").innerHTML;
document.querySelector("#more_fields").addEventListener("click", function(e) {
e.preventDefault(); // tell the browser to not send the form
document.getElementById('wrapper').insertAdjacentHTML('beforeend', template); // add next segment
document.querySelector("#wrapper > label:last-of-type").innerHTML = "Segment " + (++a) + ":";
});
}
.form-group {
display: inline
}
#wrapper > label {
margin: 0 0 10px 210px;
}
.segment {
display: inline-block;
margin: 0 0 1em
}
.form-group > label {
margin: 0 0 10px 20px;
}
.form-group > input {
width: 15%
}
<div class="container">
<h2>Form</h2>
<form>
<div id="room_fields">
<div class="content" id="wrapper">
<label style:>Segment 1:</label>
<div class="segment">
<div class="form-group">
<label>IN:</label>
<input name="seg-in[]" type="text">
</div>
<div class="form-group">
<label>OUT:</label>
<input name="seg-out[]" type="text">
</div>
<div class="form-group">
<label>Duration:</label>
<input name="seg-dur[]" type="text">
</div>
</div>
</div>
</div>
<br><br>
<div style="text-align: right;">
<button id="more_fields">+</button>
</div>
<br>
<br>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
Basically, my below code is not 100% correct, you should alter it by yourself following mine.
In the HTML, you can define a hidden div which is your wrapper. In its and nested element ids, you can set a pattern like '$$$'.
<div class="content" id="wrapper$$$" sytle="visibility: hidden;">
<label style:>Segment 1:</label>
<div class="segment">
<div class="form-group">
<label>IN:</label>
<input name="seg-in[]" type="text">
</div>
<div class="form-group">
<label>OUT:</label>
<input name="seg-out[]" type="text">
</div>
<div class="form-group">
<label>Duration:</label>
<input name="seg-dur[]" type="text">
</div>
</div>
</div>
In your javascript, declare a global variable named index and replace index value with '$$$'. It will be increased 1 when you add your template dynamically.
template = document.querySelector("#wrapper").innerHTML;
template = template.replace('$$$', index);
index ++;
...
Problem:
The problem here is with using innerHTML, because innerHTML will always override the HTML of your elements so previously typed values will be cleared, that's why you should use .appendChild().
And your logic for dynamic is correct, you just need to chnage the way you add new fields.
Solution:
I tried to rewrite your code so it uses appendChild() in a smart way using the #wrapper innerHTML as template and updating the id dynamically in the new appended fields.
var template = document.querySelector("#wrapper").innerHTML;
function addFields() {
var wrapper = document.createElement("div");
wrapper.innerHTML = template;
wrapper.querySelector("label:last-of-type").innerHTML = "Segment " + (++a) + ":";
document.getElementById('wrapper').appendChild(wrapper);
}
This code will create a new div everytime, wher we put the template HTML inside it, update the label dynamically referring the label inside our current wrapper div using wrapper.querySelector("label:last-of-type"), then finally append this new div to our element.
Demo:
Here's a working Demo snippet:
var template = document.querySelector("#wrapper").innerHTML;
var a = 1;
function addFields() {
var wrapper = document.createElement("div");
wrapper.innerHTML = template;
wrapper.querySelector("label:last-of-type").innerHTML = "Segment " + (++a) + ":";
document.getElementById('wrapper').appendChild(wrapper);
}
window.onload = function() {
document.querySelector("#more_fields").addEventListener("click", function(e) {
e.preventDefault();
addFields();
});
}
<div class="container">
<h2>Form</h2>
<form>
<div id="room_fields">
<div class="content" id="wrapper">
<label style:>Segment 1:</label>
<div class="segment">
<div class="form-group">
<label>IN:</label>
<input name="seg-in[]" type="text">
</div>
<div class="form-group">
<label>OUT:</label>
<input name="seg-out[]" type="text">
</div>
<div class="form-group">
<label>Duration:</label>
<input name="seg-dur[]" type="text">
</div>
</div>
</div>
</div>
<br><br>
<div style="text-align: right;">
<button id="more_fields">+</button>
</div>
<br>
<br>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
i have a span tag in javascript file like that
<input type="text" id="name" onblur="submitFormEmail()"/>
<span class="error">This is an error</span>
and here is its style in the css
.form_wrapper span.error{
visibility:hidden;
color:red;
font-size:11px;
font-style:italic;
display:block;
margin:4px 30px;
}
how can i change the visibility of the span when calling the function submitFormEmail()??
function submitFormEmail(){
}
Just
document.getElementsByClassName(".error")[0].style.visibility="visible";
To call it in your function you can do the following:
function submitFormEmail(){
document.querySelector('.error').style.visibility = 'visible';
}
Assuming there has many input elements, so the function should find out which node be match.
function submitFormEmail(obj) {
var nextSpan = obj.nextSibling;
while(nextSpan.nodeType != 1){
nextSpan = nextSpan.nextSibling;
}
nextSpan.style.visibility = 'visible';
}
.error {
visibility: hidden;
color: red;
font-size: 11px;
font-style: italic;
display: block;
margin: 4px 30px;
}
<input type="text" id="name" onblur="submitFormEmail(this)" /> <span class="error">This is an error</span> <br/>
<input type="text" id="name1" onblur="submitFormEmail(this)" /> <span class="error">This is an error</span> <br/>
<input type="text" id="name2" onblur="submitFormEmail(this)" /> <span class="error">This is an error</span>
I am trying to rewrite this Jquery http://jsfiddle.net/Claudius/gDChA/4/ to use this HTML instead http://pastie.org/2370829
Jquery:
$('button.add', '#companyinfo').live('click', function(e) {
$(this).parent().find('button.remove').show();
$(this).hide();
var element = $(this).parents('.input').find('input').last().clone().prop('value','');
var name = element.prop('name');
var pattern = new RegExp(/\[(.*?)\]/);
var info = name.match(pattern)[1];
var newname = name.replace(pattern, '[' + info + 'info' + ']');
var newid = element.prop('id') + 'info';
element.prop('name', newname);
element.prop('id', newid);
element.insertAfter($(this).parents('.input').find('input').last());
})
$('button.remove', '#companyinfo').live('click', function(e) {
$(this).parent().find('button.add').show();
$(this).hide();
$(this).parents('.input').find('input').last().remove('input');
});
Old HTML
<fieldset id='companyinfo'><legend>Company info</legend>
<div class='input string optional'>
<label for='company_navn' class='string optional'>Count</label>
<input type='text' size='50' name='company[count]' id='company_navn' maxlength="255" class='string optional' />
<div class='button-row'>
<button class='add'>Add info</button>
<button class='remove'>Remove</button>
</div>
</div>
<div class="input string optional">
<label for="company_navn" class="string optional">Navn</label>
<input type="text" size="50" name="company[navn]" maxlength="255" id="company_navn" class="string optional">
<div class='button-row'>
<button class='add'>Add info</button>
<button class='remove'>Remove</button>
</div>
</div>
</fieldset>
New HTML:
<div class="input string optional"><label for="virksomhed_navn" class="string optional"> Navn</label><input type="text" size="50" name="virksomhed[navn]" maxlength="255" id="virksomhed_navn" class="string optional"></div>
<div class="button-row" style="font-size: 11px; width: 110px; float: right; margin-top: -10px; margin-right: 16px;">
<button class="add" style="font-size: 11px;">Add info</button>
<button class="remove" style="font-size: 11px;">Remove</button>
</div>
<div class="input string optional"><label for="virksomhed_name" class="string optional">Name</label><input type="text" size="50" name="virksomhed[name]" maxlength="255" id="virksomhed_name" class="string optional"></div>
<div class="button-row" style="font-size: 11px; width: 110px; float: right; margin-top: -10px; margin-right: 16px;">
<button class="add" style="font-size: 11px;">Add info</button>
<button class="remove" style="font-size: 11px;">Remove</button>
</div>
<div class="input string optional"><label for="virksomhed_pis" class="string optional">Pis</label><input type="text" size="50" name="virksomhed[v]" maxlength="255" id="virksomhed_pis" class="string optional"></div>
<div class="button-row" style="font-size: 11px; width: 110px; float: right; margin-top: -10px; margin-right: 16px;">
<button class="add" style="font-size: 11px;">Add info</button>
<button class="remove" style="font-size: 11px;">Remove</button>
</div>
How can I select the inputs fields in the new HTML and create the same functionality ?
There are two places you need to change.
The buttons that the handlers hook on to.
The way you get the last input field.
And there are some minor enhancements you can do:
Since the buttons are static, you can use click() to add event handler instead of live()
At three place you need to find the last input field relative to current button; making it a function would make it easier to understand and modify.
most jQuery set functions, including prop(), can take an object to set multiple values. This is usually better then calling the same function many times.
So, the final result:
function findLastInput ( element ) {
return $( element ).parent().prev().find('input').last();
}
$('button.add').click ( function(e) {
$(this).parent().find('button.remove').show();
$(this).hide();
var element = findLastInput(this).clone();
var name = element.prop('name');
var pattern = new RegExp(/\[(.*?)\]/);
var info = name.match(pattern)[1];
element.prop({
'value': '',
'name' : name.replace(pattern, '[' + info + 'info' + ']'),
'id' : element.prop('id') + 'info'
});
element.insertAfter(findLastInput(this));
})
$('button.remove').click ( function(e) {
$(this).parent().find('button.add').show();
$(this).hide();
findLastInput(this).remove('input');
});