How to check the length of a Textarea - javascript

I am trying to calculate if a textarea has a length of more than zero, then run a piece of code. I can't get this to work for some reason. I would appreciate help.
Here is my code:
Javascript (including jQuery):
$(document).ready(function () {
if ($('.comments').val().length > 0) {
$('form').attr('action', '?Email');
}
});
HTML:
<form action="?AddToQuote" method="POST">
<textarea name="comments" class="comments"></textarea>
<input type="submit" value="submit" />
</form>
I have tried a lot of different Javascript, none of it is working. Does a Javascript if statement run once the HTML page has loaded? I am positive that the line within the if statement works without the if statement, I have tested it already.

You need to execute that line each time the textarea contents get updated. Thus you need to set up the logic on the DOM ready event but evaluate the condition on each content change in the textarea:
$( document ).ready( function() {
var $comment = $('.comments');
$comment.on( 'change', function( event ) {
if( $('.comments').val().length > 0 ) {
$( 'form' ).attr( 'action', '?Email' );
$comment.off( 'change' );
}
} );
} );
As suggested by #destroydaworld you could also use the keyup event if it is really necessary that the check should be evaluated after each single charcter typed in by the used. This is normally used in combination with character counting. But in your case – as you are trying to add some URL parameter – I guess it is sufficient to listen to the change event.

Your if statement will be executed when the DOM is ready, that is to say when your page is fully loaded. Of course, your textarea is empty at that stage. So your if statement will never be true. You should add an event listener to your textarea like so :
$('.comments').on('keyup', function() {
// Do your IF statement here
});

Do it on the submit event of the form. This way it will only check it one time.
$('form').submit(function(){
if( $('.comments').val() ) {
$('form').attr('action', '?Email');
}
});
or i like to add a hidden input:
$('form').append('<input type="hidden" name="email" value="1">');
or you could just check on the server side if there are any comments to email.

Have you tried this?
http://www.jqeasy.com/jquery-character-counter/
Also, did you try calling your form through an ID instead as ('form') ?
$('#theformid').attr('action', '?Email');

Well you can try the following code. Hope it helps you. I have written the code in JS. You need to call the function on the load of page. Hope this helps!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
window.onload = function display()
{
var txt = document.getElementById("myarea").value;
var len = txt.length;
if (len > 0){
document.write("Sucess"); // if len > 0 do some action
}
else
document.write(txt); //else condition
}
</script>
</head>
<body>
<textarea id="myarea" rows="4" cols="25">
Hello! How are you??
</textarea>
</body>
</html>

Related

Show or hide a div depending on a radiobutton (checked/not)

