Count character for textarea closest field - javascript

I have 4-5 textarea on my page and I have set the limitation of the character. The user can add 500 characters.
Now my issue is, I have to show the character count for the closest field. As of now, it's showing for all. I mean if I add any content in the first textarea then count showing for all textarea.
Please check the below image.
I was trying something like this
current = $(this).closest('.row .valInfo').find('.currentchar'),
maximum = $(this).closest('.valInfo').find('.maximumchar'),
//theCount = $('.valInfo');
theCount = $(this).closest('.valInfo')
$('.characterCount').keyup(function() {
var characterCount = $(this).val().length,
current = $('.currentchar'),
maximum = $('.maximumchar'),
theCount = $('.valInfo');
current.text(characterCount);
}
);
<div class="row">
<div class="col-lg-6">
<textarea maxlength="500" class="characterCount"></textarea>
<div class="valInfo"><span class="currentchar">0</span> <span class="maximumchar">/ 500</span> Characters</div>
</div>
<div class="col-lg-6">
<textarea maxlength="500" class="characterCount"></textarea>
<div class="valInfo"><span class="currentchar">0</span> <span class="maximumchar">/ 500</span> Characters</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

You want to find the corresponding currentchar, maximumchar and valinfo elements relative to the element that has been edited. For example by only finding matching elements in the shared parent:
$('.characterCount').keyup(function() {
var elem = $(this),
characterCount = elem.val().length;
current = elem.parent().find('.currentchar'),
maximum = elem.parent().find('.maximumchar'),
theCount = elem.parent().find('.valInfo');
current.text(characterCount);
}
);
<div class="row">
<div class="col-lg-6">
<textarea maxlength="500" class="characterCount"></textarea>
<div class="valInfo"><span class="currentchar">0</span> <span class="maximumchar">/ 500</span> Characters</div>
</div>
<div class="col-lg-6">
<textarea maxlength="500" class="characterCount"></textarea>
<div class="valInfo"><span class="currentchar">0</span> <span class="maximumchar">/ 500</span> Characters</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Related

textarea text erases when using innerHTML

I have this function which uses innerHTML to insert html into a div:
function displayInputIntro() {
var submitbutton = document.getElementById('submitbutton')
var intro = document.getElementById('Intro')
var introNewSection = document.getElementById('intro-row')
var uniqueID = ""
var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var length = 7
for (var i = length; i > 0; --i) uniqueID += chars[Math.floor(Math.random() * chars.length)];
uniqueID = uniqueID
introNewSection.innerHTML += '<div class="col-lg-5 mb-lg-0 mb-4" id=' + uniqueID + '><div class="card z-index-2"> <div class="card-body p-3" style="margin-top: -20px;"> <h6 class="ms-2 mt-4 mb-0">Intro <i class="fa fa-times" style="color: gray;"></i></h6> <p class="text-sm ms-2">Section 1</p> <div class="container border-radius-lg"> <div class="row"> <textarea type="text" class="form-control" name="intro" placeholder="Enter your current Intro" id="textvalue" style="height: 100px;" required></textarea> </div> </div> </div> </div></div>'
submitbutton.style.display = ''
}
and then my html:
<div class="row mt-4" id="intro-row"></div>
however, as you can see in the introNewSection.innerHTML, I have a <textarea type="text" class="form-control" name="intro" placeholder="Enter your current Intro" id="textvalue" style="height: 100px;" required></textarea>
the problem is, this function displayInputIntro() can be triggered multiple times. Every time its triggered, and there's any text inside the textarea, it just clears it and I don't know why. how can I fix this?
First thing you need to close the HTML tags properly, is not closing properly , i see is not having closing tag while assigning html to innerHTML, Second thing whenever you are using innerHTML it will override the html content.
If you want to inject the html then use insertAdjacentHTML tag and execute as below
introNewSection.insertAdjacentHTML('afterend', 'additional HTML code');
Note: You should find out why the function is triggering multiple times.

How do I make this conversion function work in both directions?

