Hi i have here a script for two text fields.
If the current length is 0 character... I want to alert that no characters left!
<html>
<head>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<title></title>
</head>
<body>
<span id="limit">10</span><br/>
<input type="text" class="text_question_1"><br>
<input type="text" class="text_question_1">
</body>
<script type="text/javascript">
$(document).ready(function(){
//alert("test!!");
var combined_text_length = 0;
var limit = 10;
$("input.text_question_1").live('keyup', function (e){
current_length = 0;
$.each($("input.text_question_1"), function(index, value){
current_length += value.value.length
$(this).attr("#limit")
})
$("span#limit").html(limit - current_length)
})
})
</script>
</html>
I tried to put...
if (limit < 0){
alert("EXCEEDED!");
}
But not working.
current_length += value.value.length seems wrong. Use jQuery's own val() to retrieve the input field value as a string
Try
if (current_length > limit){
alert("EXCEEDED!");
}
As you are never modifying the limit variable itself, it can not get lower than zero.
Note that an alert is not particularly user-friendly. Lookup the jQuery plugin "lightBox".
Also, it seems you are trying to use a <input>s where a <textarea> might be more appropriate.
Related
I have a simple function that applies formatting to a form field using an onblur event - if 7 characters have been input into the field, the field's border turns green. Fewer than 7 character results in a red border. I'd like to be able to apply the function to each form field individually as the user tabs through. Currently, if I fill in the first form field, both form fields are formatted at the same time. I think the answer is using a for loop that iterates through the inputs, I just don't know how to update my code to reflect that; any help is much appreciated.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
function charCount() {
var char = document.getElementById("numb").value.toString().length
if (char == 7) {
$("input").addClass("green").removeClass("red");
} else {
$("input").addClass("red").removeClass("green");
}
}
</script>
<style>
.green {border-color:#009900;}
.red {border-color:#990000;}
</style>
</head>
<body>
<p>Please input ID numbers:</p>
<input id="numb" maxlength = 7 onblur="charCount()">
<input id="numb" maxlength = 7 onblur="charCount()">
</body>
</html>
some points mate:
First thing, elements should not have same id in one html document. They can have same class but not ids.
document.getElementById("numb").value.toString().length you are trying to find the input from user using this statement. This will always pick the value from one particular item. Better use $(this) in the event handler(i suppose you are using jquery and know how to do it)
$("input").addClass using this.. you are targeting all the input elements present in the document. Be specific to what you want to target to.
Do it like this:
html:
<input class="numb" maxlength = 7 onblur="charCount()">
<input class="numb" maxlength = 7 onblur="charCount()">
JS:
$('.numb').on('blur', function() {
// you access the current input elem with $(this)
var inputElem = $(this);
var char = inputElem.val().length;
if (char == 7) {
inputElem.addClass("green").removeClass("red");
} else {
inputElem.addClass("red").removeClass("green");
}
});
1.- You cannot have the same id for multiple inputs. Use a class instead.
2.- Then use "this" to have a reference of the input that is being used
Here's a working solution. Hope it helps!
$(".numb").blur(function(){
var char = $(this).val().length;
if (char == 7) {
$(this).addClass("green").removeClass("red");
} else {
$(this).addClass("red").removeClass("green");
}
});
.green {border-color:#009900;}
.red {border-color:#990000;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<p>Please input ID numbers:</p>
<input class="numb" maxlength = 7>
<input class="numb" maxlength = 7>
There are couple of issues in your code:
1) When you use this selector $("input") You are applying the class to all inputs instead of a specific input. You need to create a selector which targets the specific input which is blurred.
$("input").addClass("green").removeClass("red");
2) You are using same id for both input elements
<input id="numb" maxlength = 7 onblur="charCount()">
<input id="numb" maxlength = 7 onblur="charCount()">
3) You are mixing selectors of vanilla javascript and jQuery which can cause problems, it's better to use one or the other for your clarity.
VERSION:
This is the version with least changes to what you have already come up with, but the way you have attached the event is quite inefficient.
<script>
function charCount(num) {
var elem = $("#numb" + num);
var char = elem.value.toString().length;
if (char == 7) {
$(elem).addClass("green").removeClass("red");
} else {
$(elem).addClass("red").removeClass("green");
}
}
</script>
<style>
.green {border-color:#009900;}
.red {border-color:#990000;}
</style>
</head>
<body>
<p>Please input ID numbers:</p>
<input id="numb1" maxlength = 7 onblur="charCount(1)">
<input id="numb2" maxlength = 7 onblur="charCount(2)">
BETTER VERSION:
<html>
</head>
<script>
function init() {
$('input').on('blur', function() {
var elem = $(this);
if(elem.val().length < 7) {
elem.addClass('red').removeClass('green');
}
else {
elem.removeClass('red').addClass('green');
}
});
}
$( document ).ready(init);
</script>
<style>
.green {border-color:#009900;}
.red {border-color:#990000;}
</style>
</head>
<body>
<p>Please input ID numbers:</p>
<input maxlength = 7>
<input maxlength = 7>
</body>
</html>
An event better solution would be to use IIFEs.
I would suggest you go through some resources for learning event handling:
https://learn.jquery.com/events/handling-events/
https://api.jquery.com/category/events/
http://gregfranko.com/blog/jquery-best-practices/
Hope it helps!
I really hope that you can help me. I have a simple jQuery character count script, that counts down when a user enters a character into a text field. However now I need to customize it in two ways:
1.) I need to add a checkbox. When this checkbox is checked the character count has to be recuded by a certain amount e.g. 10 characters.
2.) The character count currently only shows when I start entering the first character, however I want the character count to show when the page loads.
If you have any questions please let me know.
Below you can find my code:
function countChar(val) {
var len = val.value.length;
if (len >= 500)
val.value = val.value.substring(0, 500);
else
$('#charNum').text(500 - len);
};
<textarea id="field" onkeyup="countChar(this)"></textarea>
<div id="charNum"></div>
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.5.js"></script>
<script>
//Sorry for making too many functions, well you also use other approches as well.
var len;
//for initiliase the count text value on page
function init(){
$("#charNum").text(500)
}
//for keyup and checkbox
function countChar() {
len = $("#field").val().length;
if (len >= 500) {
val.value = val.value.substring(0, 500);
}
if($("#idk").is(":checked"))
{
$("#charNum").text(500-($("#field").val().length +10));
}
else {
$('#charNum').text(500 - len);
}
}
</script>
</head>
<body onload="init();">
<textarea id="field" onkeyup="countChar()"></textarea>
<input type="checkbox" name="chk" id="idk" onchange="countChar()" />
<div id="charNum"></div>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.5.js"></script>
<script>
//Sorry for making too many functions, well you also use other approches as well.
var len;
//for initiliase the count text value on page
function init() {
$("#charNum").text(500)
}
//for keyup
function countChar() {
len = $("#field").val().length;
if (len >= 500) {
val.value = val.value.substring(0, 500);
}
if ($("#idk").is(":checked")) {
$("#charNum").text(500 - ($("#field").val().length + 10));
} else {
$('#charNum').text(500 - len);
}
}
</script>
</head>
<body onload="init();">
<textarea id="field" onkeyup="countChar()"></textarea>
<input type="checkbox" name="chk" id="idk" onchange="countChar()" />
<div id="charNum"></div>
</body>
</html>
I think there is an easy solution however I have searched and cant seem to find he answer. I am trying set up several buttons that when pressed replace the the contents of an input field with the value of the button. I would prefer to control this with pure javascript rather than jquery if possible.
Also, if possible I would like the title of the button to be slightly different than the value it passes to the input field.
One way to do it
script:
function foo(id, el)
{
document.getElementById(id).value = el.innerHTML.replace(/test/, 'something');
}
(Obviously you'd want to do something more useful to the value than replacing test by something. But you can.)
html:
<input id="piet"/>
<button onclick="foo('piet',this)">test123</button>
<button onclick="foo('piet',this)">test234</button>
http://jsfiddle.net/sE2UV/
Assume this markup (an extra data attribute to avoid hardcoding the selector):
<input id="target" type="text">
<button value="potatoes" data-for="#target">Potato</button>
<button value="tomatoes" data-for="#target">Tomato</button>
You may use value attribute to store the data:
var buttons = document.querySelectorAll('button[data-for]');
for (var i = 0; i < buttons.length; i++) {
var targetId = buttons[i].dataset.for;
var target = document.querySelector(targetId);
buttons[i].addEventListener('click', function () {
target.value = this.value;
})
}
Demo: http://jsfiddle.net/dmu8N/
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<script>
function setText() {
document.getElementById("input1").value = "SOME TEXT";
}
</script>
</head>
<body>
<button type="button" onclick="setText()">Click me to set text!</button>
<input id="input1" type="text">
</body>
</html>
Full JSBin Example: http://jsbin.com/aZIyAzir/2/
Here's a jQuery solution for completeness.
<input type='text' id='target'></input>
<button>Merry</button>
<button>Christmas</button>
Then your jQuery:
$(function() {
var $target = $('#target');
$('button').on('click', function() {
$target.val($(this).html());
});
});
I have a series of input fields. I never know how many, so I need to get the value from a class. In this case the class is .total.
The bestresult is a text field that gets it's value from mysql, but I want it to be changed manually or by the highest value from the other text fields.
This is the code. Does not work obviously, but maybe you get the idea of what I want to do.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$('input.total').change(function()
{
var max = $('.total').max();
$('#bestresult').attr("value", max);
});
</script>
<body>
<form>
<input type="text" name="bestresult" id="bestresult" class="total" value=""><br>
<input type="text" name="resultat[100][total]" class="total" value=""><br>
<input type="text" name="resultat[121][total]" class="total" value=""><br>
<input type="text" name="resultat[130][total]" class="total" value="">
</form>
</body>
</html>
The solution is very simple. Try this:
$('input.total').change(function()
{
var max = 0;
$('.total').each(function(){
if(parseFloat($(this).val()) > max ) {
max = parseFloat($(this).val());
}
});
$('#bestresult').val(max);
});
But if you have multiple textboxes, you should keep track of the max value and update every time change event is triggered to achieve better performance.
var max = 0;
// get the max for the first time
$(document).ready(function () {
$('.total').each(function () {
if (parseFloat($(this).val()) > max) {
max = parseFloat($(this).val());
}
});
$('#bestresult').val(max);
});
$('input.total').change(function () {
if (parseFloat($(this).val()) > max) {
max = parseFloat($(this).val());
}
$('#bestresult').val(max);
});
First, you should have your script at the end of your body, in order to have the elements defined when you bind the change event.
Then, you'd better filter the input, to exclude the one containing the max. You can use this selector : input.total[id!=bestresult].
And it would be better to bind also the keyup event, so that the max is updated without the user having to click outside.
Thus, you can have this code :
$('input.total[id!=bestresult]').on('blur change keyup', function(){
$('#bestresult').attr("value", Math.max.apply(null, $('.total[id!=bestresult]').map(function(){
return parseFloat(this.value)}).slice().filter(function(i, v){return v==v})
));
});
Demonstration
Hello guys i have an input field and i want to validate in real time the insterted characters.
I want that this input field accept only letters, number and one blank space. If is inserted for example *, script delete this characters.
Regards
On input filed:
onkeyup="check(this,'onlyletter')" onblur="check(this,'onlyletter')
On JS:
var r={
'onlyletter': // i need correct regular expression
}
function check(o,w){
// i need function
}
I have: Abc123' 123* but i accept Abc123 123
with raw JS:
the clue is in the method transform
<html>
<head>
<script>
function transform(elem) {
var v = elem.value;
var n = "";
//loop it to cut of more than 1 -- e.g. on copy & paste
if(v.length) {
n = v.slice(-1);
if( !isNaN(parseFloat(n)) && isFinite(n) ) {
elem.value = v.substring(0, v.length - 1);
}
}
}
</script>
</head>
<body>
<input
type="text"
name="date"
placeholder="Text only!"
onkeyup="transform(this);"
maxlength="10"
>
</body>
</html>
alternate way using jquery
MASK the textfield to only accept letters. now that can be done a number of ways. one is the query mask plugin
you only need query, query-mask and then it is 1 line of code ;)
demo:
<html>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.mask.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//masked input for alphabets only
//constrained to 20 characters in length without spaces
$("#myTextField").mask("SSSSSSSSSSSSSSSSSSSS");
});
</script>
<body>
<br><input type = "text" id="myTextField" name="Text Field"></br>
</body>
</html>