After a long time here and using all your information and comments, I was able to solve all of my code problems. Actually, I don't speak too much English. Sorry for that. Anyway, here we go!
I'm doing business practices and they gave me a project and I've almost finished it, but I cannot deal with it:
I have to detect the OS user system by JS and then after that, if the client is using Windows, I should advise him that he can install a ".exe" to run this app via desktop displaying just a div within a description (here is the div — just a rectangle in this case, so, it doesn't matter). After trying for all of this afternoon, I couldn't solve it and I decided to still testing in at home:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>radio button test [FAILED haha]</title>
<link rel="stylesheet" href="index.css">
<script src="jquery.min.js"></script>
<script>
$(document).ready(function(){
systemName = navigator.platform;
if(systemName.indexOf('Win') != -1){
document.getElementById("good").checked = true;
}else{document.getElementById("bad").checked = true;}
});
if($(#good).is(":checked")){
$(#ident).style.display = "block";
};
</script>
</head>
<body>
<center>
<div id="ident"></div>
<form action="">
<input type="radio" name="system" id="good" value="good">Windows<br>
<input type="radio" name="system" id="bad" value="bad">others
</form>
</center>
</body>
</html>
The problem: I tried to use jQuery to use the Change event on input#windows. The problem is, if it's the default option, the div won't appear, and, if i try it inside out.
I'm done T.T
In advance, thanks.
PS: it's my first post, so if I did something wrong, sorry!
Your problem is that you are not listening to the changeevent. You will have to do that, and when the change event is fired, decide what to do based on the checked/unchecked status of the radio buttons. Also, since you mention that listening to change event doesn't do anything to the radio buttons on page load, that is because you are not evaluating the checked/unchecked status on page load.
p/s: And you forgot to wrap your selector in quotes.
Therefore, the solution is to fire a function on both page load (or DOM ready) and upon change:
$(document).ready(function() {
var systemName = navigator.platform;
if (systemName.indexOf('Win') != -1) {
$('#good').prop('checked', true);
} else {
$('#bad').prop('checked', true);
}
var updateIdent = function() {
if ($('#good').is(":checked")) {
$('#ident').show();
} else {
$('#ident').hide();
}
}
// Update when change event is fired
$('form input[type="radio"]').on('change', updateIdent);
// Update upon DOM ready
updateIdent();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ident">IDENT</div>
<form action="">
<input type="radio" name="system" id="good" value="good">Windows
<br>
<input type="radio" name="system" id="bad" value="bad">others
</form>
Your markup is fine, you're just missing some quotes in your jquery and having problems setting the display: block; This JS will fix it:
$(document).ready(function(){
systemName = navigator.platform;
if(systemName.indexOf('Win') != -1){
document.getElementById("good").checked = true;
}else{
$document.getElementById("bad").checked = true;
}
});
if($('#good').is(":checked")){
$('#ident').css('display','block');
};
However, unless you specifically need the radio buttons, you can do without them entirely. Some JS like this will work best:
$(document).ready(function(){
systemName = navigator.platform;
if(systemName.indexOf('Win') != -1){
$('#ident').css('display','block');
}else{
$('#ident').css('display','none');
}
});
Hope that helps!
Try this:
$('.radioBtn').change(function () {
if (this.value == 'good') {
$('#ident').show();
} else if (this.value == 'bad') {
$('#ident').hide();
}
});
systemName = navigator.platform;
if (systemName.indexOf('Win') > -1) {
$('#good').prop("checked", true).change();
} else {
$("#bad").prop("checked", true).change();
}
See it in action: https://jsfiddle.net/fmotankv/24/
Also, note that my Fiddle uses CSS to automatically hide the #ident div. I would recommend this method to avoid non-Windows users from potentially seeing the div flash on their screen before being removed by the code.

How to count string length, if length equals X, then execute code? - JavaScript

Using JavaScript, I want to call an anonymous function that checks the length of a string for every onkeyup event. When the string length equals 9, a conditional statement will execute a block of code. What am I doing wrong?
<input type="text" id="length_test" placeholder="Enter text here..." />
var length_test = document.getElementById('length_test');
var string_value = document.getElementById('length_test').value;
var x = 9;
length_test.onkeyup = function () {
if (string_value.length == x) {
// execute code here...
}
}
Give the following a try.
Note: The example below uses JQuery. If you didn't wait to use JQuery that is fine.
You could natively do it with the following.
document.getElementById("length_test").addEventListener("keyup", myFunction);
You would need to then create a function called myFunction that has your if statement in it.
$(document).ready(function() {
$("#length_test").on("keyup", function(event) {
if (event.currentTarget.value.length == 9) {
//do your logic here
alert("length is 9");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="length_test" placeholder="Enter text here..." />
document.getElementById returns a live node. This means that any changes happening to the actual element in the page will be reflected on the object. When you write something else in the field, the value property of the element gets updated. However, the value stored in string_value doesn't get updated, since it's just a good old string, not some kind of live object.
Another way to see it is that
var string_value = document.getElementById('length_test').value;
makes a copy of the element's .value and stores it in string_value (even though that's not exactly how it works). When you type in the input, it updates the .value but not the string_value variable.
But what you should do is:
document.getElementById('length_test').addEventListener("keyup", function(e) {
if(e.target.value.length === 9) {
alert("length is 9");
}
});
This is much better because document.getElementById is only executed once, when binding the event. Event listener functions can revieve the event through their first argument (commonly named e). e.target is the element which called the event, in this case the input element.
You could try:
<input type="text" id="length_test" placeholder="Enter text here..." onkeyup="keyupFunction()">
<script type = "text/javascript">
keyupFunction function () {
if(document.getElementById('length_test').value == 9) {
// execute code here...
}
}
</script>
Alternatively, you could use javascript to add an event listener to the input element:
<input type="text" id="length_test" placeholder="Enter text here...">
<script type = "text/javascript">
document.getElementById('length_test').addEventListener("keyup", function(evt) {
if(document.getElementById('length_test').value == 9) {
// execute code here...
}
});
</script>

Why is my javascript function not being invoked for simple MVC tutorial? Why can't I debug either?

Problem
I have been following this simple tutorial found here. However, I want to modify it so that the calculator is only invoked when the client clicks submit. However, when I click the submit button, no action is observed. I am not even seeing the alert.
EDIT:
I have modified the code per Ojay's suggestions. However, I am getting this error when I try to debug. I am getting this exact issue except I have VS13 Update 3. Multiple things going on here?
Code
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Sample Calculator</title>
<script src="~/Scripts/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#my-calc').on('submit', function () {
alert("This button is working?");
calculate();
});
function calculate()
{
alert('hi');
//Add
try {
$('#sum').val((parseInt($('#num1').val())) + parseInt($('#num2').val()));
} catch (e) {
}
//Subtract
try {
$('#sub').val((parseInt($('#num1').val())) - parseInt($('#num2').val()));
} catch (e) {
}
//Multiply
try {
$('#mul').val((parseInt($('#num1').val())) * parseInt($('#num2').val()));
} catch (e) {
}
//Divide
try {
$('#div').val((parseInt($('#num1').val())) / parseInt($('#num2').val()));
} catch (e) {
}
}
});
</script>
</head>
<body>
<div><h4>Sample Calculator</h4></div>
#using (Html.BeginForm())
{
<p> #Html.Label("Input 1") : #Html.TextBox("num1","0")</p>
<p> #Html.Label("Input 2") : #Html.TextBox("num2", "0")</p>
<p> #Html.Label("Sum ") : #Html.TextBox("sum")</p>
<p> #Html.Label("Sub ") : #Html.TextBox("sub")</p>
<p> #Html.Label("Mult ") : #Html.TextBox("mul")</p>
<p> #Html.Label("Div ") : #Html.TextBox("div")</p>
<button id="my-calc" type="button">Calculate</button>
}
</body>
</html>
Attempts
Put in alert. Not observed.
Rewrote it from documents.on.ready(). See below.
RTFM as seen here
Searched stackoverflow. Didn't find anything that worked.
Edit: I had something originally like the tutorial I was looking at. I had:
$(document).ready(function(){
$('#my-calc').on('submit', function (){ //stuff}
}
I don't understand why my function is not being invoked? My form id is correct. All I want to do is invoke this calculator method so my label's sum, sub, mult, and div display the results.
Please pardon the simplistic nature of this question, but I feel it would be useful for others doing .NET MVC tutorials who might also be having this problem. As a result of this question,
I decided to obtain a book on jQuery. Thanks for your assistance.
You're running your code before your form is rendered. Therefore, $('.my-calc') is returning an empty object, and doing nothing. Also, the selector for an item by ID is $('#my-calc'), your selector was looking for an element with class my-calc
// Passing a function into `$()` makes it run after the DOM is ready.
$(function() {
$('#my-calc').on('submit', function (){
alert("This button is working?");
calculate();
});
});
It looks as though there are multiple issues here.
Firstly your selector must be '#my-calc' to correctly select the submit form. Your jQuery code must be wrapped in a document ready handler (as per your added code), or the code needs to appear after the form. Also when you add a submit event handler then you need to return false to stop the form submitting. And lastly (and perhaps the most important), you cannot nest forms. The #using (Html.BeginForm()) creates a form, and then you are creating another one inside it <form id="my-calc">, this is not valid. What the browser will do is just ignore the inner one, so in other words, there will never be a submit event of the my-calc form, becuase the parent form is what is submitted.
Also because you are just doing a calculation on the page with JavaScript, there is no real need for a form anyway, perhaps just a <button type="button" id="my-calc">Calculate</button> would be better with a click event.
Now your calculate function also has errors
every calculation line is missing a $ in the attempt to get the num1 value
so
$('#sum').val((parseInt(('#num1').val())) + parseInt($('#num2').val()));
should be
$('#sum').val((parseInt($('#num1').val())) + parseInt($('#num2').val()));
and there is an additional issue with the multiplication one, the input is not #mult its #mul as per your #Html.TextBox("mul").
So all of that together, something like the following should resolve your issues
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Sample Calculator</title>
<script src="~/Scripts/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#my-calc').on('click', function () {
calculate();
});
function calculate() {
//Add
try {
$('#sum').val((parseInt($('#num1').val())) + parseInt($('#num2').val()));
} catch (e) {
}
//Subtract
try {
$('#sub').val((parseInt($('#num1').val())) - parseInt($('#num2').val()));
} catch (e) {
}
//Multiply
try {
$('#mul').val((parseInt($('#num1').val())) * parseInt($('#num2').val()));
} catch (e) {
}
//Divide
try {
$('#div').val((parseInt($('#num1').val())) / parseInt($('#num2').val()));
} catch (e) {
}
}
});
</script>
</head>
<body>
<div><h4>Sample Calculator</h4></div>
<p> #Html.Label("Input 1") : #Html.TextBox("num1", "0")</p>
<p> #Html.Label("Input 2") : #Html.TextBox("num2", "0")</p>
<p> #Html.Label("Sum ") : #Html.TextBox("sum")</p>
<p> #Html.Label("Sub ") : #Html.TextBox("sub")</p>
<p> #Html.Label("Mult ") : #Html.TextBox("mul")</p>
<p> #Html.Label("Div ") : #Html.TextBox("div")</p>
<button id="my-calc" type="button">Calculate</button>
</body>
</html>
For ids in jquery, you have to use #my-calc
But frankly, I think you're looking to call calculate on the button click otherwise you're going to have to submit your form every time you press the button, which kinda defeats the purpose of the javascript.
$("input").on("click", calculate);
http://jsfiddle.net/4pwakehm/
Your code isn't working because you don't have # in your Javascript.
# should be in front of the name, to represent an Id.
The . should be in front of the name, to represent an class.
You could is essentially do:
$(document).ready(function () {
$("#my-calc").on("click", function () {
alert("Triggered alert for click.");
});
});
Keep in mind that with $(document).ready utilizes jQuery.
That is an example, you should also use your console in the browser to help debug Javascript. Which will help troubleshoot such issues.

Two plugins in a textarea

I need to use two plug-ins in one element on my page. I've never needed to do this and tried as it is in the code below. Most did not work!
<script type="text/javascript">
$(document).ready(function()
{
var wbbOpt = {buttons: "bold,italic,underline,|,img,link,|,code,quote"}
// plugin one wysibb
$("#editor").wysibb(wbbOpt);
// plugin two hashtags
$("#editor").hashtags();
//the two plugin worked in textarea #editor
});
</script>
Can anyone help me? Thank you.
So you can't use them because each of them take control and wrap the textarea. Since the editor is the most complex of the two the best thing to do is to take the code of the hashtag and adapt it at your need.
So here's a working example, but if you want you can trigger the function I use to the change event (adding it) or some way else
<div id="higlighter" style="width;1217px;"></div>
<textarea id="editor"></textarea>
<br />
<input id="btn" type="button" value="HASH">
<br />
$(document).ready(function() {
var wbbOpt = {
buttons: "bold,italic,underline,|,img,link,|,code,quote"
};
$("#editor").wysibb(wbbOpt);
$('#btn').click(function () { report() });
});
function report() {
$("#hashtag").val($("#editor").htmlcode());
var str = $("#editor").htmlcode();
str = str.replace(/\n/g, '<br>');
if(!str.match(/(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?#([a-zA-Z0-9]+)/g)) {
if(!str.match(/#([a-zA-Z0-9]+)#/g)) {
str = str.replace(/#([a-zA-Z0-9]+)/g,'<span class="hashtag2">#$1</span>');
}else{
str = str.replace(/#([a-zA-Z0-9]+)#([a-zA-Z0-9]+)/g,'<span class="hashtag2">#$1</span>');
}
}
$("#editor").htmlcode(str);
}
you can check a working code here on jsfiddle.
http://jsfiddle.net/4kj7d6mh/2/
You can type your text and use the editor, and when you want to higlight the hastag you click the button. If you want that to happen automatically you have to change this line:
$('#btn').click(function () { report() });
And attach the function to the keypress for example (experiment a bit)

jQuery button takes value from input and do an action - how does it works?

I've got a small piece of code here
<label for="pass">Password</label>
<input type="text" id="pass" value="QWERTY">
<button for="pass">Submit!</button>
and jquery action
$("button").click(function(){
var value=$("input[id=pass]").attr("value");
if (value==="QWERTY"){
alert("Good!");
};
and it doesnt work. Do you know how to fix it?
Try this.
$("button").click(function(){
var value=$("input#pass").val();
if ( value === "QWERTY"){
alert("Good!");
}
});
jQuery has it's own built in function for fetching values from input fields.
You should prevent the default action from triggering when the button is clicked (otherwise the form will be submitted, and the JS will not execute). You should also use val() when accessing an input's value.
You should also wrap your code inside the DOMReady handler, to ensure that the DOM is accessible when your script is run.
Here's an updated version of your code:
$(function() {
$("button").click(function(e) {
e.preventDefault();
var the_value = $("#pass").val();
if(value == "QWERTY")
{
alert("Good!");
}
};
});
Try this : It's more optimized...
$("button").click(function(e){
e.preventDefault();
var value=$("#pass")[0].value;
if (value==="QWERTY"){
alert("Good!");
};
You can also remove the "for" attribute on the button, it's non correct ;)
Your code should work if you don't forget the }); at last and have put the code into dom ready callback function. The demo.
And you could write it like below:
$("button").click(function(){
if ($('#pass').val()==="QWERTY"){
alert("Good!");
};
});
I think you just have a syntax error. You need to make sure you close your function curly brace and your click close paren.
$("document").ready(function () {
$("button").click(function () {
var value = $("input[id=pass]").attr("value");
if (value === "QWERTY") {
alert("Good!");
}
});
});
Example:
http://jsfiddle.net/pandaPowder/5VjeD/3/

Categories

Resources