I have a script that is used to count the number of characters in the input. It works well for the creation, but when it comes to the edit form the problem is that while displaying the old input it shows 0 and only starts counting when I'm starting to add some characters to the input. So I need it to display the number of characters of the old input even if I didn't add any new characters yet. How can I achieve that?
HTML code:
<input type="text" name="name" class="form-control" value="{{ $employee->name }}" placeholder="Name is..." id="myText">
<div class="d-flex justify-content-end">
<span id="wordCount" class="text-muted">0</span>
<span class="text-muted">/</span>
<span class="text-muted">256</span>
</div>
Script:
var myText = document.getElementById("myText");
var wordCount = document.getElementById("wordCount");
myText.addEventListener("keyup",function(){
var characters = myText.value.split('');
wordCount.innerText = characters.filter( item => {
return (item != ' ');
}).length;
});
var myText = document.getElementById("myText");
var wordCount = document.getElementById("wordCount");
const wordCounterHelper = () => {
var characters = myText.value.split('');
wordCount.innerText = characters.filter( item => {
return (item != ' ');
}).length;
}
wordCounterHelper()
myText.addEventListener("input", () => {wordCounterHelper()});
<input type="text" name="name" class="form-control" value="Funky Chicken" placeholder="Name is..." id="myText">
<div class="d-flex justify-content-end">
<span id="wordCount" class="text-muted">0</span>
<span class="text-muted">/</span>
<span class="text-muted">256</span>
</div>
Basically you need to run the code in the event listener once before, cause else it will only be executed once you begin typing in the edit form.
This is best done by putting the code into a function and the calling the function one separate time in the js.
Also I've changed the event to the input event as this fires on any value change of the input and not just keyup
Your code needs to be moved into a function so you can trigger it in multiple places. Also your code ignores paste events not done with the keyboard.
I kept word count there name there.... put you are counting letters, not words.
var myText = document.getElementById("myText");
var wordCount = document.getElementById("wordCount");
function setLetterCount() {
wordCount.innerText = myText.value.replace(/\s/g, '').length;
}
myText.addEventListener("input", setLetterCount);
setLetterCount();
<input type="text" name="name" class="form-control" value="Funky Chicken" placeholder="Name is..." id="myText">
<div class="d-flex justify-content-end">
<span id="wordCount" class="text-muted">0</span>
<span class="text-muted">/</span>
<span class="text-muted">256</span>
</div>
Other way is to trigger the event with dispatchEvent
var myText = document.getElementById("myText");
var wordCount = document.getElementById("wordCount");
myText.addEventListener("input", function() {
wordCount.innerText = myText.value.replace(/\s/g, '').length;
});
myText.dispatchEvent(new Event('input', {
bubbles: true
}));
<input type="text" name="name" class="form-control" value="Funky Chicken" placeholder="Name is..." id="myText">
<div class="d-flex justify-content-end">
<span id="wordCount" class="text-muted">0</span>
<span class="text-muted">/</span>
<span class="text-muted">256</span>
</div>
You can achieve this by setting the initial value of the wordCount element to the length of the value attribute of the myText input element, rather than 0. This can be done by adding this line of code before the event listener:
var myText = document.getElementById("myText");
var wordCount = document.getElementById("wordCount");
wordCount.innerText = myText.value.length;
myText.addEventListener("keyup",function(){
var characters = myText.value.split('');
wordCount.innerText = characters.filter( item => {
return (item != ' ');
}).length;
});
<input type="text" name="name" class="form-control" value="{{ $employee->name }}" placeholder="Name is..." id="myText">
<div class="d-flex justify-content-end">
<span id="wordCount" class="text-muted">0</span>
<span class="text-muted">/</span>
<span class="text-muted">256</span>
</div>
Related
I'm trying to make a button that when clicked adds an input tag to the page and gives it an id. The code to get the id is stored in an object. The code looks like this:
document.getElementById('signup-students-input' + currentInputTagNumber ).value
Then the code is ran through an eval function like so
console.log (eval(theObject.getInfo()))
And the eval creates this code
document.getElementById('input-3').value
However, this returns an empty string in the console and using an alert function.
I've attached a code snippet below:
var newStudentBtn = document.getElementById ("new-student");
var students = document.getElementById ("students");
var signupStudents = 1;
var cost = document.getElementById ("cost");
var confiredStudent = "";
let ids = new Object ();
ids.idNames = "";
ids.getInfo = function () {
return this.idNames;
};
var newStudentBtnOnClick = function () {
signupStudents++;
let newStudent = document.createElement ("input");
newStudent.placeholder="Type your child's first and last name here";
newStudent.id = "signup-students-input" + signupStudents;
let newStudentHeading = document.createElement ("h3");
let studentNewLine = document.createElement ("br");
newStudentHeading.innerHTML = "Child (" + signupStudents + ") First and Last Name";
students.appendChild (newStudentHeading)
students.appendChild (newStudent);
cost.innerHTML = signupStudents*39
if (signupStudents === 2) {
ids.idNames += "document.getElementById(" + "'signup-students-input' + signupStudents " + ").value "
}
else {
ids.idNames += "+ document.getElementById ('signup-students-input' + signupStudents).value "
}
console.log (ids.getInfo())
console.log (eval(ids.getInfo()))
};
newStudentBtn.addEventListener ("click", newStudentBtnOnClick);
<div class="nav-bar">
<nav>
<img src="img_2.jpg" class="nav-img">
<div class="nav-options">
<button class="nav-option">About Us</button>
<button class="nav-option">Classes</button>
<button class="nav-option">Contact Us</button>
</div>
</nav>
</div>
<div class="welcome">
<h1>Signup for the Intermedite Class</h1>
</div>
<div class="info-content">
<div class="diveder"><h2>Please fill out the form</h2></div>
<div class="info-content-blocks">
<form>
<div id="students">
<h3>Parent First and Last Name</h3>
<input placeholder="Type your first and last name here" required id="parent-name">
<h3>Child (1) First and Last Name</h3>
<input placeholder="Type your child's first and last name here" required class="student-names" id="student-1-name">
</div>
<br><br><button class="standard-button" id="new-student" type="button">New Student</button><br><br>
<h3>Parent Email Address</h3>
<input placeholder="Type your email address here" required id="email">
<h3>Parent Phone Number (For Emgerency Contact Only)</h3>
<input placeholder="Type your phone number here" required id="phone">
<p>Please pay $<span id="cost">39</span> cash after your childs first class.</p>
<button class="standard-button" type="submit" id="send-btn">Enroll</button>
</form>
</div>
</div>
</div>
I think the problem is that you are adding a string to ids.idNames instead of the variable signupStudents. I also changed the id of the default input from "student-1-name" to "signup-students-input1" and changed the ids.idNames default value. Here's a demo:
var newStudentBtn = document.getElementById ("new-student");
var students = document.getElementById ("students");
var signupStudents = 1;
var cost = document.getElementById ("cost");
var confiredStudent = "";
let ids = new Object ();
// changed this line
ids.idNames = "document.getElementById('signup-students-input1').value";
ids.getInfo = function () {
return this.idNames;
};
var newStudentBtnOnClick = function () {
signupStudents++;
let newStudent = document.createElement ("input");
newStudent.placeholder="Type your child's first and last name here";
newStudent.id = "signup-students-input" + signupStudents;
let newStudentHeading = document.createElement ("h3");
let studentNewLine = document.createElement ("br");
newStudentHeading.innerHTML = "Child (" + signupStudents + ") First and Last Name";
students.appendChild (newStudentHeading)
students.appendChild (newStudent);
cost.innerHTML = signupStudents*39
/* changed these lines */
ids.idNames += "+ document.getElementById('signup-students-input" + signupStudents + "').value";
console.log (ids.getInfo())
console.log (eval(ids.getInfo()))
};
newStudentBtn.addEventListener ("click", newStudentBtnOnClick);
<div class="nav-bar">
<nav>
<img src="img_2.jpg" class="nav-img">
<div class="nav-options">
<button class="nav-option">About Us</button>
<button class="nav-option">Classes</button>
<button class="nav-option">Contact Us</button>
</div>
</nav>
</div>
<div class="welcome">
<h1>Signup for the Intermedite Class</h1>
</div>
<div class="info-content">
<div class="diveder"><h2>Please fill out the form</h2></div>
<div class="info-content-blocks">
<form>
<div id="students">
<h3>Parent First and Last Name</h3>
<input placeholder="Type your first and last name here" required id="parent-name">
<h3>Child (1) First and Last Name</h3>
<!-- this line changed -->
<input placeholder="Type your child's first and last name here" required class="student-names" id="signup-students-input1">
</div>
<br><br><button class="standard-button" id="new-student" type="button">New Student</button><br><br>
<h3>Parent Email Address</h3>
<input placeholder="Type your email address here" required id="email">
<h3>Parent Phone Number (For Emgerency Contact Only)</h3>
<input placeholder="Type your phone number here" required id="phone">
<p>Please pay $<span id="cost">39</span> cash after your childs first class.</p>
<button class="standard-button" type="submit" id="send-btn">Enroll</button>
</form>
</div>
</div>
</div>
When I select a number that starts with 0, such a number is converted to its octal form which I don't want but works perfectly well for those that didn't start with 0. Attached is pictures explaining what I mean.
Before Selection of Number starting with 0
After Selection of Number starting with 0
From the picture you can see 0703 got converted to 451. How can I stop this.
let phoneNumberSelector = document.querySelector("#phone");
const mtnNumber = ['703', '706', '803', '806', '810', '813', '814', '816', '903', '906', '913', '0703', '0706'];
phoneNumberSelector.addEventListener('keyup', (e) => {
removeElements();
for (let i of mtnNumber) {
// i = i.toString();
if (i.startsWith(phoneNumberSelector.value) && phoneNumberSelector.value != '') {
let listItem = document.createElement("li");
listItem.classList.add('list-items');
listItem.style.cursor = 'pointer';
listItem.setAttribute('onclick', "displayNames(" + i + ")")
let word = "<b>" + i.slice(0, phoneNumberSelector.value.length) + "</b>";
word += i.slice(phoneNumberSelector.value.length);
listItem.innerHTML = word;
document.querySelector('.list').appendChild(listItem);
}
}
})
function displayNames(param) {
phoneNumberSelector.value = param;
removeElements();
}
function removeElements() {
let items = document.querySelectorAll('.list-items')
items.forEach((element) => {
element.remove();
});
}
<section class="section1"></section>
<section class="section2">
<div class="reg-form">
<form action="" method="">
<div class="form-container">
<h1 style="text-align: center;">Phonie</h1>
<div class="input-reg email-input">
<label for="username">Username</label>
<input id="username" type="text" name="username">
</div>
<div class="list-div">
<ul class="list"></ul>
</div>
<div class="input-reg email-input">
<label for="phone">Phone Number</label>
<input id="phone" type="text" name="phone">
</div>
<div class="input-reg email-input">
<input class="submit-btn submit-btn2" type="submit" value="Check Number">
</div>
</div>
</form>
</div>
</section>
The numbers are getting converted to octal because you are passing the number (of type string) to the displayNames function as a number (without quotes).
This is the offending line:
listItem.setAttribute('onclick', "displayNames(" + i + ")")
with the value of i set to "0703", the value for onclick becomes "displayNames(0703)".
You can fix this by adding quotes around the i variable in the string passed as onclick.
For example:
listItem.setAttribute('onclick', "displayNames('" + i + "')");
or with a string template to make it a bit easier to read:
listItem.setAttribute('onclick', `displayNames("${i}")`);
I need the following output as shown in the gif below.
I created three inputs which I put in the box below. How can I have such output?
Please help with an example
NOTE:Suppose we have 50 inputs and the class is the same
I can't use it after Get ID
MY HTML code
<span class="pricing-heading">Your sale price:</span><div class="pricing-field"><input class="pricing-set-price" type="number" value="24.00"></div>
</div>
<div class="prt-pricing-detial">
<span class="pricing-heading">Product base Cost:</span><div class="pricing-field"><input class="pricing-base-price" type="number" value="10.00" disabled></div>
</div>
<div class="prt-pricing-detial">
<span class="pricing-heading">Your profit:</span><div class="pricing-field"><input class="pricing-profit" type="number" value="14.00" disabled></div>
</div>
JS code :
$(".pricing-set-price").change(function(){
var item_rrp = $(this).val();
var item_base = $(this).parent().parent().parent().find('.pricing-base-price').val();
var profit = item_rrp - item_base;
var profit_format = profit.toFixed(2);
$(this).parent().parent().parent().find('.pricing-profit').val(profit_format);
});
You may try like
$(".pricing-set-price").change(function(){
let currentValue = $(this).val();
var previousValue = this.defaultValue;
if(previousValue < currentValue){
this.defaultValue = currentValue;
console.log('Increment');
}else{
console.log('Decrement');
}
});
You can call the function that changes the value of Profit (input) on the onchange , oninput, or onClick events of the SalePrice(input)
function increment() { document.getElementById('salePrice').stepUp();
calculateProfit()
}
function decrement() {
document.getElementById('salePrice').stepDown();
calculateProfit()
}
function calculateProfit(){
let sp = document.getElementById("salePrice").value;
document.getElementById("profit").value = sp - 10;
}
<input id="salePrice" type=number value=10 min=10 max=110 />
<button onclick="increment()">+</button>
<button onclick="decrement()">-</button>
<br/>
Base Price :: <input type="text" id="basePrice" value=10
disabled >
<br/>
Profit :: <input type="text" id="profit" value=0 />
For more info about:
stepUp()
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/stepUp
stepDown()
https://www.w3schools.com/Jsref/met_week_stepdown.asp
Hi i think this might help. use id for your input fields.
function calculateProfit(val){
var baseCost = document.getElementById("baseCost").value;
document.getElementById("Profit").value = (val - baseCost).toFixed(2);
}
<div class="prt-pricing-heading">
<span class="pricing-heading">Your sale price:</span>
<div class="pricing-field"><input id="SalePrice" class="pricing-set-price" type="number" value="24.00" onchange="calculateProfit(this.value);" oninput="calculateProfit(this.value)"></div>
</div>
<div class="prt-pricing-detial">
<span class="pricing-heading">Product base Cost:</span>
<div class="pricing-field"><input id="baseCost" class="pricing-base-price" type="number" value="10.00" disabled></div>
</div>
<div class="prt-pricing-detial">
<span class="pricing-heading">Your profit:</span>
<div class="pricing-field"><input id="Profit" class="pricing-profit" type="number" value="14.00" disabled></div>
</div>
For More info regarding:
oninput() https://www.w3schools.com/tags/att_oninput.asp
onchange() https://www.w3schools.com/tags/ev_onchange.asp
I' trying to build a form in which the users can change the values of two password inputs, one for a password and a second one to verify the password.
So in order to make the user aware of what he types and to make sure both of his/her password match with one another and tried to implemente a method in which he can just check a checkbox to show his password.
The current javascript method works with just one input but I would like to have it working with both input and not just one. I would like as well to show the password of both input without having to check their own corresponding checkbox(for example if a check one checkbox it should display text in both inputs).
This is the current javascript method that I have:
// First Code //
function addEvent (el, event, callback) {
if ('addEventListener' in el) {
el.addEventListener(event, callback, false);
} else {
el['e' + event + callback] = callback;
el[event + callback] = function () {
el['e' + event + callback](window.event);
};
el.attachEvent('on' + event, el[event + callback]);
}
}
function removeEvent(el, event, callback) {
if ('removeEventListener' in el) {
el.removeEventListener(event, callback, false);
} else {
el.detachEvent('on' + event, el[event + callback]);
el[event + callback] = null;
el['e' + event + callback] = null;
}
}
// Second Code //
(function() {
var pwd = document.getElementById('password');
var chk = document.getElementById('showpass');
addEvent(chk, 'change', function(e) {
var target = e.target || e.srcElement;
try {
if (target.checked) {
password.type = 'text';
} else {
password.type = 'password';
}
} catch(error) {
alert('This browser cannot switch type');
}
});
}());
<!-- First Password -->
<div class="form-group">
<label for="password">Password</label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-lock" aria-hidden="true"></i>
</div>
<input type="password" name="password" value="" id="password" class="form-control">
<div class="input-group-addon"><input type="checkbox" id="showpass"></div>
</div>
</div>
<!-- Second Password -->
<div class="form-group">
<label for="password2">Confirm Password</label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-lock" aria-hidden="true"></i>
</div>
<input type="password" name="password2" value="" id="password2" class="form-control">
<div class="input-group-addon"><input type="checkbox" id="showpass"></div>
</div>
</div>
Thanks in advance.
Change the type of both inputs at once:
var pwd = document.getElementById('password');
var confirm = document.getElementById('password2');
...
if (target.checked) {
pwd.type = 'text';
confirm.type = 'text';
} else {
pwd.type = 'password';
confirm.type = 'password';
}
Added a little fiddle to toggle the password type.
https://jsfiddle.net/xpvt214o/321232/
JS
var $vp = $('.vp');
$vp.on('click', function() {
var $target = $(this).siblings('input[name*="password"]');
if ($target.attr('type') == "password") {$target.attr('type','text');}
else {$target.attr('type','password');}
});
HTML
<div style="width:100%;float:left;margin:0 0 16px 0;">
<p>Password 1</p>
<input type="password" name="password" val="" />
<span class="vp">View password</span>
</div>
<div style="width:100%;float:left;margin:0 0 16px 0;">
<p>Password 2</p>
<input type="password" name="password2" val="" />
<span class="vp">View password</span>
</div>
The function looks for the click event of the span "vp" and get's its sibling input element, checks the type attribute and toggles it to and from text/password. The name of the inputs must contain "password" (in lowercase).
Hey all I am using the jQuery plugin called jSearch and I have the following code that currently allows me to search some tags within the said class name:
var jSearch = (function () {
var input = $('#searchTxtBox');
var items = $('#inventory .select3-multiple-selected-item');
input.keyup(function () {
var input = $(this).val();
switch (true) {
case input === '':
items.css('opacity', '1');
break;
default:
items.css('opacity', '0.2');
items.filter('[data-searchBox*="' + input.toLowerCase() + '"]').css('opacity', '1');
break;
}
});
}());
And some of the HTML:
<div class="cssMadeTbl-cell">
<label class="control-label" data-base="NEW_Project" data-definedas="text" data-required="True" for="inventory"></label>
<div style="float: right;">
<input class="tips" data-tooltip="example 1" id="searchTxtBox" name="searchTxtBox" placeholder="Search..." type="search" value=" ">
</div>
<div class="input-group">
<span data-db="bomStatus" class="bomClass" data-id="The Status">The Status</span>
<span id="lblBG"></span>
<div class="input-group-addon" style="width: 33px;">
<img src="data:image/svg+xml;base64,+DQo8L2c+DQo8L2c+DQo8L2c+Qo8L2c+DQo8L2c+DQo8L3N2Zz4NCg==" id="iconImg_currentUsers" style="width: 20px; height:20px;">
</div>
<div class="col-sm-10">
<span id="inventory" class="tips form-control input-sm" data_tooltip="example 1" data-cnt="0">
<div class="select3-multiple-input-container">
<span class="select3-multiple-selected-item" data-item-id="1" data-searchbox="pending">Pending</span>
<span class="select3-multiple-selected-item" data-item-id="2" data-searchbox="approved">Approved</span>
<span class="select3-multiple-selected-item" data-item-id="3" data-searchbox="denied">Denied</span>
<span class="select3-multiple-selected-item" data-item-id="ADDtab_100954500" data-searchbox="add item">ADD ITEM</span>
<input type="text" autocomplete="off" autocorrect="off" autocapitalize="off" class="select3-multiple-input" placeholder="">
<span class="select3-multiple-input select3-width-detector"></span>
<div class="clearfix"></div>
</div>
</span>
</div>
</div>
</div>
This works just fine for the above area. But the problem is that, on that same page, I have more InventoryXX id's that I am in need of adding the search box too as well. These range from Inventory to Inventory18.
I know I could do something like this:
var jSearch1 = (function () {
var input = $('#searchTxtBox');
var items = $('#inventory .select3-multiple-selected-item');
[more code here....]
var jSearch2 = (function () {
var input = $('#searchTxtBox');
var items = $('#inventory1 .select3-multiple-selected-item');
[more code here....]
var jSearch3 = (function () {
var input = $('#searchTxtBox');
var items = $('#inventory2 .select3-multiple-selected-item');
[more code here....]
[etc etc...]
But that would look really messy...
How can I modify this jQuery script in order to accommodate all those Inventory id's but still have each separate from each other?
Try to omit the #inventory:
var items = $('.select3-multiple-selected-item');
or modify the selector this way if you need to target #inventory* only:
var items = $('[id^="inventory"] .select3-multiple-selected-item');