Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
If I enter 0900 in this text field then I would like it to automatically turn into 09:00
form
<form action="form.html">
<p>
<label>time:</label>
<input type="text" name="time" class="time"/>
</p>
<span id="error" class="hide">Error in the field</span>
</form>
I Know I should use the following to at least get the value and then I have to turn that value into the value that I want:
$(document).ready(function(){
$(".time").on("focusout",function(){
var old_value = $(this).val();
// The old value to the new value
if(old_value.length < 2 || > 4){
$("#error").show();
} else {
if(old_value.length == 2){
// Then add 2 leading zero's
// Then add a : in the middle
} else if (old_value.length == 3){
// Then add 1 leading zero's
// Then add a : in the middle
} else if (old_value.length == 4){
// Then add a : in the middle
}
}
}
Thanks in advance for the effort taken. If something isn't clear please ask me.
Use this as a basis to solve your problem:
$("#your_filed_id").on("focusout", function(){
// Do whatever checking you like here
});
You can do like this:
JsFiddle: http://jsfiddle.net/ha9kx/1/
HTML:
<form action="demo_form.html">
<p>
<label>Hour:</label>
<input type="text" name="hour" class="hour_modification"/>
</p>
<span id="error" class="hide">Error in the field</span>
</form>
JavaScript:
$(document).ready(function(){
$(".hour_modification").on("focusout",function(){
var old_val = $(this).val();
if (old_val.length > 4 || old_val.length < 3){
$("#error").show();
}
else{
if(old_val.length = 3){old_val = "0" + old_val;}
var new_val = old_val.substring(0,old_val.length-2) + ":" + old_val.substring(old_val.length-2);
$(this).val(new_val);
}
});
});
This solution will work even if the user put "300" for "03:00"
If the entered value is always going to be 4 characters in the format you specified above, the following code should work. I don't use jQuery that often, but the following should give you an idea of what is required. You can modify the event listener with jQuery along with the selector.
http://jsfiddle.net/DS92Z/
<input type="text" id="time" />
<script>
var input = document.getElementById('time');
input.addEventListener('blur',function(e) {
var target = e.target || e.srcElement;
var value = target.value;
if(value.length != 4) {
return false;
}
target.value = value[0]+value[1]+':'+value[2]+value[3];
},false);
</script>
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I need to validate a part of my form which is the postcode based on Malaysia's postcode which is a 5 digit numeric postcode. How to validate a value enter by user which has exactly 5 numbers only no more and no less? Thanks in advance!
Here's my part of the code:
HTML:
<label>Postcode: <input type="text" name="postcode" id="postcode" required="required"></label><br />
Javascript:
function chkPostcode () {
var postcode = document.getElementById("postcode").value;
var pattern = /^[0-9]+$/; //check only alpha characters or space
var postcodeOK = true;
if ((postcode.length < 5 && postcode.length > 5)){ //same as owner==""
gErrorMsg = gErrorMsg + "Please enter postcode.\n"
postcodeOK = false; //if condition or clause complex more readable if branches on separate lines
}
else{
if (!pattern.test(postcode)){
gErrorMsg = gErrorMsg + "Postcode must only contain numbers.\n"
postcodeOK = false; //if condition or clause complex more readable if branches on separate lines
}
}
//if (!nameOk){
// document.getElementById("owner").style.borderColor = "red";
//
return postcodeOK;
}
This is a much shorter code for what you're trying to accomplish.
document.getElementById("postcode").addEventListener("input", function(e) {
if ( /^\d{5}$/.test(e.target.value)){
console.log("valid");
return;
}
console.log("invalid");
})
<label>Postcode: <input type="text" name="postcode" id="postcode" required="required"></label><br />
Your JavaScript is unnecessarily complicated. Here's a sure (and much better) way (except for all the ifs) to do this (the button and the check function are just for demo purposes):
function chkPostcode() {
var postcode = document.getElementById("postcode").value;
if(postcode.length !== 5)
{
return false;
}
else {
if(!isNaN(parseInt(postcode.charAt(0)))) {
if(!isNaN(parseInt(postcode.charAt(1)))) {
if(!isNaN(parseInt(postcode.charAt(2)))) {
if(!isNaN(parseInt(postcode.charAt(3)))) {
if(!isNaN(parseInt(postcode.charAt(4)))) {
return true;
}
}
}
}
}
}
return false;
}
function check() {
if(chkPostcode()) alert("Valid!");
else alert("Not a postcode");
}
<input type="text" id="postcode" />
<button onclick="check()">Check</button>
Just keep in mind, although client side (JavaScript) validation scripts are helpful, it's easy to defeat client-side JavaScript. Make sure you make some validation on the server-side as well, where the client can't tamper with the code as easily.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have a page full of random stuff and into those things I have a random number generator. I tried it but the result is higher than expected, somebody knows what? Here is my code:
<div>
<h2>Get a random number</h2>
<br>
<input type="text" id="inputMin" placeholder="Min" required autocomplete="off">
<input type="text" id="inputMax" placeholder="Max" required autocomplete="off">
<br><br>
<button id="randomNumberButton">Generate</button>
<br>
<span class="error" id="randomNumberError"></span>
<span id="randomNumberResult"></span>
</div>
And the JavaScript:
try {
var randomNumberError = document.getElementById("randomNumberError")
const randomNumberButton = document.getElementById("randomNumberButton")
function getRandomNumber2(){
var inputMin = document.getElementById("inputMin")
var inputMax = document.getElementById("inputMax")
const selector = getRandomNumber(inputMin.value, inputMax.value)
console.log(inputMin.value, inputMax.value, selector);
const result = document.getElementById("randomNumberResult")
function removeRandomNumberError(){
randomNumberError.textContent = ""
}
if (inputMin.value == "" || inputMax.value == ""){
randomNumberError.textContent = "Both fields are required."
inputMin.addEventListener("click", removeRandomNumberError)
inputMax.addEventListener("click", removeRandomNumberError)
return
}
if(isNaN(inputMin.value) || isNaN(inputMax.value)){
randomNumberError.textContent = "Both values should be numbers"
inputMin.addEventListener("click", removeRandomNumberError)
inputMax.addEventListener("click", removeRandomNumberError)
return
}
result.textContent = selector
}
randomNumberButton.addEventListener("click", getRandomNumber2)
} catch (err){
randomNumberError.textContent = err
}
I would really appreciate if someone
You can try this solution (working as I understood to your question):
html code (only changed input type to number)
<input type="number" id="inputMin" placeholder="Min" required autocomplete="off">
<input type="number" id="inputMax" placeholder="Max" required autocomplete="off">
and js code is:
var button = document.getElementById('randomNumberButton');
var result = document.getElementById('randomNumberResult');
button.addEventListener('click', function() {
var min = parseInt(document.getElementById('inputMin').value);
var max = parseInt(document.getElementById('inputMax').value);
result.value = Math.floor(Math.random() * max) + min;
alert(result.value);
});
I have a phone number input that I am trying to get the dashes to appear in the number as the user types.
I am wanting the number to appear as 555-555-5555.
The function works for the most part, but the dashes aren't entered until after the whole number is entered. I am using the keyup function, which I thought would solve this, but no luck.
Does anyone have any recommendations as to what I have to do to get the dashes to be entered as the user types in the digits?
$('#phone').keyup(function() {
$(this).val($(this).val().replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<label class="contact-label">Phone Number:</label>
<input type="tel" class="contact_input" name="phone" id="phone">
</div>
I modified your code slightly to produce something that I think is a little easier to read, but still does the job.
I just evaluated the length of the <input /> tag's value on each .keyup() event and then augmented the value accordingly. Take a look at the snippet below:
--UPDATE--
After comments regarding backspacing issues I added a couple lines of code that seem to fix the issue:
First I checked for either backspace or delete .keyup() events to prevent the formatting code from interfering with correcting errors in the number.
I also added a few checks, and a global formatFlag variable to ensure that if the user backspaces to an awkward index like 3 or 6(where hyphens would normally be added), that formatting would resume as normal on the next .keyup() event.
let formatFlag = false;
$(function(){
$('#phone').keyup(function(evt) {
let modifiedValue = $(this).val().replace(/-/g, "");
if(evt.keyCode == 8 || evt.keyCode == 46) { //8 == backspace; 46 == delete
//Checks whether the user backspaced to a hyphen index
if(modifiedValue.length === 3 || modifiedValue.length === 6) {
//Checks whether there is already a hyphen
if($(this).val().charAt($(this).val().length - 1) !== '-') {
formatFlag = true; //Sets the format flag so that hyphen is appended on next keyup()
} else {
return false; //Hyphen already present, no formatting necessary
}
} else {
formatFlag = false;
}
return false; //Return if backspace or delete is pressed to avoid awkward formatting
}
if(!!formatFlag) {
// This re-formats the number after the formatFlag has been set,
// appending a hyphen to the second last position in the string
$(this).val($(this).val().slice(0, $(this).val().length - 1) + '-' +
$(this).val().slice($(this).val().length - 1));
formatFlag = false; //Reset the formatFlag
}
if(modifiedValue.length % 3 == 0) {
if(modifiedValue.length === 0 || modifiedValue.length >= 9){
return false;
} else {
$(this).val($(this).val() + '-');
return;
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<label class="contact-label">Phone Number:</label>
<input type="tel" class="contact_input" name="phone" id="phone" />
</div>
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am trying to show an alert message when the check box is not selected. I use the following code for that purpose
function IsEmpty(){
var oldpath = document.forms['pathuploader'].oldpath.value;
var newpath = document.forms['pathuploader'].newpath.value;
var metavalue = !document.forms['pathuploader'].chkmeta.checked;
var postvalue = !document.forms['pathuploader'].chkpost.checked;
if((oldpath == "")||((oldpath.substring(0,4))!='http')||((oldpath.substring(0,4))=='Http'))
{
alert("Enter a valid URL");
return false;
}
if((newpath == "")||(newpath.substring(0,4)!='http')||(newath.substring(0,4)!='Http'))
{
alert("Enter a valid URL");
return false;
}
if((metavalue) && (postvalue))
{
alert("Select any category to change");
return false;
}
return true;
}
Working JSFiddle
First of all you have a typo on the following line
if((newpath == "")||(newpath.substring(0,4)!='http')||(newath.substring(0,4)!='Http'))
The last if is "newath" should be "newpath" and the same area "!=" should match the oldpath logic and instead be "==".
To clean up the code just a bit more, use "===" and "!==" instead of just "==" as this forces a more precise comparison.
See this link for more info use strict mode
Here is adjusted code
Also, try to use a camelCase naming convention if you wish to comply with JS standards. I have corrected the "IsEmpty" function to be "isEmpty" as an example.
function isEmpty(){
var oldpath = document.forms['pathuploader'].oldpath.value;
var newpath = document.forms['pathuploader'].newpath.value;
var metavalue = !document.forms['pathuploader'].chkmeta.checked;
var postvalue = !document.forms['pathuploader'].chkpost.checked;
if((oldpath === "")||((oldpath.substring(0,4))!=='http')||((oldpath.substring(0,4))==='Http'))
{
alert("Enter a valid old URL");
return false;
}
if((newpath === "")||(newpath.substring(0,4)!=='http')||(newpath.substring(0,4)==='Http')){
alert("Enter a valid new URL");
return false;
}
if((metavalue) && (postvalue)){
alert("Select any category to change");
return false;
}
return true;
}
UPDATE I also agree with "Sourabh" where the BANG (!) should be. As in
if(( !metavalue ) && ( !postvalue ){
instead of how it is currently. Both work, but the BANG is hiding in the variable. If you did keep it where it is, perhaps you could alert the next programmer that may view your code by calling it
var metaValueNotChecked = !document.forms...
var postValueNotChecked = !document.forms...
Then it would read correctly as
if(( metaValueNotChecked ) && ( postValueNotChecked ){
In this case, the BANG should be where you have it.
Hope this helps!
use the below procedure for more better way to do it, i am assuming that you have elements defined in your form, you need to change this two parts of code
first:
var metavalue = document.forms['pathuploader'].chkmeta.checked;
var postvalue = document.forms['pathuploader'].chkpost.checked;
then in if condition use the below procedure:
if(!metavalue && !postvalue)
{
alert("Select any category to change");
return false;
}
You can use "required" from HTML5, and remove it once a checkbox is checked, from every other of your checkbox. ex:
<input required="required" value="1" name="site[source][]" id="site_source_any" type="checkbox">
<input required="required" value="2" name="site[source][]" id="site_source_many" type="checkbox">
In your script file:
<script type="text/javascript">
// Check if atleast one of the checkbox is checked
$(function(){
var requiredCheckboxes = $(':checkbox[required]');
requiredCheckboxes.change(function(){
if(requiredCheckboxes.is(':checked')) {
// Remove Required once at-least one is checked
requiredCheckboxes.removeAttr('required');
}
else {
requiredCheckboxes.attr('required', 'required');
}
});
});
</script>
OK so i have this task that im not sure how to achieve. I have a text field that is only allowing the users to enter numeric values....I am validating on keypress to make sure that only numeric numbers are allowed
That works well
My problem is that the client wants text after the numbers to say " Miles" so if the user enters 100 they see "100 Miles"
I guess for usability. Does anyone know a good technique or jquery plugin to do this
In addition to a javascript solution, you may also want to look into the HTML 5 pattern attribute for <input>. For example, in modern browsers you could do something like:
<input name="miles" pattern="^\d+\s?[Mm]iles$" required>
Which requires no javascript at all :) Here's the relevant spec.
How about this:
$('input').keypress(function(e) {
if (e.which < 48 || e.which > 57) {
// not a number
return false;
}
// gets current entered numer
var number = this.value.split(' ')[0];
// adds new number
number = '' + number + String.fromCharCode(e.which);
this.value = number + ' miles';
return false;
})
It would be easier and I think clearer to do this in some sort of tag just outside of the textbox. Have a span directly below or something then update it on your keypress.
$('#textBox').keydown(function(){
// Validation code
$('#someSpan').html($(this).val() + " Miles");
});
How about this http://jsfiddle.net/TmxSN/1/
$(function(){
var timerOutId;
$('#inp').keypress(function(e) {
var key = e.which;
clearTimeout(timerOutId);
try{
if(this.value){
this.value = $.trim(this.value.match(/\d+/g)[0]);
}
}catch(e){}
if ((key < 48 || key > 57) && !(key == 8 || key == 9 || key == 13 || key == 37 || key == 39 || key == 46) ){
return false;
}
}).keyup(function(e) {
var textBox = this;
if(this.value){
timerOutId = setTimeout(function(){
textBox.value = $.trim(textBox.value.match(/\d+/g)[0]) + " Miles";
}, 2000);
}
})
});
My problem is that the client wants text after the numbers to say "
Miles" so if the user enters 100 they see "100 Miles"
Then you can handle it in the onfocus and onblur event of your input type="text" like this.
Try this
<input type="text" min="0" max="1000" step="1" id="distance" placeholder="Enter the value in miles"/>
And Script
$(document).ready(function() {
//$("#distance").keypress(PassNumbersOnly);
$("#distance").focus(OnFocus);
$("#distance").blur(OnBlur);
});
function OnFocus() {
var $this = $(this);
if ($this.val().indexOf("Miles") != -1) {
$this.val($this.val().split(" ")[0]);
}
}
function OnBlur() {
var $this = $(this);
if ($.trim($this.val()) != "") {
$this.val($this.val() + " Miles");
}
}
Demo here: http://jsfiddle.net/naveen/EQEMr/
Tell your client that anyone with enough intelligence to use the web can understand:
<label for="distance">Distance in miles:
<input type="text" name="distance" id="distance"></label>
and that doing anything else is:
confusing for users
problematic as javascript may or may not be enabled/available
of zero practical use for the business as the value must be validated on the server anyway
the value requires additional processing at the server to remove the appended characters