I have found the code below, that automatically adds '/' to an input with a date. I was wondering if there was a way instead of adding a '/' I could add a '-'? I am not very good with javascript and would appreciate any help.
<input id="dob" type="text" onkeyup="getAge()" />
<script type="text/javascript">
function getAge() {
document.getElementById("dob").value=document.getElementById("dob").value.replace(/^(\d\d)(\d)$/g,'$1/$2').replace(/^(\d\d\/\d\d)(\d+)$/g,'$1/$2').replace(/[^\d\/]/g,'');
</script>
This might be what you are looking for. I made the following adjustments to your original code:
used a variable to call the "dob" element to save lines of code
added event listener because that is preferable to declaring it in your HTML (so say the fancy developers)
changed "keyup" event to be "keydown", because I think it is more reliable
added maxlength to the input so that user cannot add more digits than a date should have
added placeholder to the input so user will know what format they should be able to enter
changed your RegEx to search for - instead of /
N.B. I have not added error checking to make sure user entered a "real" date (i.e. "02-31-2018") would not be caught.
var dob = document.getElementById("dob");
dob.addEventListener("keydown", getAge);
function getAge() {
dob.value = dob.value.replace(/^(\d\d)(\d)$/g,"$1-$2").replace(/^(\d\d\-\d\d)(\d+)$/g,"$1-$2").replace(/[^\d\-]/g,'');
}
<input id="dob" maxlength="10" placeholder="mm-dd-yyyy" type="text" />
Related
So this is probably an easy one, but I'm just not doing it right. My goal is to send the user input from this textbox:
<input type='text' placeholder='Form Name...' id='formNameInput' required>
Into this Div:
<div id="code_output"></div>
I'm trying to make it appear in real time, and so far I used this to try and do so, but it doesn't work:
document.getElementById("code_output").innerHTML += document.getElementById("formNameInput").value;
Why doesn't it show? Does my code need something to trigger the Javascript?
You're close, but the issue is that you're not using an event handler. The script is executing your code once, as soon as possible (before you have the chance to enter anything into the text input). So, you have to add some sort of event listener so that the copying happens at the appropriate time. Something like below:
document.getElementById('formNameInput').addEventListener('keyup', copyToDiv);
function copyToDiv() {
document.getElementById("code_output").innerHTML = document.getElementById("formNameInput").value;
}
<input type='text' placeholder='Form Name...' id='formNameInput' required>
<div id="code_output"></div>
You need to do that whenever the value of formNameInput changes. For that you need an event.
Your code should look like:
document.getElementById("formNameInput").addEventListener('input', function () {
document.getElementById("code_output").innerHTML += this.value;
});
function change() {
document.getElementById("code_output").innerHTML = document.getElementById("formNameInput").value;
}
document.getElementById('formNameInput').onkeyup = change
maybe this is what you are trying?
You need to attach an event listener to your input that executes a function any time an input event occurs on the field:
formNameInput.addEventListener('input', function(e) {
code_output.textContent = e.target.value
})
<input type="text" placeholder="Form Name..." id="formNameInput" required />
<div id="code_output"></div>
Please note that the above code takes advantage of the fact that browsers automatically create a global variable for each element with a unique id attribute value, and this variable has the same name as the value of the id.
If the concept of events is new to you, this might be a good place to get started:
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events
I have a
<input id="TxtBox" runat="server" autocomplete="off" onkeypress="">
And while doing the keypress, directly with js code, it replaces all the characters for '*'. Like a password typing.
Edit: 2022
As i read this old question i found imprecision why i wanted to avoid type="password" at that time. It was because if that attribute were in the tag the browser would remind a old password and it was annoying.
Edit:
I passed all day trying do put the autocomplete=off on all of my inputs to the browser stop asking password while someone is filling a form on my site, ddnt worked(a tried a few more things). And i thought in this type of solution i tried the javascript replace function but it only returned one char and decided to ask about a complete sequence of '*' while writing in a input. Tks for all the help.
sorry if i wasnt clear in the context i was just thinking in the code. i thought in some old i did before in C language but anyway i asked.
Edit:
I asked help how to do this in JS i did some stuff on keypress with JS functions like replace i did some code but i simply erased it and asked for some help. Next time i will post code to have some kick start code. I was doing something like
onkeypress="this.value=this.replace(this.value,'*')"
Tks in advance.
This is for in a visible input see a password typing and in a hidden i have it.
note: i want to avoid type="password"
Why do you need JavaScript to accomplish what HTML gives your for free? The element exposes all the same attributes/properties so you can still use it like a text box.
<input type="password">
If you feel you must reinvent the wheel, this can be done by using two fields. The user will type in the first and it will display the mask character and the actual key will be stored in a hidden input field for processing:
// Get references to DOM elements:
var txt = document.getElementById("txtMask");
var hdn = document.getElementById("pass");
// This keeps track of how many characters should be displayed
var maskLen = 1;
// Set up input event on first box
txt.addEventListener("keydown", function(evt){
// Manually put the right amount of mask characters into the box
// and update the maskLen value
var str = '#'.repeat(maskLen++)
this.value = str;
// Cancel the event and stop bubbling
evt.preventDefault();
evt.stopPropagation();
// Set the actual typed data into the hidden field
hdn.value += evt.key;
// Just for testing:
console.clear();
console.log("Actual data is: " + hdn.value);
});
<input type="text" id="txtMask" autocomplete="false">
<input type="hidden" id="pass">
Use type="password"
Like this:
<input type="password" id="TxtBox" runat="server" autocomplete="off" onkeypress="">
You can also do one of these:
input { -webkit-text-security: none; }
input { -webkit-text-security: circle; }
input { -webkit-text-security: square; }
input { -webkit-text-security: disc; /* Default */ }
You can use those without having a type="password"
I need to send a form off to where a single hidden field is comprised of two of the other fields that will be dynamically populated by a user (post/zip code and first line of address) where after regular expression only the numbers remain "123|456".
I have attempted to start, using the code below, where I monitor the output in the console. I have managed to dynamically edit a textfield so that all that is shown are the numbers but this is not suitable for a user. So I was trying to store the edited textfield data into the hidden field whilst leaving the complete line of address but I could not see how this can be done.
Also, can someone explain why if I remove the commented line the variable is not stripped of any letters albeit just 1?
$(document).ready(function() {
$("#testMe").on('propertychange change click keyup input paste', function() //attaching multiple handlers
{
var removedText = $("#testMe").val().replace(/\D/, '');
$("#testMe").val(removedText); //only removes once if removed
console.log(removedText);
}
);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="hidden" id="hide" value="">
<input type="text" id="testMe" value="">
<span id="test2"></span>
The question was kind of unclear to me, but I did my best to answer.
https://jsfiddle.net/ccu6j6xu/
<input type="hidden" id="hide" value="">
<input type="text" id="zip" value="">
<input type="text" id="address" value="">
<span id="test2"></span>
In the HTML, all I did was add another input, because I think that's what you wanted to do?
$(document).ready(function() {
$("#zip, #address").on('propertychange change click keyup input paste', function() {
var concatText = $("#zip").val().replace(/\D/g, '') + "|" + $("#address").val().replace(/\D/g, '');
$("#test2").text(concatText);
$("#hide").val(concatText);
});
});
Then in the JavaScript, I changed the selector to match the new inputs, and then I changed the function.
The first line of this function defines a variable concatText to hold the values of each input concatenated with a | character between. Each one has regex applied to remove the letters for the final value. Then the next line changes the value of the span to display, and the final line applies this value to the hidden input.
Again, the question was kind of confusing to me, but feel free to comment and I can help some more :)
EDIT: reread the question, I think this better answers
I know it's simple and there's probably something wrong with my syntax but I just don't understated it. I'm talking about the following:
//declaration of a string
var str_input = "";
//this is supposed to get the new inputs and to store them in str_input
$(document).ready(function(){
str_input = $('input[name=po]').val();
});
//this is on html side, this should make an input field where the user to type in the needed
<input type"text" name = 'po' id="po" value="asd">
That's it, can you help me to sort it out? The problem so far is that str_input is undefined regardless of what is written in the input, though, it saves its initial value.
Your html tag is invalid:
<input type"text" name = 'po' id="po" value="asd">
Should be:
<input type="text" name = 'po' id="po" value="asd">
// ^ Missing this character (=)
Ok, Now I understood, you can do 2 things, first, you can create a button than when the user clicks it calls the function to store the value in the variable like this:
var str_input = "";
//this is supposed to get the new inputs and to store them in str_input
$(document).ready(function(){
$("#MyButton").click(function(){
str_input = $('input[name=po]').val();
})
});
//this is on html side, this should make an input field where the user to type in the needed
<input type"text" name = 'po' id="po" value="asd">
<input type="button" id="MyButton" value="Click Here" />
Or the blur function when the user lose focus of the input text like this:
var str_input = "";
//this is supposed to get the new inputs and to store them in str_input
$(document).ready(function(){
$('input[name=po]').blur(function(){
str_input = $('input[name=po]').val();
})
});
//this is on html side, this should make an input field where the user to type in the needed
<input type"text" name = 'po' id="po" value="asd">
Ok, so here is the solution, though it's a little bit in "from Alf to Alf" style. So, yes, the code I've posted in the main post uses correctly the 'by default' value of the input but the problem comes from that nothing is checking for further changes in the input text field. I'm using $(document).ready... which as far as I know runs during the web project is opened and of course enables the use of some jquery methods within it. There is an interesting function called .change() which actually put the whole thing up for me. Take a glance at the following:
$(document).ready(function(){
$('input[type="text"]').change(function(){
str_input = $('input[name=polynom]').val();;
});
str_input = $('input[name=polynom]').val();
});
The second, third and fourth line make the magic actually, where the code in the .change() method updates str_input on each time a change have appeared in the input box field, whereas the str_input = $('input[name=polynom]').val(); outside of change() takes into account the initial value of the input. That's it... I knew I was forgetting something and yeah...
P.S. Another approach is to use a function and a button (a.k.a. an event-triggered function) which to 'update' the str_input on event. For this way check the post bellow this one.
I need to clear the default values from input fields using js, but all of my attempts so far have failed to target and clear the fields. I was hoping to use onSubmit to excute a function to clear all default values (if the user has not changed them) before the form is submitted.
<form method='get' class='custom_search widget custom_search_custom_fields__search' onSubmit='clearDefaults' action='http://www.example.com' >
<input name='cs-Price-2' id='cs-Price-2' class='short_form' value='Min. Price' />
<input name='cs-Price-3' id='cs-Price-3' class='short_form' value='Max Price' />
<input type='submit' name='search' class='formbutton' value=''/>
</form>
How would you accomplish this?
Read the ids+values of all your fields when the page first loads (using something like jquery to get all "textarea", "input" and "select" tags for example)
On submit, compare the now contained values to what you stored on loading the page
Replace the ones that have not changed with empty values
If it's still unclear, describe where you're getting stuck and I'll describe more in depth.
Edit: Adding some code, using jQuery. It's only for the textarea-tag and it doesn't respond to the actual events, but hopefully it explains the idea further:
// Keep default values here
var defaults = {};
// Run something like this on load
$('textarea').each(function(i, e) {
defaults[$(e).attr('id')] = $(e).text();
});
// Run something like this before submit
$('textarea').each(function(i, e){
if (defaults[$(e).attr('id')] === $(e).text())
$(e).text('');
})
Edit: Adding some more code for more detailed help. This should be somewhat complete code (with a quality disclaimer since I'm by no means a jQuery expert) and just requires to be included on your page. Nothing else has to be done, except giving all your input tags unique ids and type="text" (but they should have that anyway):
$(document).ready(function(){
// Default values will live here
var defaults = {};
// This reads and stores all text input defaults for later use
$('input[type=text]').each(function(){
defaults[$(this).attr('id')] = $(this).text();
});
// For each of your submit buttons,
// add an event handler for the submit event
// that finds all text inputs and clears the ones not changed
$('input[type=submit]').each(function(){
$(this).submit(function(){
$('input[type=text]').each(function(){
if (defaults[$(this).attr('id')] === $(this).text())
$(this).text('');
});
});
});
});
If this still doesn't make any sense, you should read some tutorials about jQuery and/or javascript.
Note: This is currently only supported in Google Chrome and Safari. I do not expect this to be a satisfactory answer to your problem, but I think it should be noted how this problem can be tackled in HTML 5.
HTML 5 introduced the placeholder attribute, which does not get submitted unless it was replaced:
<form>
<input name="q" placeholder="Search Bookmarks and History">
<input type="submit" value="Search">
</form>
Further reading:
DiveintoHTML5.ep.io: Live Example... And checking if the placeholder tag is supported
DiveintoHTML5.ep.io: Placeholder text
1) Instead of checking for changes on the client side you can check for the changes on the client side.
In the Page_Init function you will have values stored in the viewstate & the values in the text fields or whichever controls you are using.
You can compare the values and if they are not equal then set the Text to blank.
2) May I ask, what functionality are you trying to achieve ?
U can achieve it by using this in your submit function
function clearDefaults()
{
if(document.getElementById('cs-Price-2').value=="Min. Price")
{
document.getElementById('cs-Price-2').value='';
}
}