Special jQuery Character Count - javascript

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>

Related

New to Javascript Making a Tip calculator cant figure out why its not loading?

Hey guys I am new to javascript, I was trying to practice by doing a lab that I saw online and I was following along with the original code posted and I was making my own tweaks at the same time. I finished the html portion and javascript portion but when I hit calculate nothing is happening. I did inspect element went to console and ran it and it showed syntax error but I am unclear where this error is?? this is my code
<DOCTYPE !html>
<html lang="en">
<head>
<link rel="stylesheet" href="css/tip.css">
<title>Tip Calculator</title>
<script type="text/javascript">
//this is to calculate tip
function calculateTip() {
var billAMT = document.getElementBy("billamount").value;
var serviceQual = document.getElementById("servicequality").value;
var peopleAmt = document.getElementById("peopleamount").value;
//to validate input
if billAmt( === "" || serviceQual == 0) {
alert("please enter numbers");
return;
}
if (peopleAmt === "" || peopleAmt <= 1) {
peopleAmt = 1;
document.getElementById("each").style.display = "none";
} else {
document.getElementById("each").style.display = "block";
}
// to calculate the tip
var total = (billAmt * serviceQual) / peopleAmt;
//to round to two places
total = Math.round(total * 100) / 100;
total = total.toFixed(2);
// to display tip
document.getElementById("totalTip").style.display = "block";
document.getElementById("tip").innerHTML = total;
}
document.getElementById("totalTip").style.display = "none";
document.getElementById("each").style.display = "none";
// to call function
document.getElementById("calculate").onclick = function() {
calculateTip();
};
</script>
</head>
<body>
<div id="container">
<h1> Tip Calculator</h1>
<div id="calculator">
<form>
<p> Enter bill amount</p>
<input id="billamount" tyle="text" placeholder="Bill Amount">
<p>How was your service?</p>
<select id="servicequality">
<option value="0.3">30% - Amazingly LITT</option>
<option value="0.2">20% - Good</option>
<option value="0.15">15%-Was ight</option>
<option value="0.10">10%- bad</option>
<option value="0.05">5%- Terrible</option>
</select>
</form>
<p>How many people are sharing the bill?</p>
<input id="peopleamount" type="text" placeholder="# of people">
<button type="button" id="calculate">Calculate</button>
</div>
<div id="totalTip">
<sup>$</sup><span id="tip">0.00</span>
<small id="each">each</small>
</div>
</div>
</body>
</html>
There are a couple of errors in your script.
The browser parses your HTML code from top to bottom. That means it processes the <head> section before <body>.
The JavaScript part is located inside the <head> section and put between the opening tag <script type="text/javascript">
and the closing tag </script>.
If you take a closer look at your JavaScript code you'll find find this two statements:
document.getElementById("totalTip").style.display = "none";
document.getElementById("each").style.display = "none";
Those aren't inside the scope of the calculateTip(){} function nor the .onclick = function() {} handler so the browser
tries to execute it. Unfortunately it can't! The two elements it tries to manipulate - totalTip & each - aren't available
yet since the browser didn't reach the <body> section yet where it's actually defined.
So you have two options.
A
Move the whole JavaScript block including <script type="text/javascript"> and </script> and anything in-between to the body
section, just above the closing </body> tag almost at the end of the file.
B
Maybe those two statements belong inside the .onclick = function() {} handler. Move it there like:
document.getElementById("calculate").onclick = function() {
document.getElementById("totalTip").style.display = "none";
document.getElementById("each").style.display = "none";
calculateTip();
};
Change this line
if billAmt( === "" || serviceQual == 0) {
to this
if (billAMT == "" || serviceQual == 0) {
Javascript is case-sensitive - meaning billAmt and billAMT are not the same. Change all references to either billAmt or billAMT
there is a little typo:
var billAMT = document.getElementById("billamount").value;
You have various minor error such as:
Putting script the referenced an HTML element before the HTML element itself. Putting it at the bottom of the body fixed it
Using document.getElementBy instead of document.getElementById
Referencing the wrong variable name (declared as billAMT, referenced as billAmt)
And some typographical error
<DOCTYPE !html>
<html lang="en">
<head>
<title>Tip Calculator</title>
</head>
<body>
<div id="container">
<h1> Tip Calculator</h1>
<div id="calculator">
<form>
<p> Enter bill amount</p>
<input id="billamount" tyle="text" placeholder="Bill Amount">
<p>How was your service?</p>
<select id="servicequality">
<option value="0.3">30% - Amazingly LITT</option>
<option value="0.2">20% - Good</option>
<option value="0.15">15%-Was ight</option>
<option value="0.10">10%- bad</option>
<option value="0.05">5%- Terrible</option>
</select>
</form>
<p>How many people are sharing the bill?</p>
<input id="peopleamount" type="text" placeholder="# of people">
<button type="button" id="calculate">Calculate</button>
</div>
<div id="totalTip">
<sup>$</sup><span id="tip">0.00</span>
<small id="each">each</small>
</div>
</div>
<script type="text/javascript">
//this is to calculate tip
function calculateTip() {
var billAmt = document.getElementById("billamount").value;
var serviceQual = document.getElementById("servicequality").value;
var peopleAmt = document.getElementById("peopleamount").value;
//to validate input
if (billAmt === "" || serviceQual == 0) {
alert("please enter numbers");
return;
}
if (peopleAmt === "" || peopleAmt <= 1) {
peopleAmt = 1;
document.getElementById("each").style.display = "none";
} else {
document.getElementById("each").style.display = "block";
}
// to calculate the tip
var total = (billAmt * serviceQual) / peopleAmt;
//to round to two places
total = Math.round(total * 100) / 100;
total = total.toFixed(2);
// to display tip
document.getElementById("totalTip").style.display = "block";
document.getElementById("tip").innerHTML = total;
}
document.getElementById("totalTip").style.display = "none";
document.getElementById("each").style.display = "none";
// to call function
document.getElementById("calculate").onclick = function() {
calculateTip();
};
</script>
</body>
</html>

piece of html+javascript that finds if number from an input is prime then displays the result

School project. I must design a page that contains an input box, a button that sends the entered number to the function, and a paragraph that displays the result. Here's my progress as of now, problem is it just says "false" everytime. Sorry for the triviality of the question, i'm a total newb with web coding.
<!DOCTYPE html>
<html>
<head>
<script>
function isPrime($n)
{
$i=2;
if ($n==2){
return true;
}
$sqrtN = sqrt($n);
while ($i<= $sqrtN){
if ($n % $i ==0){
return false;
}
$i++;
}
return true;
}
</script>
</head>
<body>
Value: <input type="number" id="n"><br>
<input type="submit" value="Send" onclick="isPrime(n)">
</form>
<p id="derp">sdvfsdg</p>
<script>
document.getElementById("derp").innerHTML = isPrime(n);
</script>
</body>
</html>
Basically you are setting the content of the derp once and for all before pressing the button
function isPrime($n)
{
$i=2;
if ($n==2){
document.getElementById("derp").innerHTML = "True";
}
$sqrtN = sqrt($n);
while ($i<= $sqrtN){
if ($n % $i ==0){
document.getElementById("derp").innerHTML = "False";
}
$i++;
}
document.getElementById("derp").innerHTML = "True";
}
And not sure you really need the $ everywhere - that's a PHP thing
You had not used input field value at all, that was your mistake
Value:
<input type="number" id="n">
<br>
<input type="submit" value="Sebd" onclick="x()">
</form>
<p id="derp">sdvfsdg</p>
<div id="try">jdfs</div>
<script>
function x() {
document.getElementById('derp').innerHTML = isPrime(Number(document.getElementById('n').value));
}
function isPrime(n) {
i = 2;
if (n == 2) {
return true;
}
sqrtN = Math.sqrt(n);
document.getElementById('try').innerHTML = n;
while (i <= sqrtN) {
document.getElementById('try').innerHTML = 'try';
if (n % i == 0) {
return false;
}
i++;
}
return true;
}
</script>
Here's the code that'll work for your case... You should execute the code on click AFTER entering the value
<!DOCTYPE html>
<html>
<head>
<script>
</script>
</head>
<body>
Value: <input type="number" id="n"><br>
<input type="submit" value="Send" onclick="checkPrime()"> <!--use function on click-->
</form>
<p id="derp">sdvfsdg</p>
<script>
function isPrime(num)
{
var isPrime = true; //initially set to true
for(var i=2; i<num; i++){
if(num%i == 0){ //if the num gets divide by any other number except itself
isPrime = false;
}
}
return isPrime;
}
function checkPrime(){ //function that gets called on send button click
var number = document.getElementById("n").value; //get the value of input
number = parseInt(number); //since it's a string,convert it into number
document.getElementById("derp").innerHTML = isPrime(number); //check if prime and display result
}
</script>
</body>
</html>

Javascript click counter

<HTML>
<HEAD>
<TITLE>counter </TITLE>
</head>
<body>
<script type="text/javascript">
var clicks = 0;
function linkClick(){
document.getElementById('clicked').value = ++clicks;
}
document.write('Add');
</script>
<input id="clicked" size="3" onfocus="this.blur();" value="0" >
<script type="text/javascript">
function linkClick1(){
document.getElementById('clicked').value = --clicks;
}
document.write('Subtract');
</script>
</BODY>
</HTML>
This on adds and subtracts depending on how many times its clicked i want the value not to go below 0 how to do it??
Replace:
document.getElementById('clicked').value = ++clicks;
on:
document.getElementById('clicked').value = clicks >= 0? --clicks : clicks;
This might work, if it doesn't add a comment :)
This is a more practical:
function linkClick1(){
if (clicks > 0) {
document.getElementById('clicked').value = --clicks;
}
}
function linkClick1(){
if (clicks > 0) {
document.getElementById('clicked').value = --clicks;
}
}

If length is less than 0 alert in javascript

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.

How to make the numbers automatically using jquery append ..?

Hello all I want to ask, how to make the numbers automatically using jquery append ..?
I have made ​​it but still failed
My source code is :
<html>
<head>
<title>Help Help</title>
</head>
<body>
<input type="button" id="button" value="Create a number from 1 to N"/>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function ()
{
$('#button').click(function()
{
$('#result').append('<div class="number">Numbers To ......</div>');
});
});
</script>
</body>
<hr>
results from click button
<hr>
<div id=result></div>
Here's one way of doing it:
$('#numbers').change(
function(){
var max = $(this).val();
var sequence;
for(i=0; i<=max; i++) {
var text = $('#result').text();
if (text == false){
text = i;
}
else if (i == max) {
text = text + ', ' + i + '.';
}
else {
text = text + ', ' + i;
}
$('#result').text(text);
}
});
$('form').submit(
function(){
return false;
});
With the following, simplified, html:
<form action="#" method="post">
<label for="numbers">Make a sequence of numbers, from one to <em>n</em></label>
<input type="number" min="0" max="1000" step="1" id="numbers" name="numbers" />
</form>
<div id="result">
</div>
JS Fiddle demo.
Edited to offer a more concise version of the above jQuery code, as offered by mplungjan (in comments, below):
$('#numbers').change(
function(){
var max = $(this).val(),text="";
for(i=1; i<=max; i++) {
text += ', ' + i;
}
if(text) $('#result').text(text.substring(2)+".");
});
$('form').submit(
function(){
return false;
});
Revised/optimised jQuery at JS Fiddle
Answer convertd to community wiki, since earning rep from someone else's efforts just seems wrong....

Categories

Resources