html multiple functions for "onkeypress" attribute - javascript

I have this HTML text input as below
<label style="color: white;" for="id">ID:</label>
<input type="text" onkeypress="return event.charCode >= 48 && event.charCode <= 57" maxlength="9" name="id" id="id">
Now, in the onkeypress I successfully added so only numbers can be entered.
but I have a JavaScript function called:
function checkID() {
and I want that additionally, after every number entered it will call this function. But I just can't get it to do them both (only allow numbers and call the function).
Thanks in advance! Itay.

You can enter the number validation to the checkID function.
<input type="text" onkeypress="return checkID(event,this)" maxlength="9" name="id" id="id">
function checkID(e,elem) {
if !(e.charCode >= 48 && e.charCode <= 57)
return false;
// continue checking the id...
}

Alternatively to attaching your function via html, you can add it using purely javascript:
document.querySelector("your-html-selector").addEventListener("keypress", function(event) {
// all your code here
});
This keeps your html clean and your code easy to read, especially if you're trying to execute multiple functions and such on an event occurring.

Related

Input formatting

I'm using an input type="number"to allow users to put a duration time on a post. The format is days hours:minutes:seconds as the backend provides the format.
What I need to do is to give that format to the input. Is this possible?
You can use input type text with pattern:
<form>
<input type="text" pattern="^\d{1,3} \d{1,2}:\d{1,2}:\d{1,2}$" placeholder="days hours:minutes:seconds"/>
<input type="submit"/>
</form>
It will validate the text using 1-3 digits for days and 1-2 for hours minutes and seconds.
You can also restrict typing of no digits and colons and space using jQuery:
$(function() {
$('input').keydown(function(e) {
console.log(e.which);
if (!((e.which >= 48 && e.which <= 57) || (e.which == 186 && e.shiftKey) || e.which == 32)) {
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" pattern="^\d{1,3} \d{1,2}:\d{1,2}:\d{1,2}$" placeholder="days hours:minutes:seconds"/>
<input type="submit"/>
</form>
If you have jQuery, then take a look at:
http://jonthornton.github.io/jquery-timepicker/
you can use also
<input type="datetime">

how to dynamically insert character in middle input text with JS

I have an input text box to fill in with hours from 00:00 to 23:59
I'd like to dynamically insert the double point ":" after the 2 first characters, something like in http://www.railtime.be/website/home-fr which is even giving an error message when wrong hours are given like 30:66... I can't figure out how it has been done, any idea?
<input type="text" name="time" id="time" placeholder="00:00" maxlength="5" value="">
I think a keypress function has been used but what with?
Thanks in advance!
Resolved with dfsq solution:
$('input#time').on('keyup', function(e) {
if (e.which && this.value.length === 2 && e.which !== 8) {
this.value += ':';
}
});
<input type="time"> isn't supported in Firefox etc.
If you wish to avoid jQuery, just use this simple code wherein your ':' would be inserted at the time of typing itself using the keyup event-
<html>
<head>
<script type="text/javascript">
function insertColon(e){
var unicode=e.keyCode? e.keyCode : e.charCode
if(unicode!=8){// this avoids backspace to spoil your logic
var textval=document.getElementById("time").value;
if(textval.length==3&&textval.charAt(1)!=":"&&textval.charAt(2)!=":"){// this case arises when backspace is used
textval=textval.substring(0,2)+":"+textval.substring(2,3);
document.getElementById("time").value=textval;
}
else if(textval.length==2&&textval.charAt(1)!=":"){// normal case
textval=textval+":";
document.getElementById("time").value=textval;
}
}
else if(unicode==46&&textval.length>=3&&textval.charAt(1)!=":"&&textval.charAt(2)!=":"){
textval=textval.substring(0,2)+":"+textval.substring(2);`document.getElementById("time").value=textval;`
}
}
</script>
</head>
<body>
<input type="text" name="time" id="time" placeholder="00:00" maxlength="5" value="" onKeyup="insertColon(event);">
</body>
</html>
You can yourself add some little code to script to check if the ranges of hours and minutes are falling within range.
This may help you out. http://jsfiddle.net/e2DzT/380/
It checks for the correct format, and if it is empty. It will output the correct response. Format can be only in 15:30 format.
When the correct format is found, the form is submitted.
<form id="login" name="login" method="post" action="#">
Just change it to what you want it to do.
You can try the following Javascript code:
function appendColon(){
var time=document.getElementById("time").value;
var hours=time.substring(0, 2);
var minutes=time.substring(2, 4);
document.getElementById("time").value=hours+":"+minutes;
}
<input type="text" name="time" id="time" onchange="appendColon()" placeholder="00:00" maxlength="5" value="">
In the onchange event of the input, appends : between hours and minutes.

JavaScript form with decimal numbers

I have a form which for now is only accepting integers, how can I have a form which accept decimals?
Also how can I activate a keyboard in HTML that has a keypad and a decimal point?
My JavaScript code for now is this:
var peso = parseInt(form.elements["x"].valueAsNumber);
var eta = parseInt(form.elements["y"].valueAsNumber);
var creatinina = parseInt(form.elements["c"].valueAsNumber);
and for the variables in HTML form, this:
<p align="center" style="font-size:20px">Peso (kg)</p>
<input name="x" type="number" value="70" style="width:100%;height:40px;font-size:15px;" pattern="\d*"/>
The way to handle it is to use an <input type="text"> and add a proper javascript-match.
<input type="text" name="amount" id="amount" maxlength="6" autocomplete="off"/></span>
After any change in this field happened, you could check against a regular expression like that one:
var ok = /^\d*\.?\d*$/.test(input);
If you think the input is correct, everything is fine. If not, you can print a message that this box should accept a decimal.
try this one to make you textbox able to accept only Numbers and decimals.
<HTML>
<HEAD>
<SCRIPT language=Javascript>
<!--
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<INPUT name="x" style="width:100%;height:40px;font-size:15px;" id="txtChar" onkeypress="return isNumberKey(event)"
type="text">
</BODY>
</HTML>

Which event should be used on text box to call javascript function?

I'm having two text boxes to store two dates. I want to call a javascript function upon entering date into the first and second textbox. That is as soonas I enter the date in second box I want to call the javascript function. I tried onchange but it is not calling the javascript function. Can you suggest me the right event to call the javascript function? Thanks in advance. I'm using smarty. My code is as follows:
<label>Created Date From</label>
<div class="form-element">
<input type="text" class="cal fl-left" name="from_date" id="frmDate" value="{if $data.from_date}{$data.from_date}{else}{/if}" maxlength="10" />
</div>
<label>Created Date To</label>
<div class="form-element">
<input type="text" class="cal fl-left" name="to_date" id="toDate" value="{if $to_date}{$to_date}{else}{/if}" maxlength="10" onchange="get_tests_by_date(); return false;"/>
</div>
Javascript code is as follows:
function get_tests_by_date() {
document.location.href = "view_tests.php?test_category_id="+document.getElementById('test_category_id').value+"&test_mode="+document.getElementById('test_mode').value+"&test_type="+document.getElementById('test_type').value+"&package_type="+document.getElementById('package_type').value+"&created_date_from="+document.getElementById('frmDate').value+"&created_date_to="+document.getElementById('toDate').value+"&page=1";
}
This is what i ended up doing years ago, no jquery in this code:
HTML:
<input name="FormStartDate" value="" maxlength="10" onkeydown="KeyDateNumCheck()"/>
<input name="FormEndDate" value="" maxlength="10" onkeydown="KeyDateNumCheck()"/>
JS:
//do not allow to input anything except the numeric characters, dashes, or slashes
function KeyDateNumCheck()
{
var iKeyCode = event.keyCode;
if ( (iKeyCode != 109) && (iKeyCode != 189) && (iKeyCode != 111) && (iKeyCode != 191) &&
( ((iKeyCode > 57)&&(iKeyCode < 96)) || (iKeyCode > 105) || (iKeyCode == 32)) )
event.returnValue = false;
}

Put label next to the input

I have a simple case. I want two things.
Put label next to the input.
Some sort of validation, only digit number for the text box.
The corresponding link is here.
Now the input is below the label.
My code:
<div id="generatePinsDialog" title="Generate New PINs">
<label style="display: inline-block; width: 400px;">
How many?</label>
<input id="newInmateCount" type="text" size="25" value="Enter the number!" />
<br />
<select>
<option value="sameAsID">Same as ID</option>
<option value="appendID">AppendID</option>
</select>
Demo: http://jsfiddle.net/GCtPE/25/
label, input { display: inline-block; }
For verification you will have to use javascript since HTML5 isn't fully supported by all browsers. HTML5 is pretty cool though.
First, remove the "inline-block" from your label and add the for attribute like so:
<label for="newInmateCount" style="width: 400px;">How many?</label>
As for the input, do this for numeric only:
$("#newInmateCount").keydown(function(e) {
if (e.which == 8 || e.which == 46) return true; // for backspace and delete
if (e.which < 48 || (e.which > 57 && e.which < 96) || e.which > 105) return false;
});
See your jsFiddle Updated
Remove the display: inline-block. That is causing the input filed to go to new line.
You this js function to validate just digits, call it onkeypress event of the input field or bind it with onkeydown event
function onlyNumbers(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
jsFiddle demo
to put the label next to the input, change display:inline-block; to display:inline, or decrease the width:400px to a lower value until you acheive the positioning you want. for validation you need to do some reading on regular expressions
jsfiddle here
The input was so far to the right because you set the width of the label to 400px, I just removed that and it looks fine now. Also added some quick validation, you'd obviously have to run the validation when the form is submitted.
<div id="generatePinsDialog" title="Generate New PINs">
<label style="display: inline-block;">
How many?</label>
<input id="newInmateCount" type="text" size="25" value="Enter the number!" />
<br />
<select>
<option value="sameAsID">Same as ID</option>
<option value="appendID">AppendID</option>
</select>
</div>​
And the JS is below:
if($('#newInmateCount').val() != "") {
var value = $('#newInmateCount').val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var intRegex = /^\d+$/;
if(!intRegex.test(value)) {
errors += "Field must be numeric.<br/>";
success = false;
}
} else {
errors += "Field is blank.</br />";
success = false;
}​
On-submit validation is pretty easy with jQuery. Here's an example. If you want to keep it from ever having something other than numbers in it, you can go with an onchange or onkeyup event and simply strip the numbers from the input.
For the positioning, try inline instead of inline-block.

Categories

Resources