How to apply masking in a textbox - javascript

I have a grid in which there is a textbox that is currently accepting numeric numbers. However I want to apply masking in that textbox using javascript or jquery without any plugin.
I have searched and everywhere they are asking for plug-in.
I tried this solution but it does not work my default value should be 00000-00-000
$("input[name='masknumber']").on("keyup change", function(){
this.value = createMask($("input[name='masknumber']").val());
})
function createMask(string){
return string.replace(/(\d{2})(\d{3})(\d{2})/,"$1-$2-$3");
}
Any help would be appreciated.

Add a hidden input which will store original value without masking.
Html:
<input type="text" value="0000000000" id="masknumber">
<input type="text" id="numberWithoutMask" style="display:none;" value="0000000000">
JS:
// call function on change
$("#maskNumber").on("keyup change", function () {
updateValue();
})
// function to update the value with masking
function updateValue() {
$("#numberWithoutMask").val(destroyMask($("#maskNumber").val()));
$("#maskNumber").val(createMask($("#numberWithoutMask").val()))
}
function createMask(string) {
return string.replace(/(\d{5})(\d{2})(\d{3})/, "$1-$2-$3");
}
function destroyMask(string) {
return string.replace(/\D/g, '').substring(0, 10);
}
updateValue(); // call function to update the default value
If you're loading default value, load value to both the inputs.

Related

get value from an input with datedropper js in the onchange event

I'm using the js library from datedropper, but when I want to get its value, when it changes value, no value returns, I don't know what is the correct way to do it
<input id="my-timepicker"type="text" data-lang='es' data-large-mode="true" data-large-default="true">
$(document).ready(function () {
$("#my-timepicker").dateDropper();
$("#my-timepicker").change(function () {
console.log($(this).val());
});
});

Clear input, textarea on blur and default if field is blank

I am trying to clear two input fields with classes assigned, and one textarea with a class assigned of their default values on blur and return it to default only if the field is blank when the field is exited. If the user has included their own text I require that to stay.
This is what I have thus far:
$("input, textarea").focus(function() {
this.value = "";
});
$(".namefield").on("blur", function() {
$(this).val("Name");
});
$(".emailfield").on("blur", function() {
$(this).val("Email");
});
$(".messagefield").on("blur", function() {
$(this).val("Message");
});
First a quick note, the HTML placeholder attribute will do exactly what you describe natively. I'd encourage that as a first choice if possible. The implementation would simply be:
<input type="text" class="namefield" placeholder="Name" />
More reading on it is here: http://www.w3schools.com/tags/att_input_placeholder.asp
If you can't add attributes to the elements, but you have the value set, you can add the attributes dynamically using jQuery. You could use the jQuery method we talked about originally, or you could just add the placeholder attribute.
Here are both examples, I've also updated the JS Fiddle with a working example.
Using Placeholder
$(document).ready(function() {
$("input, textarea").each(function() {
$(this).attr('placeholder',$(this).val());
$(this).val('');
})
})
Using data-default in conjunction with the original answer
$(document).ready(function() {
$("input, textarea").each(function() {
$(this).data('default',$(this).val());
})
})
Original Answer:
If you still need to use jQuery, you can set and check the state and compare it against a default value. Something like this would work:
HTML
<input type="text" class="namefield" data-default="Name" value="Name" />
<input type="text" class="emailfield" data-default="Email" value="Email" />
JavaScript
$(document).ready(function() {
$("input, textarea").focus(function() {
if($(this).data('default') == $(this).val()) {
$(this).val('');
}
});
$("input, textarea").blur(function() {
if($(this).val() == '') {
$(this).val($(this).data('default'));
}
});
})
You can see it working in this JS Fiddle: https://jsfiddle.net/77Lk4kep/1/
Hope that helps!

How to not clear textarea value when searching with Javascript onsearch Event

