Javascript: set label text - javascript

I'm trying to implement a generic function for a form with several fields in the following format.
<label id="LblTextCount"></label>
<textarea name="text" onKeyPress="checkLength(this, 512, LblTextCount)">
</textarea>
And the following JavaScript:
function checkLength(object, maxlength, label) {
charsleft = (maxlength - object.value.length);
// never allow to exceed the specified limit
if( charsleft < 0 ) {
object.value = object.value.substring(0, maxlength-1);
}
// I'm trying to set the value of charsleft into the label
label.innerText = charsleft;
document.getElementById('LblTextCount').InnerHTML = charsleft;
}
The first part works fine, but I'm not able to set the charsleftvalue into the label. What am I doing wrong?
Please note that I'm looking for a dynamic approach instead of hard coding the label name into the JS function. JQuery would be fine too :)
Solution - thanks to all!
HTML
<label id="LblTextCount"></label>
<textarea name="text">
</textarea>
JS
$(document).ready(function() {
$('textarea[name=text]').keypress(function(e) {
checkLength($(this),512,$('#LblTextCount'));
}).focus(function() {
checkLength($(this),512,$('#LblTextCount'));
});
});
function checkLength(obj, maxlength, label) {
var charsleft = (maxlength - obj.val().length);
// never allow to exceed the specified limit
if( charsleft < 0 ) {
obj.val(obj.val().substring(0, maxlength-1));
}
// set the value of charsleft into the label
$(label).html(charsleft);
}

InnerHTML should be innerHTML:
document.getElementById('LblAboutMeCount').innerHTML = charsleft;
You should bind your checkLength function to your textarea with jQuery rather than calling it inline and rather intrusively:
$(document).ready(function() {
$('textarea[name=text]').keypress(function(e) {
checkLength($(this),512,$('#LblTextCount'));
}).focus(function() {
checkLength($(this),512,$('#LblTextCount'));
});
});
You can neaten up checkLength by using more jQuery, and I wouldn't use 'object' as a formal parameter:
function checkLength(obj, maxlength, label) {
charsleft = (maxlength - obj.val().length);
// never allow to exceed the specified limit
if( charsleft < 0 ) {
obj.val(obj.val().substring(0, maxlength-1));
}
// I'm trying to set the value of charsleft into the label
label.text(charsleft);
$('#LblAboutMeCount').html(charsleft);
}
So if you apply the above, you can change your markup to:
<textarea name="text"></textarea>

you are doing several things wrong. The explanation follows the corrected code:
<label id="LblTextCount"></label>
<textarea name="text" onKeyPress="checkLength(this, 512, 'LblTextCount')">
</textarea>
Note the quotes around the id.
function checkLength(object, maxlength, label) {
charsleft = (maxlength - object.value.length);
// never allow to exceed the specified limit
if( charsleft < 0 ) {
object.value = object.value.substring(0, maxlength-1);
}
// set the value of charsleft into the label
document.getElementById(label).innerHTML = charsleft;
}
First, on your key press event you need to send the label id as a string for it to read correctly. Second, InnerHTML has a lowercase i. Lastly, because you sent the function the string id you can get the element by that id.
Let me know how that works out for you
EDIT Not that by not declaring charsleft as a var, you are implicitly creating a global variable. a better way would be to do the following when declaring it in the function:
var charsleft = ....

For a dynamic approach, if your labels are always in front of your text areas:
$(object).prev("label").text(charsleft);

Related

Javascript form value restriction