I'm new in JS and I have trouble to finish a converter only with inputs, I explain the problem !
We have two input, Meters and Feet. when I transmit a number to Feet I have the result in Meters. And I Want to do the same think with Meters . and vice versa
let metresEl = document.getElementById('inputMetres');
function LengthConverter(valNum) {
metresEl.value = valNum/3.2808;
}
<div class="container">
<div class="form-group">
<label>Feet</label>
<input type="number" id="inputFeet" placeholder="Feet" oninput="LengthConverter(this.value)" onchange="LengthConverter(this.value)" >
</div>
<div class="form-group">
<label>Metres</label>
<input type="number" id="inputMetres" placeholder="Metres">
</div>
</div>
You can add another parameter in the LengthConvertor function which will say the input unit (meter or feet) and convert it accordingly inside the function using if.
function LengthConverter(valNum, inputUnit) {
if(inputUnit === 'feet')
metresEl.value = valNum/3.2808;
if(inputUnit === 'meter')
feetsEL.value = valNum * 3.2808;
}
<div class="container">
<div class="form-group">
<label>Feet</label>
<input type="number" id="inputFeet" placeholder="Feet" oninput="LengthConverter(this.value,"feet")" onchange="LengthConverter(this.value,"feet")" >
</div>
<div class="form-group">
<label>Metres</label>
<input type="number" id="inputMetres" placeholder="Metres" oninput="LengthConverter(this.value,"meter")" onchange="LengthConverter(this.value,"meter")" >
</div>
</div>
Added inverse conversion:
let metresEl = document.getElementById('inputMetres');
let feetEl = document.getElementById('inputFeet');
function FeetToMetres(valNum) {
metresEl.value = valNum/3.2808;
}
function MetresToFeet(valNum) {
feetEl.value = 3.2808*valNum;
}
<div class="container">
<div class="form-group">
<label>Feet</label>
<input type="number" id="inputFeet" placeholder="Feet" oninput="FeetToMetres(this.value)" onchange="FeetToMetres(this.value)" >
</div>
<div class="form-group">
<label>Metres</label>
<input type="number" id="inputMetres" placeholder="Metres" oninput="MetresToFeet(this.value)" onchange="MetresToFeet(this.value)">
</div>
</div>
You can add a element.addEvenetListener to each input, and when it chances you get it's value, convert, and put in on the right input.
let metresEl = document.getElementById('inputMetres');
let feetsEl = document.getElementById('inputFeets');
metresEl.addEventListener('change', yourCode);
feetsEl.addEventListener('change', yourCode);
For exemple, if metres input changes, you convert to feets and add to feets input.

How to spawn a new div prior to the last div in a container?

I'm trying to create new fields like the first field in this form by clicking on an image, but the fields are spawning below the button to submit and I don't understand why. The behavior I'm looking for is for the new fields to spawn above the button.
Here's my code
<div id="title">
<h1>Monthly Run Operations Assessment</h1>
</div>
<div class="row">
<div class="col-20" id="row-one">
<label for="name">1. </label>
</div>
<div class="col-60">
<input type="text" id="op" name="op" placeholder="Insert operation here">
</div>
<div class="col-20" id="symbol">
<img src="file:///C:/Users/user/Downloads/plus-circle-solid.svg" id="add">
</div>
</div>
<div id="submit">
<input type="submit" value="Submit">
</div>
</div>
This is the function:
var element = document.getElementById("add");
element.onclick = function() {
console.log("woot");
var ele = document.getElementsByClassName("row")[0];
var clone = ele.cloneNode(true);
var newDiv = document.createElement("div");
document.body.appendChild(clone);
}
appendChild, as its name suggests, always appends the new element -- that is, it adds it to the end. What you want is insertBefore:
document.body.insertBefore(clone, ele);
One way to handle this is to wrap your form in a container and append to it :
var element = document.getElementById("add");
element.onclick = function() {
// console.log("woot");
var ele = document.getElementsByClassName("row")[0];
var clone = ele.cloneNode(true);
var newDiv = document.createElement("div");
document.querySelector('#container').appendChild(clone);
}
<div id="title">
<h1>Monthly Run Operations Assessment</h1>
</div>
<div id="container">
<div class="row">
<div class="col-20" id="row-one">
<label for="name">1. </label>
</div>
<div class="col-60">
<input type="text" id="op" name="op" placeholder="Insert operation here">
</div>
<div class="col-20" id="symbol">
<img src="file:///C:/Users/user/Downloads/plus-circle-solid.svg" id="add">
</div>
</div>
</div>
<div id="submit">
<input type="submit" value="Submit">
</div>
</div>
I combined the above answers to achieve the expected behavior.
var element = document.getElementById("add");
element.onclick = function() {
// console.log("woot");
var ele = document.getElementsByClassName("row")[0];
var clone = ele.cloneNode(true);
var newDiv = document.createElement("div");
document.querySelector('#container').insertBefore(clone, ele);
}

How to loop through the form which has random elements

I am trying to loop through the form which has label inside random elements and check if the label matches with the given label name and if matches, I am adding a class to that element. But I am not able get it working, how can I do this?
Here's what I have tried.
Form which has labels inside random elements like div
<form id="grtform">
<div id="section-1">
<lable>Currency type</lable>
<input type="text" name="currencyType">
</div>
<div id="section-2">
<lable>Currency rate</lable>
<input type="text" name="currencyRate">
</div>
<lable>Currency of country</lable>
<input type="text" name="currencyCountry">
<div id="section-3">
<div class="formData">
<lable>Currency due</lable>
<input type="text" name="currencyDue">
</div>
</div>
</form>
Jquery code:
$("#grtform").each(function(){
var matchLable = "Currency due"
var lable = $(this).find('label').text();
if(matchLable == lable){
$(this).addClass('matchFound');
}
});
You need loop through lables, not against form
$("#grtform lable").each(function(){ // selecting all labels of form
var matchLable = "Currency type"
var lable = $(this).text(); // changed here too
if(matchLable == lable){
$(this).addClass('matchFound');
}
});
In above code, this refers to currently iterating label.
After trimming a bit
$("#grtform lable").each(function(){ // selecting all labels of form
if($(this).text() == "Currency type"){
$(this).addClass('matchFound');
}
});
You can also use following way :-
var allLables = document.querySelectorAll("#grtform lable");
for(var i = 0; i < allLables.length; i++){
var matchLable = "Currency type";
var lable = allLables[i].innerText; // changed here too
if(matchLable == lable){
allLables[i].classList.add("matchFound");
}
}
<form id="grtform">
<div id="section-1">
<lable>Currency type</lable>
<input type="text" name="currencyType">
</div>
<div id="section-2">
<lable>Currency rate</lable>
<input type="text" name="currencyRate">
</div>
<lable>Currency of country</lable>
<input type="text" name="currencyCountry">
<div id="section-3">
<div class="formData">
<lable>Currency due</lable>
<input type="text" name="currencyDue">
</div>
</div>
</form>