I'm using this method http://www.w3schools.com/jsref/event_onsearch.asp
What I want is the text that I searched with to stay in the textarea or at least get back to the textarea, not disappear because I click the enter button.
I understand that it clears the text because in the link they describe the function like this: "The onsearch event occurs when a user presses the "ENTER" key or clicks the "x" button in an element with type="search".
So it acts as if I click the x button, although, there must be a way to get the text back there after?
This is my current code html code
<form> <input type="search" name="search" id="searchid" onsearch="OnSearch(this)"/> </form>
This is my javasript/jquery
function OnSearch(input) {
alert("The current value of the search field is " + input.value);
$("#searchid").val(input.value);
}
What happens now is that it correctly alerts the value the textarea is holding, although it wont add back the textarea value.
EDIT: It seems like the page reloads, how can i insert code that runs after page reload?
Well I have an alternative. Since you cannot avoid the clear functionality you can store the text each time keypressed in a global variable and if x is pressed retain the value in textbox. Below is the code:
DEMO HERE
var text="";
function OnSearch(input) {
if(input.value == "") {
$("#searchid").val(text);
}
else {
alert("You searched for " + input.value);
}
}
$(document).on('keyup','#searchid', function (e) {
text=$(this).val();
console.log(text);
});
UPDATE
if your html is inside the form you can do as below:
Check in document.ready if it already had a text and if yes set it!!
$(document).ready(function()
{
if(localStorage.getItem("text")!="")
{
$("#searchid").val(localStorage.getItem("text"));
}
});
function OnSearch(input) {
if(input.value == "") {
$("#searchid").val(localStorage.getItem("text"));
}
else {
alert("You searched for " + input.value);
}
}
$(document).on('keyup','#searchid', function (e) {
localStorage.setItem("text",$(this).val());
});
I think this will help you to display the alert dialog symbol as that:
HTML:
<input type="search" name="search" id="searchid"/>
Javascript:
document.getElementById("searchid").onsearch = function() {yourfunctionname()};
/* Put this before the below function or in the top of the document */
function yourfunctionname(){
var x = document.getElementById("searchid").value;
alert("The current value of the search field is "+x);
/* Or do what ever you wish */
}
/*Remember to replace the yourfunctionname with your function's name */
OR If it is in a form try this:
Your form should look like this:
<form method="/* method */" action="/* action */" onSubmit="yourfunctionname()">
<input type="search" name="search" id="searchid"/>
/* Rest of your form*/
</form>
Javascript:
document.getElementById("searchid").value = localStorage.getItem("saved");
document.getElementById("searchid").onsearch = function() {yourfunctionname()};
/* Put this before the below function or in the top of the document */
function yourfunctionname(){
var x = document.getElementById("searchid").value;
alert("The current value of the search field is "+x);
/* Or do what ever you wish */
/* The below code does the trick*/
localStorage.setItem("saved", x);
location.reload();
return false;
}
/* Remember to replace the yourfunctionname with your function's name */
If you are having a different function to submit the form then replace your form's onsubmit attribute with that function's name and a word "return" before it's name and add the below javascript inside that function.
var x = document.getElementById("searchid").value
localStorage.setItem("saved", x);
location.reload();
return false;
If you wanted something else then please comment.
Please accept as if it solves your problem.
And thanks...
Lastly for more just comment

Need to run a function based on conditional

