I have a PHP page that pulls data from a database and auto-populates an input box. The code below is of a counter that displays how many characters are in a field upon typing.
However, when the PHP page is pulled up with the field populated, the counter says "0" until I type something in. How can I change the code so the counter displays how many characters are in the auto-populated field without me having to type something in? And then of course it should update when I do type something in.
<script language="JavaScript">
function textCounter(field, countfield, maxlimit) {
if (field.value.length > maxlimit) {
field.value = field.value.substring(0, maxlimit);
countfield.value = 'max characters';
// otherwise, update 'characters left' counter
}else {
countfield.value = field.value.length;
}
}
</script>
<center>
<form name=myform action="#">
<font size="1" face="arial, helvetica, sans-serif">
( You may enter up to 125 characters. )<br>
<input type="text" name="message" id="message"
onKeyDown="textCounter(this.form.message,this.form.remLen,125);"
onKeyUp="textCounter(this.form.message,this.form.remLen,125);"
>
<br>
<input readonly type=text name=remLen size=3 maxlength=3 value="0"> characters total</font>
</form>
</center>
Use window.document.onload to call your textCounter function
something like
<script>
window.document.onload=function(){
var form = document.getElementsByName('myform')[0];
textCounter(form.message,form.remLen,125);
};
....
Or just call your function on the onchange event like
<input type="text" name="message" id="message"
onchange="textCounter(this.form.message,this.form.remLen,125);" >
Related
I am trying to display #output value into another input field so far I found
this -> http://jsbin.com/oleto5/5/edit?html,js,output
here you can see when type into input field showing entered data into < div> which id=output <input id="txt" type="text" />
what I am looking to achieve: 1 - Changes in html- I am looking to show #output as a value into another input field like this <input id="output" type="text" />
2 - Changes in script - I also want to do changes in calculation i have php variable named $final_rate for, i want to "Output" deivide by php variable $final_rate
Expected Code Example
<body>
<input id="txt" type="text" />
<input id="output" type="text" value=""/>
</body>
<?php $final_rate = "121";?>
<script>
$(function(){
$('#txt').keydown(function(){
setTimeout(function() {
$('#output').text($('#txt').val());
}, 50);
});
});
</script>
in above example if we enter 10000 in #txt input field we should get an out of 82.644 in simple words "10000/121 = 82.644"
<body>
<input id="txt" type="text" />
<input id="output" type="text" value=""/>
<script>
//put the value in a javascript variable as a Number
var finalRate = <?php echo "121"; ?>;
$(function(){
//bind on the input event, which happens any time the value of the input changes
$('#txt').on('input', function(e){
//console log the rate just for debugging
console.log(finalRate);
//console log the math just for debugging
console.log(parseFloat(e.target.value)/finalRate);
//turn the value in the input into a Number, and perform the math
$('#output').val(parseFloat(e.target.value)/finalRate);
});
});
</script>
</body>
//put the value in a javascript variable as a Number
var finalRate = 121;//'<?php echo "121"; ?>;
$(function() {
//bind on the input event, which happens any time the value of the input changes
$('#txt').on('input', function(e) {
//console log the rate just for debugging
console.log(finalRate);
//console log the math just for debugging
console.log(parseFloat(e.target.value) / finalRate);
//turn the value in the input into a Number, and perform the math
$('#output').val(parseFloat(e.target.value) / finalRate);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="txt" type="text" />
<input id="output" type="text" value="" />
I want to limit number of words that user input to a text box . I tried one code it was successfull for only single text box when i ammend it to multiple text box this code did not work, An advice will be really appreciated.
<html>
<head>
<script type="text/javascript">
function validate(){
x=document.myForm
input=x.myInput.value
if (input.length>5){
alert("The field cannot contain more than 5 characters!")
return false
}else {
return true
}
}
</script>
</head>
<body>
<form name="myForm" action="http://www.java2s.com" onsubmit="return validate()">
Enter some text (less than 5 characters):
<input type="text" name="myInput" size="20">
<input type="submit" value="Submit">
</form>
</body>
</html>
There are two methods to go about it:
Method 1:
Using the maxlength="5" attribute
<input type="text" maxlength="5" name="somename"/>
Method 2:
Using Javascript:
<script language="javascript" type="text/javascript">
function limitInput(field, max) {
if (field.value.length > max) {
field.value = field.value.substring(0, max);
}
}
</script>
<input type="text" name="somename" onKeyDown="limitInput(this,5);" onKeyUp="limitInput(this,5);"" />
UPDATE
With a message:
<script language="javascript" type="text/javascript">
var errHolder = document.getElementById('err');
function limitInput(field, max) {
if (field.value.length > max) {
err.style.display = 'inline-block';
}
else
{
err.style.display = 'none';
}
}
</script>
<span>
<input type="text" name="somename" onKeyDown="limitInput(this,5);" onKeyUp="limitInput(this,5);" />
</span>
<span id="err" style="display:none;background-color:red;">Please enter less than 5 characters</span>
You can either set the maxlength attribute or trim the string everytime the user enters into it. Using maxlength is a better way of doing it
var input = document.getElementById("limit5");
var LIMIT = 5;
input.onkeyup=function(){
if(input.value.length > LIMIT){
input.value = input.value.substr(0,LIMIT);
//alert("Please limit your input to 5 characters")
}
}
<input id="autolimit5" maxlength="5" type="text"/>
<input id="limit5" type="text"/>
There are many ways to to prevent user from entering data in form elements. What you are trying is to validate all data in one go when user clicks on the Submit button. It would be better to validate at the time when the user is typing. Basically there are 4 related events whenever the user presses anything on the keyboard.
onKeyPress
onKeyDown
onKeyUp
onInput
You can use a combination of these events to achieve anything that you want. For the use case in the question we can just use keypress event.
<html>
<head>
<script type="text/javascript">
function validate(){
x=document.myForm
input=x.myInput.value
if (input.length>5){
alert("The field cannot contain more than 5 characters!")
return false
}else {
return true
}
}
// function which runs on every keypress of input element to which this
// function is attached
function validateTextField(e){
if(event.currentTarget.value.length >= 5){
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="http://nothing.com" onsubmit="return validate()">
Enter some text (less than 5 characters):
<input type="text" name="myInput" size="20" onkeypress="return validateTextField(event)">
<input type="text" name="anotherInput" size="20" onkeypress="return validateTextField(event)">
<input type="submit" value="Submit">
</form>
</body>
</html>enter code here
If you want, you can customize the size for the validation by changing some of the parameters
Update the html input definition with below
<input type="text" name="myInput" size="20" onkeypress="return validateTextField(event, 5)">
<input type="text" name="anotherInput" size="20" onkeypress="return validateTextField(event, 8)">
Update the function definition to use the second parameter
function validateTextField(e, size){
console.log(e);
if(event.currentTarget.value.length >= size){
return false;
}
}
I'm trying to make a form with pop up message where if the user doesn't fill up the input box nothing will happen and I'm done with that using required = "required" of input type number.
What I need is when the input box has been filled a message will pop up and says that the item is added when the button is clicked by the user.
Here's my code:
<label style="color:#000000;">Qty:
<input type="number" min="1" name="qty" required = "required" />
SCRIPT:
<script type="text/javascript">
function myFunction()
{
var a=document.forms["abc"]["qty"].value;
if (a!=null){
alert("Item has been successfully added to your Cart");
}
}
</script>
echo '<td>'.'<input name="but" type="image" value="'.$row3['id'].'"
src="images/button.png" onclick="myFunction()" />'.'</td>';
You missed the name of form - "abc" - in function myFunction You call element by
var a=document.forms["abc"]["qty"].value;
You have to use an id for your input tag.
<label style="color:#000000;">Qty:
<input type="number" min="1" id="qty" name="qty" required = "required" />
function myFunction()
{
var a=document.forms["abc"]["qty"].value;
if (a!=null && a!= ""){
alert("Item has been successfully added to your Cart");
}
}
Also check for empty fields
im trying to validate a form before its submitted to the database but something seems to be conflicting with it and its just sending anyway without any values
heres my form:
<form method="post" action="send.php" id="theform" name="theform">
<input type="text" name="firstname" id="firstname" value="First Name" onFocus="this.value=''" class="yourinfo" ><br/>
<input type="text" name="lastname" id="lastname" value="Last Name" onFocus="this.value=''" class="yourinfo"><br/>
<input type="text" name="email" id="email" value="Email Address" onFocus="this.value=''" class="yourinfo"><br/>
<span style="color:#FFF; font-family:Arial, Helvetica, sans-serif; font-size:12px;">Ally McCoist will be sacked on</span>
<div id="datepicker"></div>
<input type="hidden" name="date" id="date">
<input type="image" src="images/submit-button-small.png" name="submit" id="submit" value="submit" style="margin-top:10px; margin-left:-2px;" >
</form>
heres my validate javascript:
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["firstname", "lastname", "email"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
$("#theform").submit(function(e){
//Validate required fields
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
// Validate the e-mail.
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
e.preventDefault();
} else {
errornotice.hide();
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});
i also have this javascript on the page fore my jquery UI datepicker which i think might be causing the problem
<script>
$(function() {
$("#datepicker").datepicker({
altField: '#date'
});
$('#submit').click(function() {
$('#output').html($('form').serialize());
});
});
fingers crossed one of you can see something that might fix this problem
It is possible that the form was filled out by a person with JavaScript disabled or that a person or machine simply invoked an HTTP POST, with whatever values they saw fit. For this reason, it is necessary to perform validation on the server-side (i.e. in send.php), not just on the client-side (in the JavaScript file). JavaScript validation is really just a UI optimization that allows a user to be immediately told that something is wrong without requiring a round-trip communication to the server. From a user-interface perspective, JavaScript validation is important, but from a security perspective it is useless.
I have a form
<form>
<input id="input" type="number">
<input type="submit">
</form>
I want to be able to input a number into the number and click the submit button and javascript displays a number based on the number submitted.
(My Guess is that this question is very basic but I am pretty knew to javascript.)
Here is a very simple (jquery-less) example of what you might be after:
<script type="text/javascript">
function ShowANumber() {
var currentNumber = document.getElementById("input").value;
var newNumber = currentNumber * 10 // Do something with input
document.getElementById("result").innerHTML = newNumber;
return false; // Stop form submit
}
</script>
<form onsubmit="return ShowANumber();">
<input id="input" type="text"/>
<input type="submit"/>
</form>
<div>Result: <span id="result"></span></div>