I am trying to create a form which will store values in an empty array but the values must be between 0 to 5 and comma separated. the problem is it alerts if values is more than 5 but still stores the value in the array. I want it to alert and then restore the form value.
Here is my code:
<form name ="form1" onsubmit="return validateForm()">
<input type="number" name="text" id="inputText" name="inputText" />
<button onclick="pushData();">Insert</button>
<p id="pText"></p>
</form>
And javascript:
function validateForm () {
var form = document.forms["form1"]["inputText"].value;
if(form <0 && form >= 6) {
alert('value should must be between 0 to 5');
return false;
}
}
// create an empty array
var myArr = [];
function pushData() {
// get value from the input text
var inputText = document.getElementById('inputText').value;
// append data to the array
myArr.push(inputText);
var pval = "";
for(i = 0; i < myArr.length; i++) {
pval = pval + myArr[i];
}
// display array data
document.getElementById('pText').innerHTML = "Grades: " + pval ;
}
Try
if (form <0 || form >= 6)
I think it may work better if you reorganize where the functions are being bound.
Event propagation order:
The button is clicked, and the value is pushed into the array.
The form's submit event triggers, and validates the values, but it's too late.
There are many ways to approach this one, but the simplest would be to call pushData at the end of your validateForm.
Adjusted the condition, because there's no way for a number to
be less than 0 AND greater than or equal to 6 at the same time.
Also added event.preventDefault to stop form submission.
JavaScript
function validateForm (event) {
event.preventDefault();
var form = document.forms["form1"]["inputText"].value;
if (form < 0 || form > 5) {
alert('value should must be between 0 to 5');
return false;
}
pushData();
}
HTML
<form name="form1" onsubmit="validateForm(event)">
<input type="number" id="inputText" />
<button type="submit">Insert</button>
<p id="pText"></p>
</form>
JSFiddle
Note that per the MDN:
A number input is considered valid when empty and when a single number
is entered, but is otherwise invalid.
With this particular form element you may add min and max attributes so that the user must enter a value within a specified range. Therefore, the current contents of the OP's validateForm() function are superfluous. Additionally, that function has a problematic line of code:
if(form <0 && form >= 6) {
You cannot have a value that is both less than zero and greater than or equal to six. Use instead a logical OR, i.e. "||" operator for the logic to work.
The following code allows for a user to select numeric values in the range that the OP specifies and then it displays them in a comma-separated format, as follows:
var d = document;
d.g = d.getElementById;
var pText = d.g('pText');
pText.innerHTML = "Grades: ";
var inputText = d.g("inputText");
var myArr = [];
function pushData() {
var notrailingcomma = "";
myArr.push(inputText.value);
if (myArr.length > 1) {
notrailingcomma = myArr.join(", ").trim().replace(/,$/g,"");
pText.innerHTML = "Grades: " + notrailingcomma;
}
else
{
pText.innerHTML += inputText.value;
}
}
d.forms["form1"].onsubmit = function(event) {
event.preventDefault();
pushData();
};
p {
padding: 1em;
margin:1em;
background:#eeeeff;
color: #009;
}
<form name="form1">
<input type="number" id="inputText" name="inputText" min=0 max=5 value=0>
<button type="submit">Insert</button>
</form>
<p id="pText"></p>
A couple of points with respect to the form:
The OP's HTML has an error in the input field: it has two names. I dropped the one with a name of "text".
I like what #thgaskell recommends with respect to changing "Insert" into a submit button, preventing the default action of submitting the form, and associating pushData with the form's onsubmit event. So, I've modified the code accordingly.

How do I change a string into a password?

I have:
$('#pass').on('keyup keydown', function() { //the password input
$('#pass-result').text( $(this).val() ); //the input's bullet's, not string value
});
The text value of the password is printed as the input's string. How do I convert it to the password's masqueraded bullet form (•)?
If you're looking for dots to appear in the field when text is typed in it, you should use <input type="password"> instead of <input type="text">:
<input type="password" id="pass" />
which you would get the text from with $("pass").val().
It looks like you want a string of dots instead. To accomplish this, use:
var dots = Array($("pass").val().length + 1).join("•");
To explain:
$("pass").val() gets the text
$("pass").val().length gets the length of that
Array($("pass").val().length + 1) gets a new Array whose length is 1 more than the length of the password text
Array($("pass").val().length + 1).join("•") returns each element of the Array with a dot inserted between each - which is why we needed 1 extra, otherwise we would get a fencepost error.
According to the fact that you only want to parse a string of dots . what you gonna do is (IF YOU USE 2 INPUTS!)
function getKeyCode(event) {
event = event || window.event;
return event.keyCode;
}
$('#pass').on('keyup', function(e) { //the password input
if (getKeyCode(e) == 8) {
$('#pass-result').val($('#pass-result').val().slice(0,-1) );
}
else {
$('#pass-result').val($('#pass-result').val() + '•');
}
});
didnt test the code though. but it should add a • to the #pass-result on ever key-down in the #pass field. it doesnt remove any on backspace though..
http://jsfiddle.net/7810squo/
if you wanna do it with a <span> you need to use .html()
function getKeyCode(event) {
event = event || window.event;
return event.keyCode;
}
$('#pass').on('keyup', function(e) { //the password input
if (getKeyCode(e) == 8) {
$('#pass-result').html($('#pass-result').html().slice(0,-1) );
}
else {
$('#pass-result').html($('#pass-result').html() + '•');
}
});
http://jsfiddle.net/u9kdeewd/
EDIT: updated code and provided jsFiddle link

jQuery plugin for inline form validation

I m using jQuery plugin for inline form validation in my .NET web application.
With following:
jquery.validationEngine.js
jquery.validationEngine-en.js
jquery-1.6.min.js
validationEngine.jquery.css
template.css
Now i have two html <select> , one is for minimum value and second is for maximum value. Values should be check onchange.
How to use custom functions to Validate minimum and maximum values.
Untested but according to the reference of the jQuery plugin, you can work with custom functions to validate a field value:
HTML:
<input class="validate[required,funcCall[checkMinMax]]" type="text" ...
JavaScript:
function checkMinMax(field, rules, i, options) {
var minVal = parseInt($("#sel_min").val(), 10),
maxVal = parseInt($("#sel_max").val(), 10);
if(!isNaN(minVal) && !isNaN(maxVal)) {
if (minVal > maxVal) {
return 'YOUR MESSAGE TEXT HERE';
} else if (maxVal < minVal) {
/* OR use the options with */
return options.allrules.validate2fields.alertText;
}
}
}
It's a long time since I saw the usage of another jQuery validation plugin than jQuery validate, comparing both I suggest you should look into this, because it became more a less the 'standard' way to handle form validation with jQuery, it's well documented and you'll find most of the problems already solved.
<select id="sel_max" name="sel_max" style="width:83px" class="validate[required,funcCall[checkMinMax]]" >
jquery.validationEngine.js :
window.checkMinMax = function(field, rules, i, options) {
var minVal = parseInt($("#sel_min").val(), 10);
var maxVal = parseInt($("#sel_max").val(), 10);
var bothHaveValues = !isNaN(minVal) && !isNaN(maxVal);
if (bothHaveValues) {
if (minVal > maxVal) {
return options.allrules.cmm.alertText2;
}
else if (maxVal < minVal) {
return options.allrules.cmm.alertText;
}
}
};
jquery.validationEngine-en.js :
"cmm": {
"alertText": "* Max value < Min value!",
"alertText2": "* Min value > Max value!"
},

if input field is not a number OR not empty replace with a number

I have an input field that I am monitoring for changes using an .on('input') function as this covers .change and .keyup.
There is no submit button yet I just want to change the behaviour of the input field depending on what is entered.
I will validate server side later and I'm using html5 type='number'.
I only want the field to be able to hold a number, or it can be empty. The user might want to empty the contents to type the number 15 for example.
However I don't want any other characters to be accepted - if they are entered, a prompt should show notifying the user of this and the field is defaulted back to it's starting value of 1.
HTML
<input type="number" class="input-field" placeholder="" value="1" min="1">
JS
$(document).ready(function ($) {
var num = $('input[type="number"]').val();
$('input[type="number"]').on('input', function () {
var num = $(this).val();
if (num < 1 || isNaN(num) || num !== '') {
alert(num + ' is not a number or is less than 1');
$(this).val(1);
}
});
});
I have tried with the above code and it doesn't allow for an empty field. I've also tried if (num < 1 || isNAN(num) || num.length != 0) {
do I need to use .replace() with a Regexr. I've been looking at a few questions on here like here but I'm not sure thats what I'm looking for considering I'm testing for an empty string.
JSFIDDLE
You can use the constraint validation API:
$('input[type="number"]').on('input', function () {
if (!this.validity.valid) {
alert(this.value + ' is not a number or is less than 1');
this.value = 1;
}
});
$('input[type="number"]').on('input', function () {
if (!this.validity.valid) {
alert(this.value + ' is not a number or is less than 1');
this.value = 1;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" class="input-field" placeholder="" value="1" min="1">
However, note that this behavior is obtrusive. If an user types the wrong key, you will annoy him with a modal dialog and will clear the number.
Consider doing nothing. HTML5 browsers won't send the form if the input is not valid.
The HTML5 answer is definitely more elegant.
But if you want to offer more support, this is usually the route I take when trying to verify numbers.
Note that I am using data-min attribute but if you want to switch you can always use $.attr() to grab your min="" attribute.
$(document).ready(function ($) {
$('input[type="number"]').on('change', function () {
var min = parseInt(this.dataset.min),
num = isNaN(parseInt(this.value)) ? 0 : parseInt(this.value),
clamped = Math.max(num, min);
if(num != clamped) {
alert(num + ' is less than 1');
this.value = clamped;
}
});
});
jsfiddle

Insert '-' every 5 characters as users type [like a product key] [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Auto-format structured data (phone, date) using jQuery plugin (or failing that vanilla JavaScript)
Insert space after certain character into javascript string
I am trying to write a script that handles product keys like the ones you see on the back of software and games.
I would like so when the user is inputing their key code the '-' are inserted every 5 characters for 5 sets of characters. Ex(ABCDE-FGHIJ-KLMNO-PQRST-UVWXY). So when the user enters ABCDE as soon as the 'E' is enetered a '-' is inserted immeditly after via jQuery or JavaScript.
Thanks In Advance.
Comment if you have any questions or if I was unclear :)
Form:
<form method="post" action="process.php">
<p>Key: <input name="key" id="key" size="40"></p>
<p><input type="submit"></p>
</form>
You can use http://digitalbush.com/projects/masked-input-plugin/
jQuery(function($){
$("#key").mask("aaaaa-aaaaa-aaaaa-aaaaa-aaaaa");
});
HTML:
<fieldset id="productkey">
<input type="text" size="5" maxlength="5">
<input type="text" size="5" maxlength="5">
<input type="text" size="5" maxlength="5">
<input type="text" size="5" maxlength="5">
<input type="text" size="5" maxlength="5">
</fieldset>
JavaScript:
$( '#productkey' ).on( 'keyup', 'input', function () {
if ( this.value.length === 5 ) {
$( this ).next().focus();
}
});
Live demo: http://jsfiddle.net/XXLND/3/show/
You can also enhance the code, so that when the last text-box is filled out, a processing mechanism is activated:
$( '#productkey' ).on( 'keyup', 'input', function () {
var $field = $( this );
if ( $field.val().length === 5 ) {
if ( $field.is( ':last-of-type' ) ) {
$field.blur();
processKey();
} else {
$field.next().focus();
}
}
});
Live demo: http://jsfiddle.net/XXLND/4/show/
Simply because I don't like JQuery :)
function insertSpace(string, part, maxParts) {
"use strict";
var buffer = string.split("-"), step, i;
for (i = 0; i < buffer.length; i += 1) {
step = buffer[i];
if (step.length > part) {
buffer[i] = step.substr(0, part);
buffer[i + 1] = step.substr(part) + (buffer[i + 1] || "");
} else if (step.length < part) {
if (i == buffer.length - 1) {
if (!step) {
buffer.pop();
}
} else {
buffer[i + 1] = step + (buffer[i + 1] || "");
buffer.splice(i, 1);
i -= 1;
}
}
}
buffer.length = Math.min(maxParts, buffer.length);
return buffer.join("-");
}
How about using http://digitalbush.com/projects/masked-input-plugin
With that plugin, the following:
jQuery(function($){
$("#key").mask("99999-99999-99999-99999-99999",{placeholder:" "});
});
or, if your key is all letters use:
$("#key").mask("aaaaa-aaaaa-aaaaa-aaaaa-aaaaa",{placeholder:" "});
or, if it's alpha/numeric use:
$("#key").mask("*****-*****-*****-*****-*****",{placeholder:" "});
Here's one approach:
// binds to both the 'keyup' and 'paste' events
$('input:text').on('keyup paste', function(e) {
var that = $(this), // caches the $(this)
val = that.val(), // access the value of the current input
key = e.which, // determines which key was pressed
allowed = [8, 46, 9, 16]; // defines 'allowed' keys (for editing/focusing)
// backspace, delete, tab, shift
if ($.inArray(key, allowed) == -1) {
// if the pressed key is *not* an 'allowed' key
if (val.length == 5) {
// focuses the next element
that.next().focus();
}
else if (val.length > 5) {
// truncates the string, if greater than 5 characters
that.val(val.substring(0, 5));
that.next().focus();
}
}
});​
JS Fiddle demo.
The advantage of this approach is that rather than masking or manipulating the entered string, and accounting for multiple edge-cases, you're simply aiding the user by moving the focus at the right point. And, in this case, also allowing the user to refocus the re-edit the previously entered data.
two things:
One the user experience side, I would avoid dynamically adding character in the input field as the user type a code. Depending on the environment you run the risk to interfere with what the user type.
However, the '-' helps user typing the code since this is a reference point for him. So I would suggest to have an input field and to show a pretty version of the code next to it (or make the field invisible and manage the focus of the field yourself).
For the php code, instead of adding a character every 5 characters I would do the opposite and simplify the code by removing all the unnecessary characters.
Something like that
if ( str_replace('-', '', $userInputKey)==str_replace('-', '', $officialKey) {
echo 'Yeah! Valid key!';
}

Categories

Resources