I'm trying to assign a function to a couple of checkboxes, but I only want them added based on a condition, in this case the step number of the form. This is a roundabout way of making the checkboxes readOnly AFTER they have been selected (or not). So, at step 1 I want the user to choose cb1 or cb2, but at step 2 I want to assign the function that will not let the checkboxes values be changed.
What am I doing wrong?
function functionOne() {
this.checked = !this.checked
};
if (document.getElementById("stepNumber").value == 2) {
document.getElementById("cb1").setAttribute("onkeydown", "functionOne(this)");
document.getElementById("cb2").setAttribute("onkeydown", "functionOne(this)");
}
You are passing the element in an argument, so use that:
function functionOne(elem) {
elem.checked = !elem.checked
};
You could also use properties:
document.getElementById("cb1").onkeydown = functionOne;
document.getElementById("cb2").onkeydown = functionOne;
function functionOne() {
this.checked = !this.checked
};
This is a solution that requires jquery but you can use the .click function to disable checkboxes once one is clicked.
Here is a working example:
http://jsfiddle.net/uPsm7/
Why not on the selection disable the checkbox?
Function onCheck(elm)
{
document.getElementById("cbValue").value = elm.value;
elm.disabled = true;
}
<input id="cbValue" type="hidden" />
Use the hidden input field to allow form to send data back to server.

Change an element's onfocus handler with Javascript?

I have a form that has default values describing what should go into the field (replacing a label). When the user focuses a field this function is called:
function clear_input(element)
{
element.value = "";
element.onfocus = null;
}
The onfocus is set to null so that if the user puts something in the field and decides to change it, their input is not erased (so it is only erased once). Now, if the user moves on to the next field without entering any data, then the default value is restored with this function (called onblur):
function restore_default(element)
{
if(element.value == '')
{
element.value = element.name.substring(0, 1).toUpperCase()
+ element.name.substring(1, element.name.length);
}
}
It just so happened that the default values were the names of the elements so instead of adding an ID, I just manipulated the name property. The problem is that if they do skip over the element then the onfocus event is nullified with clear_input but then never restored.
I added
element.onfocus = "javascript:clear_input(this);";
In restore_default function but that doesn't work. How do I do this?
Use
element.onfocus = clear_input;
or (with parameters)
element.onfocus = function () {
clear_input( param, param2 );
};
with
function clear_input () {
this.value = "";
this.onfocus = null;
}
The "javascript:" bit is unnecessary.
It looks like you don't allow the fields to be empty, but what if the user puts a single or more spaces in the field? If you want to prevent this, you need to trim it. (See Steven Levithans blog for different ways to trim).
function trim(str) {
return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
If you really want to capitalize the strings you could use:
function capitalize(str) {
return str.substr(0, 1).toUpperCase() + str.substr(1).toLowerCase();
}
By clearing the onfocus event you have created a problem that should not have been there. An easier solution is to just add an if-statement to the onfocus event, so it only clears if it is your default value (but I prefer to select it like tvanfosson suggested).
I assume that you on your input-elements have set the value-property so that a value is shown in the input-elements when the page is displayed even if javascript is disabled. That value is available as element.defaultValue. Bonuses by using this approach:
You only define the default value in one place.
You no longer need to capitalize any value in your handlers.
The default value can have any case (like "John Y McMain")
The default value no longer needs to be the same as the name of the element.
.
function clear_default(element) {
if (trim(element.value) == element.defaultValue ) { element.value = ""; }
}
function restore_default(element) {
if (!trim(element.value).length) { element.value = element.defaultValue;}
}
I would suggest that you handle it a little differently. Instead of clearing the value, why not just highlight it all so that the user can just start typing to overwrite it. Then you don't need to restore the default value (although you could still do so and in the same way if the value is empty). You also can leave the handler in place since the text is not cleared, just highlighted. Use validation to make sure the value is not the original value of the input.
function hightlight_input(element) {
element.select();
}
function restore_default(element) // optional, do we restore if the user deletes?
{
if(element.value == '')
{
element.value = element.name.substring(0, 1).toUpperCase()
+ element.name.substring(1, element.name.length);
}
}
<!-- JavaScript
function checkClear(A,B){if(arguments[2]){A=arguments[1];B=arguments[2]} if(A.value==B){A.value=""} else if(A.value==""){A.value="Search"}}
//-->
<form method="post" action="search.php">
<input type="submit" name="1">
<input type="text" name="srh" Value="Search" onfocus="checkClear(this,'Search')" onblur="checkClear(this,' ')">
</form>

Categories

Resources