keyup function not working - javascript

I am making a character counter in js but keyup event is not working ???
$(document).ready(function() {
function countingCharacter(element, maxCount) {
var countLength = $('#' + element).val().length();
alert(countLength);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea onkeyup="countingCharacter("storyOutline",100)" onkeypress="countingCharacter("storyOutline",100);" onkeydown="countingCharacter("storyOutline",100)" id="storyOutline" rows="5" class="form-control" name="labinput7" placeholder="Story Outline" required></textarea>

To avoid any issues related to the functions scope and keep JS code separated from HTML, I'd go with following event binding:
$('#storyOutline').on('keyUp', function() {
var length = $(this).val().length();
alert(length);
});

onkeyup="countingCharacter("storyOutline",100)"
"storyOutline" will close and open the quotes in onkeyup
You could use single quotes inside the double quotes:
onkeyup="countingCharacter('storyOutline',100)"

You can get textarea length using event.currentTarget.textLength value
$(document).on("keyup", "#storyOutline", function (e) {
console.log(e.currentTarget.textLength);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<textarea id="storyOutline" rows="5" class="form-control" name="labinput7" placeholder="Story Outline" required></textarea>

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("input").keyup(function(){
alert("your pressed the key");
});
});
</script>
</head>
<body>
Enter your name: <input type="text">
</body>
</html>
when you keyup on the text field, you'll find an alert message that you have keyed.

Use single quotes to add arguments to the inline JavaScript functions, so:
<textarea onkeyup="countingCharacter('storyOutline')" ... ></textarea>
Instead of
<textarea onkeyup="countingCharacter("storyOutline")" ...></textarea>
But you don't actually need those parameters (you can keep maxCount inside the function's scope). Then access the target (input box element) with event.target. Select its input value and its length.
Here's a working code:
function countingCharacter(maxCount) {
console.log($(event.target).val().length);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea onkeyup="countingCharacter(100)" onkeypress="countingCharacter(100);" onkeydown="countingCharacter(100)" id="storyOutline" rows="5" class="form-control" name="labinput7" placeholder="Story Outline"
required></textarea>
You shouldn't use alert for debugging, use console.log instead.

Related

Multiple textareas

how can I reset multiple textareas to their default values (texts)? Is it possible without giving them specific class? I found only solution for one text input, but no successful with multiple textareas on 1 page, reseted by function.
<html>
<body>
<textarea rows="1" cols="30">Hello World</textarea><br/>
<textarea rows="1" cols="30">Hello Second World</textarea><br/>
<button onclick="reset()">Reset</button>
<script>
function reset() {
document.querySelectorAll('textarea').value = <!--Default Value-->
}
</script>
</body>
</html>
How about something like this?
Address:<br>
<textarea id="myTextarea">
342 Alvin Road
Ducksburg</textarea>
<textarea id="myTextarea2">
Value 2</textarea>
<p>Click the button to change the contents of the text area.</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("myTextarea").value = "Txt1";
document.getElementById("myTextarea2").value = "Txt2";
}
</script>
Edit to match the use case in the comment
According to MDN, textarea does not have a value property.
When the page loads the default value for a textarea is whatever the value in between some value. Therefore when the user changes it we don't have a way to find the original value.
To Overcome that we need somekind of a mechanism to store the default value
In your case if you have a lot of elements (Textareas), using a data attribute will help us to identify the default value after the page loads and the user changes the values
So use the following example
<textarea rows="1" cols="30" data-default="Default Val">Hello World</textarea><br/>
<textarea rows="1" cols="30" data-default="Default Val1">Hello World</textarea><br/>
<textarea rows="1" cols="30" data-default="Default Val2">Hello World</textarea><br/>
<button onclick="reset()">Reset</button>
<script>
function reset() {
var textareas = document.querySelectorAll('textarea');
for(i =0; i < textareas.length; ++i){
textareas[i].value = textareas[i].getAttribute('data-default');
}
}
</script>
You need to modify the js script like below:
function reset() {
document.querySelectorAll('textarea').forEach((elem) => elem.value = "Desiered value");
}
Or you can use an HTML placeholder and make the textarea value empty.

how to append a extra character to a variable that contain string in jquery

Hi I have struck in a issue that appending a special character to a variable that contain the value from a textbox. I have used .append() function to append a character but I getting error in console as append is not a function can anyone help me out from this issue
<html>
<body>
<form>
<input type="textbox" id="textbox"/>
<input type="submit" class="button" value="submit"/>
</form>
</body>
</html>
jquery
<script type="text/javascript">
$(document).ready(function() {
$(document).on('click', '.button', function(){
var demo=$('#textbox').val();
var demoapp=demo.append("^");
console.log(demoapp);
});
});
</script>
Can Any one help me out from this
https://jsfiddle.net/pxdc9g0f/6/
You can do normal string concatenation instead of using any library (like use used .append() )
$(document).ready(function() {
$(document).on('click', '.button', function() {
var demo = $('#textbox').val();
var demoapp = demo + "^";
alert(demoapp);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<input type="textbox" id="textbox" />
<input type="submit" class="button" value="submit" />
</body>
</html>
Instead of var demoapp=demo.append("^");, use var demoapp=demo+"^";
You're using append on a value, but from the docs:
Insert content, specified by the parameter, to the end of each element in the set of matched elements.
If you just need a string concatenation, you should try something like this:
var demo=$('#textbox').val();
var demoapp=demo + "^";
alert(demoapp);
If you want to edit the #textbox value, then you should try this:
var demo=$('#textbox');
demo.val(demo.val() + '^');
alert(demo.val());

jquery placeholder text for input form

I'm using jquery placeholder text for a search placeholder. This search field doesn't have any placeholder so i added this text.
$(document).ready(function(){
$('.mfilter-search').find("input[type=text]").each(function(ev)
{
if(!$(this).val()) {
$(this).attr("placeholder", "Refine Your Search");
}
});
});
i don't know it's the best way to add a placeholder using jquery. If anyone know more simple way please add your code it will be very helpful.
You can directly set the placeholder no need to check value and use .each()
$('.mfilter-search input[type=text]').attr("placeholder", "Refine Your Search")
If you want to place on first then use
$('.mfilter-search input[type=text]:first').attr("placeholder", "Refine Your Search")
You can simply use find method using value attribute
$('.mfilter-search').find("input[type=text][!value]").attr("placeholder", "Refine Your Search");
you can add placeholder attribute directly in your html element like this
<input type="text" name="fname" placeholder="search">
or you can add a class to all your element that you need to put placeholder eg:- .placeholder and add placeholder attribute in javascript like this.
$(".placeholder").attr("placeholder", "Type here to search");
or you can use plugins like these.
http://andrewrjones.github.io/jquery-placeholder-plugin/ or
https://github.com/mathiasbynens/jquery-placeholder or refer this site for different placeholder plugins.
https://www.sitepoint.com/top-5-jquery-html5-placeholder-plugins/
and your code is also good. We can do that way too.
hope this will work.
Try this code
$(document).ready(function(){
$('.mfilter-search').find("input[type=text]").each(function(ev)
{
var txt = $(this).data('placeholder');
$(this).attr('placeholder', txt);
});
});
For place holder no need complex method function in jquery simply use like this
<input type="text" placeholder = "Zipcode" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Zipcode'" name="zipcode" class="form-control" maxlength='10'>
try this. this is how you can add place holder if you have two input fields with same class name.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<style type="text/css">
</style>
<body>
first name :<input type="text" name="firstname" class="tfield" id="field0">
last name :<input type="text" name="lastname" class="tfield" id="field1">
</body>
<script type="text/javascript">
$(document).ready(function(){
var thelength = $(".tfield").length;
for(var i=0;i<thelength;i++)
{
var theid = $("#field"+i);
var thename = theid.attr("name");
alert(thename);
if(thename == "firstname")
{
theid.attr("placeholder","name");
}
}
});
</script>
</html>

how to read input from text input field and put input into div

I am trying to run this code.
the code should take a string as input and put that input to a div and calculate the width of the div.
here is code i have used.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<input type="text" value="" name="input">
<input type="submit" value="submit" name="submit">
<script>
var elem = '<div id="divitem" style="width:auto;"></div>';
$('body').append($(elem));
$("submit").click(function () {
var text = $(this).text();
value= $("input").val(text);
alert(value);
});
</script>
</body>
</html>
but i am not getting any output. how to do this?
please help me.
Try this paps!
Demo
This is similar to your problem.
HTML
<div id="container">
<input type="text" value="" id="inputtext">
<input type="button" value="submit" id="submit">
</div>
Script
$(function(){
var elem = '<span id="divitem"></span>';
$('#container').append($(elem));
$("#submit").click(function () {
$('#divitem').html($('#inputtext').val());
alert($('#divitem').width());
});
});
Here's a fiddle
To obtain value from a text field you need to use this,
$('input[name="input"]').val();
and not .text()
To answer your second question, you need to use this
$('#divitem').attr('style');
or
$('#divitem').attr('width');
The problem is here:
$("submit").click(function () {
var text = $(this).text();
value= $("input").val(text);
alert(value);
});
$(this) refers to the element that you select, which is the submit button.
You should replace the first line of the function with
$('input[name="input"]').text();
Finally, setting the html content of the div, will be done this way:
elem.html(test);
Hope this helps. Have a great day.
I have created a jsFiddle for your question http://jsfiddle.net/N4zFZ/ in JavaScript
You can calculate width by
`var width = $('#divId').attr('width');`

Error when trying to refer to a field by name

I am getting an error (document.my_formm.fieldName.value is null or not an object) from the below code:
<html>
<head>
<title>(Type a title for your page here)</title>
<script language=JavaScript>
function check_length(my_formm,fieldName)
{
alert(fieldName);
alert(document.my_formm.fieldName.value);
}
</script>
</head>
<body>
<form name=my_form method=post>
<input type="text" onChange=check_length("my_form","my_text"); name=my_text rows=4 cols=30 value="">
<br>
<input size=1 value=50 name=text_num> Characters Left
</form>
</body>
</html>
Your check_length function is using variables to identify the form and field names, however, by using dot notation, you are referring to a element of document named my_formm. When you are are using variable names, you should use the bracket notation instead:
function check_length(my_formm,fieldName)
{
alert(fieldName);
alert(document[my_formm][fieldName].value);
}
Also, you should really quote attributes in your input:
<input type="text" onKeyPress="checkCompanyName();" onChange="check_length('my_form', 'my_text');" name="my_text" rows="4" cols="30" value="">
In your javascript you have referred to the form as 'my_formm' i.e. you have an extra 'm' at the end which is not present in the HTML, this could be your problem.
Why does your JavaScript method take in that first parameter if it never uses it?
Just do onChange=check_length(this)
and in your function
function check_length(element)
{
// element points to the element in question
// element.form points to the form if you need it
alert(element.value);
}
In general it would be nice to write WHAT error are you getting...
anyhow checkCompanyName is not defined in the code you wrote.
Also you're passing two strings as variable, they do not have properties...
A better way to do this:
<script type="text/javascript">
function checkLength()
{
inp = document.getElementById("myInput");
len = document.getElementById("len");
len.value = inp.value.length;
}
</script>
<input id="myInput" onkeyup="checkLength()" />
<input id="len" />
EDIT AFTER COMMENT:
<script type="text/javascript">
function checkLength(inputname, lenname)
{
inp = document.getElementById(inputname);
len = document.getElementById(lenname);
len.value = inp.value.length;
}
</script>
<input id="myInput" onkeyup="checkLength('myInput', 'len')" />
<input id="len" />
document.my_formm looks for a form named my_formm. You need to use the associative array sintax instead, like document[my_formm], which will pass the value in my_formm at runtime, rather than looking for a property in the document object called my_formm (which doesn't exist).

Categories