Change href to tel: + number (user defined)

I'm trying to write a script where users can type a phone number and store it in the input (which works in this demo: http://bootsnipp.com/snippets/featured/iphone-number-pad) and then update href="" = "tel:" + that-same-value. So for example the if the user types 600 999 999 the href is updated to href="tel:600 999 999" and the user can then click the the button and make a call.
I've been beating myself up trying to figure this out. It seemed really simple because I'm not even trying to use restrict the phone number to 6-7 characters long.
Any help would be greatly appreciated.
$(document).ready(function() {
// Get number
$('.num').click(function() {
var num = $(this);
var text = $.trim(num.find('.txt').clone().children().remove().end().text());
var telNumber = $('#telNumber');
$(telNumber).val(telNumber.val() + text);
$('#call-this').href = "tel:" + $(telNumber).val(telNumber.val() + text)
console.log(text);
console.log(telNumber);
});
// add number to href
var call = $(#call - this).attr('target')
// Other stuff I've tired
// $('#call-this').click(
// $('#call-this').href="tel:" + $(telNumber).val(telNumber.val() + text)
// var call = $('#call-this');
// $('#call-this').href= "tel:" + telNumber;
// console.log(call);
// });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="tel" name="name" id="telNumber" class="form-control tel" value="" />
<div class="num">
<div class="txt">0</div>
</div>
<div class="num">
<div class="txt">1</div>
</div>
<div class="num">
<div class="txt">2</div>
</div>
<div class="num">
<div class="txt">3</div>
</div>
<div class="num">
<div class="txt">4</div>
</div>
<div class="num">
<div class="txt">5</div>
</div>
<div class="num">
<div class="txt">6</div>
</div>
<div class="num">
<div class="txt">7</div>
</div>
<div class="num">
<div class="txt">8</div>
</div>
<div class="num">
<div class="txt">9</div>
</div>
<button class="expand">
Call
</button>
Your function can actually be simplified into this — the reason is that you don't need to actually transverse all the way to the .txt element if it is the one and only child of .num and that it only contains the number of interest.
$(document).ready(function () {
$('.num').click(function () {
// Append trimmed number to current value
$(telNumber).val($(telNumber).val() + $(this).text().trim());
// Update href attribute on #call-this
$('#call-this').attr('href', 'tel:'+$(telNumber).val());
});
});
See fiddle here: http://jsfiddle.net/teddyrised/jwqL4o8w/3
In fact, a better choice would be to store the number in the HTML5 data- attribute, so you can freely change the innerHTML of the .txt element without having to worry about issues:
<div class="num" data-num="0">
<div class="txt">0</div>
</div>
Then for your JS, just use:
$(document).ready(function () {
$('.num').click(function () {
// Append trimmed number to current value
$(telNumber).val($(telNumber).val() + $(this).data('num'));
// Update href attribute on #call-this
$('#call-this').attr('href', 'tel:'+$(telNumber).val());
});
});
I think where you have
$('#call-this').href="tel:" + $(telNumber).val(telNumber.val() + text)
It should be
$('#call-this').attr("href", "tel:" + telNumber.val());
edit I just caught the double val()
I think you need this, i have simplified the solution.
$("#telNumber").on("blur", function() {
$("#call-this").prop("href", "tel:" + $(this).val());
alert($("#call-this").prop("href"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="tel" name="name" id="telNumber" class="form-control tel" value="" />
<button class="expand">
Call
</button>
If you want to link a button your HTML code should look like this:
<input type="tel" name="name" id="telNumber" class="form-control tel" value="" />
<div class="num">
<div class="txt">0</div>
</div>
<div class="num">
<div class="txt">1</div>
</div>
<div class="num">
<div class="txt">2</div>
</div>
<div class="num">
<div class="txt">3</div>
</div>
<div class="num">
<div class="txt">4</div>
</div>
<div class="num">
<div class="txt">5</div>
</div>
<div class="num">
<div class="txt">6</div>
</div>
<div class="num">
<div class="txt">7</div>
</div>
<div class="num">
<div class="txt">8</div>
</div>
<div class="num">
<div class="txt">9</div>
</div>
<form action="#">
<input type="submit" value="Call" />
</form>
and script will be:
$(document).ready(function () {
$('.txt').on('click', function () {
$("#telNumber").val($("#telNumber").val() + $(this).text());
$("form").attr('action', "tel:" + $("#telNumber").val());
});
});
JSFiddle

Categories