How to in real-time format user input? For example, the user puts A9364470240ZGS001 to the input field, and using JavaScript format it in the input field in real-time to be like: A 936 447 02 40 ZGS 001?
<div class="childDumpFile">
<label for="ds">Dataset</label>
<input type="text" class="form-control" id="ds" name="ds" value="{{Request::get('ds') ?? ''}}">
</div>
I found the true answer. These expectations are naming as "input-mask" and if you'd like to use. You have to use 3. party libraries. Some of them listing in following sites:
Libraries 1
Libraries 2
I chose Cleave.js for your question. This is the demo:
<script src="https://nosir.github.io/cleave.js/dist/cleave.min.js"></script>
<script src="https://nosir.github.io/cleave.js/dist/cleave-phone.i18n.js"></script>
<script>
function loadFunction() {
// custom
var cleaveCustom = new Cleave('.input-custom', {
blocks: [1, 3, 3, 2, 2, 3, 3],
delimiter: ' ',
});
}
</script>
<body onload="loadFunction()">
A 936 447 02 40 ZGS 001
<div class="container">
<input class="input-custom" placeholder="Custom delimiter & blocks" />
</div>
</body>
If we suppose users have to write the characters one by one. This will work.
<body>
<input type="text" class="form-control" id="ds" name="ds" onkeypress="keyPress()" maxlength="23">
</body>
<script>
function keyPress() {
var field = document.getElementById("ds");
var text = field.value;
if(text.length == 1 || text.length == 5
|| text.length == 9 || text.length == 12
|| text.length == 15 || text.length == 19 ) {
var newText = text + " ";
field.value = newText;
}
}
</script>
Here is a little example.
<div class="childDumpFile">
<label for="ds">Dataset</label>
<input type="text" class="form-control" id="ds" name="ds">
</div>
<div class="test_ds"></div>
JS with jquery.
$("#ds").change(function(){
var ds_value = $("#ds").val();
var temp = ds_value;
temp = temp.substring(0,1) + " " + temp.substring(1, 4) + " " + temp.substring(4, 7) + " " + temp.substring(7, 9) + " " + temp.substring(9, 11) + " " + temp.substring(11, 14) + " " + temp.substring(14, 17);
$("#ds").val(temp);
$(".test_ds").html(temp);
});
Here is a demo -
https://jsfiddle.net/Kistlak/7bkdtev8
First, you need add onchange="getTimeNow()" oninput="getTimeNow()" in to input
<input type="text" class="form-control" id="ds" name="ds" value="{{Request::get('ds') ?? ''}}" onchange="getTimeNow()" oninput="getTimeNow()">
Finally, you get event input text
<script>function getTimeNow(){console.log(new Date())}</script>
Related
I'm making a program that returns value from input field, then changes string of field to x result depending condition. Would really appreciate help as members here have always greatly helped me in the past. Debugger is throwing this error and of course nothing is working:
script.js:22 Uncaught TypeError: Cannot set property 'innerHTML' of null
at uberChecker (script.js:22)
at HTMLButtonElement.onclick (index.html:25)
Here is my code (beginner here):
JS:
var username = document.getElementById("myUsername").value;
var groupIs = document.getElementById("myGroup").value;
var warnings = document.getElementById("myWarning").value;
var postCount = document.getElementById("myPostCount").value;
function uberChecker() {
if ((groupIs != ('Uber' || 'uber') && postCount > '1000') && warnings === '0') {
document.querySelector("output-box").innerHTML = "You can become Uber !";
} else if (postCount < '1000' && warnings === '0') {
document.querySelector("output-box").innerHTML = (username + ' You have ' + postCount + ' posts, you do not meet the requirements');
} else if (warnings != '0' && postCount > '1000') {
document.querySelector("output-box").innerHTML = (username + ' You cannot upgrade with ' + warnings + ' warning')
} else if (postCount < '1000' && warnings != '0') {
document.querySelector("output-box").innerHTML = (username + ' you have ' + postCount + ' posts which is less than 1000 and you have ' + warnings + '% warning. You cannot upgrade');
} else {
document.querySelector("output-box").innerHTML = (username + ' You are already Uber');
}
}
HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="blue-box"></div>
<input type="text" placeholder="Type username" id="myUsername" class="user" >
<input type="text" placeholder="Type user group" id="myGroup" class="group">
<input type="text" placeholder="Type post count" id="myPostCount" class="post">
<input type="text" placeholder="Type warning level" id="myWarning" class="warning">
<div class="UsernameText">Username</div>
<div class="groupText">Group</div>
<div class="postText">Posts</div>
<div class="warningText">Warning</div>
<button type="button" onclick="uberChecker();" class="black-box">Check if you are upgradeable</button>
<div class="output-box">Result will display here</div>
<script src="script.js"></script>
</body>
</html>
put a dot before the class name.
document.querySelector(".output-box").innerHTML = "You can become Uber !";
The problem is in this line
document.querySelector("output-box").innerHTML
querySelector function takes a selector
just change it to
document.querySelector(".output-box").innerHTML
And it will work
The problem are these statements: document.querySelector("output-box")
You are looking for an element here instead of a class. You need to add a dot (.) in front of the classname so that the querySelector works properly:
document.querySelector(".output-box")
Try following code, this will remove all error:
There are two issues in your code:
1 - You are declaring variables before creating input fields.
2 - You are using querySelector in wrong way.
Put js before end of body tag.
var username = document.getElementById("myUsername").value;
var groupIs = document.getElementById("myGroup").value;
var warnings = document.getElementById("myWarning").value;
var postCount = document.getElementById("myPostCount").value;
function uberChecker() {
if ((groupIs != ('Uber' || 'uber') && postCount > '1000') && warnings === '0') {
document.querySelector(".output-box").innerHTML = "You can become Uber !";
} else if (postCount < '1000' && warnings === '0') {
document.querySelector(".output-box").innerHTML = (username + ' You have ' + postCount + ' posts, you do not meet the requirements');
} else if (warnings != '0' && postCount > '1000') {
document.querySelector(".output-box").innerHTML = (username + ' You cannot upgrade with ' + warnings + ' warning')
} else if (postCount < '1000' && warnings != '0') {
document.querySelector(".output-box").innerHTML = (username + ' you have ' + postCount + ' posts which is less than 1000 and you have ' + warnings + '% warning. You cannot upgrade');
} else {
document.querySelector(".output-box").innerHTML = (username + ' You are already Uber');
}
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="blue-box"></div>
<input type="text" placeholder="Type username" id="myUsername" class="user">
<input type="text" placeholder="Type user group" id="myGroup" class="group">
<input type="text" placeholder="Type post count" id="myPostCount" class="post">
<input type="text" placeholder="Type warning level" id="myWarning" class="warning">
<div class="UsernameText">Username</div>
<div class="groupText">Group</div>
<div class="postText">Posts</div>
<div class="warningText">Warning</div>
<button type="button" onclick="uberChecker();" class="black-box">Check if you are upgradeable</button>
<div class="output-box">Result will display here</div>
<script src="script.js"></script>
</body>
</html>
Change selector condition from ("output-box") to (".output-box")
I've looked at lots of posts but I couldn't find anything that works in my case. I need to display of a preview of the user's signature in their profile, with the options to not show their phone number and/or email address so I have a checkbox for each.
Here's my HTML for the checkboxes:
<div class="checkbox">
<label>
<input type="checkbox" name="showInSignature[]" id="showPhoneId" value="showPhone" class="checkbox style-0" checked="checked">
<span>Teléfono</span>
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="showInSignature[]" id="showEmailId" value="showEmail" class="checkbox style-0" checked="checked">
<span>Dirección de e-mail</span>
</label>
</div>
and here is the jQuery:
var fname = $('#personalOptionsForm').find('[name="fname"]').val(),
lname = $('#personalOptionsForm').find('[name="lname"]').val(),
cellphone = $('#personalOptionsForm').find('[name="cellphone"]').val(),
email = $('#personalOptionsForm').find('[name="email"]').val(),
if ($('#showPhoneId').is(':checked') = true) {
showPhone = 1;
} else {
showPhone = 0;
},
// showPhone = (($('input[name="showInSignature[]"]')['showPhone'].checked = true) ? 1 : 0),
// showEmail = (($('input[name="showInSignature[]"]')['showEmail'].checked = true) ? 1 : 0),
str = "<strong>" + fname + " " + lname + "</strong><br /><br />" + ((showPhone = 1) ? 'Teléfono: ' + cellphone + '<br />' : '') + "E-mail: " + email + "",
html = $.parseHTML( str );
$('#signaturePreview').append(html);
If I comment out the IF (as I've commented out other tries I've made) and the ternary operator in the str var it works but NOTHING is displayed when trying to use a dynamic value (like the phone checkbox). There's only two methods there but I've tried many more. None of them work. Nothing is appended.
How can I do it? Thanks in advance!
showPhone = $('#showPhoneId').is(':checked');
surely that's all you need. It returns a boolean
$(document).ready(function() {
alert('Is Checked: ' + $('#showPhoneId')[0].checked);
console.log(typeof $('#showPhoneId')[0].checked);
console.log($('#showPhoneId')[0].checked === true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox">
<label>
<input type="checkbox" name="showInSignature[]" id="showPhoneId" value="showPhone" class="checkbox style-0" checked="checked">
<span>Teléfono</span>
</label>
</div>
In your code you are using assignment operator "=" which means
a = b (value of b is assigned to a),
in your case you are trying to assign true to $('#showPhoneId').is(':checked')
kindly"==" instead
var fname = $('#personalOptionsForm').find('[name="fname"]').val() ,
lname = $('#personalOptionsForm').find('[name="lname"]').val() ,
cellphone = $('#personalOptionsForm').find('[name="cellphone"]').val(),
email = $('#personalOptionsForm').find('[name="email"]').val(),
//dummy values
fname = 'abc', lname="dksjdn",
cellphone = "98989898", email = "abc#gmail.com";
if($('#showPhoneId').is(':checked') == true) {
showPhone = 1;
} else {
showPhone = 0;
};
// showPhone = (($('input[name="showInSignature[]"]').is(':checked') == true) ? 1 : 0),
// showEmail = (($('input[name="showInSignature[]"]').is(':checked') == true) ? 1 : 0),
str = "<strong>" + fname + " " + lname + "</strong><br /><br />" + ((showPhone == 1) ? 'Teléfono: ' + cellphone + '<br />' : '') + "E-mail: " + email + "",
html = $.parseHTML( str );
$('#signaturePreview').append(html);
please refer https://jsbin.com/rolodozode/1/edit?html,js,output
I want to generate target textbox value depends on another textbox value with following conditions -
Assumed First TextBox value - "myfile name"
If first textbox value not start with "Copy of " then target value will "Copy of [1] myfile name".
If first textbox value "Copy of [1] myfile name" then target value will "Copy of [2] myfile name".
If first textbox value "Copy of [2] myfile name" then target value will "Copy of [3] myfile name".
i.e increment of the no.
Here is my code sample
How do I do this using jquery?
HTML:
<div class="panel">
<input type="text" id="filename" value="filename">
</div>
<div class="panel">
<input type="text" id="newfilename" value="">
</div>
<div class="panel">
<button type="button" id="btnGenerate">
Get File Name
</button>
</div>
JS:
$('#btnGenerate').click(function(){
var newname;
var oldname = $('#filename').val();
if(typeof oldname !== undefined || oldname != ''){
if(oldname.indexOf('Copy of')){
var nCount = parseInt(oldname.match(/\([.*]\)/),10) + 1;
newname = "Copy of [" + nCount[1] + "] " + oldname;
$('#newfilename').val(newname);
}else{
newname = "Copy of [1] " + oldname'
}
$('#newfilename').val(newname);
}
});
Updated fiddle.
You're so close, you've just to adjust the regex a little bitand add else statement :
$('#btnGenerate').click(function(){
var oldname = $('#filename').val();
if(typeof oldname !== undefined || oldname != ''){
//Adding '>-1' in this condition
if(oldname.indexOf('Copy of')>-1)
{
var nCount = parseInt(oldname.match(/\[(.*)\]/)[1],10) + 1;
var file_name = oldname.split('] ')[1];
var newname = "Copy of [" + nCount + "] " + file_name;
}else{
var newname = 'Copy of [1] '+oldname;
}
$('#newfilename').val(newname);
}
});
Hope this helps.
$('#btnGenerate').click(function(){
var oldname = $('#filename').val();
if(typeof oldname !== undefined || oldname != ''){
if(oldname.indexOf('Copy of')>-1){
var nCount = parseInt(oldname.match(/\[(.*)\]/)[1],10) + 1;
var file_name = oldname.split('] ')[1];
var newname = "Copy of [" + nCount + "] " + file_name;
}else{
var newname = 'Copy of [1] '+oldname;
}
$('#newfilename').val(newname);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel">
<input type="text" id="filename" value="Copy of [1] filename">
</div>
<div class="panel">
<input type="text" id="newfilename" value="">
</div>
<div class="panel">
<button type="button" id="btnGenerate">
Get File Name
</button>
</div>
names = new Array()
$('#btnGenerate').click(function(){
var oldname = $('#filename').val();
names.push(oldname);
if(oldname != ''){
var nCount = $.grep(names, function (elem) {
return elem === oldname;
}).length;
var newname = "Copy of [" +nCount + "] " + oldname;
$('#newfilename').val(newname);
}
});
.panel{
display:block;
padding: 5px 10px;
}
.panel input{
width:100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel">
<input type="text" id="filename" value="Name">
</div>
<div class="panel">
<input type="text" id="newfilename" value="">
</div>
<div class="panel">
<button type="button" id="btnGenerate">
Get File Name
</button>
</div>
I hope this is what you are looking for.
Your code is working, but you have to change the regex from
/\([.*]\)/ to /\d+/
I've made the following adjustments to your code:
if(oldname.substr(0, 7) == "Copy of"){
var nCount = parseInt(oldname.match(/\[(\d+?)\]/)[1],10) + 1;
var newname = oldname.replace(/\[\d+?\]/, "["+nCount+"]");
$('#newfilename').val(newname);
}
else
{
$('#newfilename').val("Copy of [1] " + oldname); //prepend Copy of [1]
}
Look at oldname.substr(0, 7) == "Copy of" the former indexOf skipped the if, not executing the code.
now [(\d+?)\] does the magic. It takes out all numbers between [ and ] and groups them in (). \d+? means get all numbers that occur 1 or n times. ? makes it lazy so it stops at ].
var newname = oldname.replace(/\[\d+?\]/, "["+nCount+"]") simply do a replace on the [] block and replace it with nCount.
You can even optimize it using just a replace:
var newname = oldname.replace(/\[(\d+?)\]/, function(whole, group1){
return "[" + (parseInt(group1, 10)+1) + "]";
});
$('#btnGenerate').click(function(){
var oldname = $('#filename').val();
if(typeof oldname !== undefined || oldname != ''){
if(oldname.substr(0, 7) == "Copy of"){
var newname = oldname.replace(/\[(\d+?)\]/, function(whole, group1){
return "[" + (parseInt(group1, 10)+1) + "]";
});
$('#newfilename').val(newname);
}
else
{
$('#newfilename').val("Copy of [1] " + oldname); //prepend Copy of [1]
}
}
});
.panel{
display:block;
padding: 5px 10px;
}
.panel input{
width:100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel">
<input type="text" id="filename" value="Copy of [1] filename">
</div>
<div class="panel">
<input type="text" id="newfilename" value="">
</div>
<div class="panel">
<button type="button" id="btnGenerate">
Get File Name
</button>
</div>
On a whole different subject. You are building a filesystem kind of control. Wouldn't it be better that the copy amount is being determined by the amount of occurrences of that file name (and copies)?
I am building a form using JavaScript and HTML only (business need - no server access). I have a list of textboxes that I need the values from. The user has the option of either filling out 1 textbox, or as many as they need up to 35. I COULD create a function for each individual box
var a = $('#a').val();
var b = $('#b').val();
var c = $('#c').val();
if (a != '' && b != '' && c != '') {
var abc = "this is a: " + a + "this is b: " + b + "and this is c:" + c;
}
and I could make a function for each scenario of each value:
if(a != '' && b != '' && c == '') {
var ab = "this is a: " + a + " and b: " + b + "but not c";
}
if(a != '' && b == '' && c != '') {
var ac = "this is a: " + a + " and c: " + c + "but not b";
}
if(a != '' && b == '' && c == '') {
var a-only = "this is a: " + a + " but not b or c";
}
if(a == '' && b != '' && c != '') {
var bc = "this is b: " + b + " and c: " + c + " but not a";
}
That's not even every scenario for just 3 variables, but I could potentially have up to 35 different variables that I need to make a function for each scenario which is a huge chunk of time and space and I think after about 10 of them, it will get too messy and hard to maintain later if I need let alone all 35.
I feel like there must be a far more efficient way of capturing the values and displaying them if they are not empty other than going through each possible scenario.
My textboxes are dynamically created by clicking an "Add More" button
JavaScript:
var max_fields = 35;
var x = 0;
$('#add').click(function(e) {
e.preventDefault();
if(x < max_fields){
x++;
var inps = $('#wrapper >div:last').data('count')+1 || 1;
$('#wrapper').append('<div class="date-time-list" data-count="'+inps+'"><input type="text" name="date_count' + inps + '" id="date_count'+inps+'" class="inp"/><input type="text" name="time_count' + inps + '" id="time_count'+inps+'" class="inp"/><a class=remove>Remove</a><br><br></div>');
}
});
$('#wrapper').on('click' , 'a.remove' ,function(){
var inps = $('#wrapper > div:last').data('count')-1 || 1;
x--;
$(this).closest('div').remove();
});
HTML:
<tr class="list" style="line-height:1em;">
<td>
Please fill in the dates and times
</td>
<td>
<strong>Dates</strong> <strong>Times</strong>
</td>
</tr>
<tr class="list" style="line-height:1em;">
<td>
</td>
<td>
<span id="wrapper">
</span>
</td>
</tr>
<tr class="list">
<td>
</td>
<td>
<button id="add">Add More</button>
</td>
</tr>
Please have a look at this little snippet: https://jsfiddle.net/0h52y0Ly/1/
$( document ).ready(function() {
$('button').click(function(){
var content = '';
var countOfTextareasFilled = 0;
$('textarea').each(function(){
if ($(this).val().length){
content += $(this).val() + '\n\n';
countOfTextareasFilled++;
}
});
alert(countOfTextareasFilled + ' text boxes have been filled. Contents are:\n\n' +content);
});
});
It shows a very generic approach to your task. You should be able to adapt it to your needs very easily.
EDIT:
I am fairly certain, that adapting a perfectly functioning generalized solution to your special use case, is something you should do yourself. But here it is:
https://jsfiddle.net/cb7ujmsw/
$('#evaluate').click(function(){
var content = '';
var data = [];
var dateField, timeField;
$('.date-time-list').each(function(){
dateField = $('#date_count' + $(this).data('count'));
timeField = $('#time_count' + $(this).data('count'));
if (dateField.val().length && timeField.val().length){
data.push({
date: dateField.val(),
time: timeField.val()
});
}
});
alert(data.length + ' complete datetimes. Data:\n\n' +JSON.stringify(data));
});
I added a button with the ID "evaluate". The rest is completely your code.
Assuming you have a way to select all relevant inputs (in this example all elements have the check-me class)
$(function(){
$('.do-the-check').on('click', function(e){
e.preventDefault();
var inputs = $('.check-me', this.form),
empty = inputs.filter(function(){return this.value === ''}),
nonempty = inputs.not(empty),
message = 'This is ';
if (nonempty.length){
message += nonempty.map(function(){return this.name + ':' + this.value}).get().join(' and ');
}
if (empty.length){
if (nonempty.length){
message += ' but ';
}
message += 'not ' + empty.map(function(){return this.name;}).get().join(' or ');
}
alert(message);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
a:<input name="a" class="check-me"><br/>
b:<input name="b" class="check-me"><br/>
c:<input name="c" class="check-me"><br/>
d:<input name="d" class="check-me"><br/>
e:<input name="e" class="check-me"><br/>
f:<input name="f" class="check-me"><br/>
g:<input name="g" class="check-me"><br/>
h:<input name="h" class="check-me"><br/>
i:<input name="i" class="check-me"><br/>
j:<input name="j" class="check-me"><br/>
<button class="do-the-check">check them</button>
</form>
I'm trying to learn Javascript and I feel like I have a decent grasp on the fundamentals but I am having problems making it do things that i want .. for example.. I am trying to create a simple form in html that calculates the sum of 2 numbers.. here is my html and javascript:
<head>
<script type="text/javascript">
function adder(a,b) {
var a = document.getElementById('firstNum').value;
var b = document.getElementById('secondNum').value;
var numbers = new Array(a,b);
var sum = 0;
for (i=0; i < numbers.length; i++) {
sum += parseInt(numbers[i]);
}
//this part i need help with
document.getElementById('answer').write("First Number: " + a + " plus Second Number: " + b + " is " + sum).value; //this part i need help with
</script>
</head>
<body>
<form id="additionForm">
A + B = C : <input type="text" id="firstNum" placeholder="A">
+ <input type="text" id="secondNum" placeholder="B">
<input type="button" id="addBtn" value="Add" onClick="adder();">
= <input type="text" id="answer" placeholder="C">
</form>
</body>
My problem is that i don't know how to get the javascript to overwrite the value attribute for my form input id=answer .. or if i'm supposed to be using Jquery instead .. thanks in advance.
function adder() {
var a = parseInt( document.getElementById('firstNum').value, 10);
var b = parseInt( document.getElementById('secondNum').value, 10);
var sum = a + b;
//this part i need help with
document.getElementById('answer').value = "First Number: " + a + " plus Second Number: " + b + " is " + sum).value; //this part i need help with
}
If you want to modify an input field in javascript, you can simply set the value attribute:
document.getElementById('answer').value = "First Number: " + a + " plus Second Number: " + b + " is " + sum;