Can someone help me in jquery addition? - javascript

I would like to give points to my users who submit articles based on their articles word count.
But my page has many text area fields. Lets say message1,message2,message3
When the user fill textarea(message1,message2,message3) it will show like this in the bottom.
You have typed x words. Points per word : 0.2. Estimated point: xx
I also want to calculate overall points. So i would like to add points of message1,message2,message3 and display it as overall points.
I'm a jquery noob. So i'm not sure which variable i should call.
Here is the jfiddle code what i have so far.
Can someone help me? Thanks

you can declare a variable to save the value of each word count (initialized in 0):
var count1 = count2 = count3 = 0;
And then do something like:
count1 = data.words;
$('#showData4').html((count1+count2+count3)*0.2);
For each $('#testTextarea').textareaCount() you have, as you can see on this jsfiddle

Your first problem is that you're not storing the scores from the individual text area fields so you have no values to add up for the total score. After you start storing this data, you just have to update the total score area when any of the individual scores change.
Check out this fiddle: http://jsfiddle.net/NFDQ3/6/

Keep the count of every Textfield in an array that you can use to compute the overall sum.
I've edited your code, see the demo here: http://jsfiddle.net/yZb7w/38/

Another solution would be to have something like:
$('#testTextarea3').textareaCount(options3, function(data){
$('#showData3').html("You have typed <b>" + data.words + "</b> words. Points per word : <b> 0.2</b>. Estimated point: <b>" + (0.2 * data.words) +"</b>");
$(this).data("points",(0.2 * data.words));
});
This will store the points value per testTextarea. The next step you will do is have a totalScore textarea or some updating behavior for some component and extract stored scored from all the textAreas like:
$('#testTextarea3').data("points");

You could trigger an event from inside getInfo, then bind to that event from outside your plugin to get the updated count from each textarea. Then, it's just a matter of keeping track of each count and adding them up. See jsfiddle (info object will be logged to the console).

Related

Javascript Random Guess Game

https://jsfiddle.net/andrew_jsfiddle/eyLyqajz/1/
Assignment 1 - Using your JSFiddle account you are going to create a guessing game, only it will be the computer doing the guessing. Here is how it works - the computer will ask you for a number between 1 and 1000, it will check first to make sure your input is within the bounds.
Once you enter the number it will guess the number and do a comparison with the number you entered. It will output the results of the guess and continue to do this until it gets the correct answer. This is what the output of the program will look like (if I enter 329)
For this attempt I did:
var guessnum= new Guessnum(1000);
document.getElementById("click").onclick= function() {
guesslist()};
function guesslist() {
document.getElementById('guessnum').innerHTML= InsertGuess();
}
function InsertGuess() {
for (var a= 0; a < guessnum.length; a++){
guessnum[a] = Math.floor((Math.random() * 1000) + 1);
}
var show_guess="";
for (i=0; i < guessnum.length; i++){
show_array += "You guess" + guessnum[i] + "of " + i + "<br>";
}
return document.getElementById('guess').innerHTML=show_array;
}
Use a listener on the input with a global variable that contains the random number
var myRandomNumber;
input.addEventListener('input', function(){
}
)
You'll need to click first on the button though.
Fiddle
My friend, I think you are really confused. It wouldn't help to just create it for you. Break down the requirements to actionable steps and start from scratch. You want to create a guess game that you set a number. Think it as simply as possible:
Action 1 - Set a number -->
Create the field
Action 2 - Check if number is valid(1-1000) -->
Get the value entered and make the necessary checks
Action 3 - Computer tries to guess by selecting a num up to 1000 -->
Generate random num from 1-1000
Action 4 - Compare number with the one you set before -->
Simple comparison of generated number and the selected one
Action 5 - Proceed as needed -->
If it's the exact number it won and it will stop!
If it's higher then the next guesses should have this number as highest limit.
If it's lower then the next guesses should have this number as lowest limit.
Action 6 - Show guess and result of comparison --> Simply show the results of the previous actions
Action 7 - If not successful guess --> repeat until the number is guessed
Try to apply this kind of logic to all these problems.

jQuery calculation updating one row at a time

So, I'm trying to create a small table for working out the potential winnings of betting on a rubber duck race when each duck has certain odds.
I sort of have this working but have hit a stumbling block...
When the page loads all of the maths is done correctly based on the default value of £10. What I then want to do is allow people to change the amount of money they would like to bet per duck and the potential winnings for that duck only updates automatically.
This is what I have so far:
function calculate_odds(row) {
var winnings = 0;
// Set winnings to 0
var odds = $(row).find('#theodds').attr('data-duckodds'),
// Find the value of the data attribute for a specific td
betting_amount = $('[name="betting-amount"]').val(),
// Find the value entered into an input field
winnings = (parseFloat(odds) / 1 + 1) * betting_amount;
// Work out the winnings based on the odds given.
// Divide first number by 1 as all odds are something to 1 for now, then +1
// Multiply that number by the bet
// For example Bet 30 on 3/1 odds
// 3 / 1 = 3 + 1 = 4 * 30 = 120
$(row).find('.js-winnings').html(winnings.toFixed(2));
// Show the winnings amount in the final td in each row
}
$(document).ready(function() {
$('.lineup tbody tr').each(function() {
// Run the function calculate_odds() initially based on the default value;
calculate_odds();
$(this).find('[name="betting-amount"]').on('keyup', function() {
// Now loop through each row and change the winnings amount if the betting amount is changed
calculate_odds($(this).closest('tr'));
}).trigger('keyup');
})
});
From what I understand (my jQuery is not great), within this line: $(this).find('[name="betting-amount"]').on('keyup', function() { all I should need to do is select the specific row I want to update. Which should be simple right?
Instead what this does is takes the updated value from the first row and then applies as that as you change the later rows.
Can anyone point our where I'm going wrong? You can see the calculator here: http://www.kb-client-area.co.uk/ducks/races/race-1/
Thanks in advance :)
The specific problem you're encountering is where you're setting betting_amount:
betting_amount = $('[name="betting-amount"]').val()
You're looking globally in the document, and so finding the first instance.
Switching it to this makes it work:
betting_amount = $(row).find('[name="betting-amount"]').val()
As an aside: it would be better to use a class instead of an ID for #theodds, as IDs are supposed to be unique per document :)
I think perhaps your 'this' isn't referring to what you think it is in this line: calculate_odds($(this).closest('tr'));
Could you try something along the lines of:
$(this).find('[name="betting-amount"]').on('keyup', function(e) {
// Now loop through each row and change the winnings amount if the betting amount is changed
calculate_odds($(e.target).closest('tr'));
}).trigger('keyup');
})
As I said earlier, element IDs must be unique in a given document. You have the id theodds repeated as many times as the number of rows in your table which makes your HTML invalid! Remove those IDs and you could just work around the data-* that you already have.
function calculate_odds(row) {
row = $(row);
var winnings = 0,
//find the data-* from within the context of the keyup - the row
odds = row.find('[data-duckodds]').attr('data-duckodds'),
//find the entered amount from within the context of the keyup - the row
betting_amount = row.find('[name="betting-amount"]').val(),
//Your math
winnings = (parseFloat(odds) / 1 + 1) * betting_amount;
row.find('.js-winnings').html(winnings.toFixed(2));
}
$(document).ready(function() {
//You don't need an each loop here as the keyup will be triggered on every amount box on load as well.
$('.lineup').on("keyup", "[name='betting-amount']", function() {
calculate_odds($(this).closest('tr'));
})
.find("[name='betting-amount']").keyup();
});
Take a look at this fiddle for a demo.

Meteor: How to set a number based on the number of checked boxes within a section

I currently have a multi-section form, with a number of checkboxes. What Im trying to do, is show the number of checked boxes, next to the total. I have total showing up just fine, but I cant for the life of me figure out a way to loop over the inputs, successfully find the :checked, and print that number out.
I think the main thing causing me issues, is that it needs to update every time a new box is checked. Heres some of the code.
Event Handler
'click input[type=checkbox]': function(){
Session.set('selectedPlayerCount', n);
Session.get('selectedPlayerCount');
}
The goal here is to set the number of selected players, and pass it to the template/helper.
Helper
countSelected: function(){
n = 0;
n++;
var selectedPlayerCount = Session.get('selectedPlayer');
return selectedPlayerCount;
}
Within the helper I'm attempting to iterate every time the event is triggered, and as a result increase the value by one. I'm aware that resetting n back to 0 is going to cause some issues, and I know that needs to be changed one the rest is figured out. I just cant figure out where the variable needs to be set in order to provide a default value.
Template
<header>
<p>{{ countSelected }}</p>
</header>
All I'm trying to do here for now is to print out the value rendered by the helper. I don't believe this is causing any issues.
TL;DR - How to count number of checked inputs within a section of a form, and for each one, increment a value, and then return it every time its changed.
I'm new to this but maybe this will serve: define your account to zero in a session variable, each time you select a checkbox you increase the value of your session variable
Session.set("countPlayersChecked", 0);
Template.proof.helpers({
countSelected: function () {
return Session.get("countPlayersChecked");
}
});
Template.proof.events({
'click input[type=checkbox]': function (event) {
if($(event.target).is(':checked'))
Session.set("countPlayersChecked", Session.get("countPlayersChecked")+1);
else
Session.set("countPlayersChecked", Session.get("countPlayersChecked")-1);
}
});
Hope it serves.

attribute maxlength of input field is changing, but input doesn't care

I have a function to limit the number of characters that a user can type into an input field for my game. It works, except that if it goes down by 1 or more in length, the user can still enter 1 or more characters than they should be able to.
I check the inspector, and it even shows maxlength changing correctly. However, for whatever reason, it still lets the user enter in a length equal to the max number of characters that the variable was equal to during the same session. Is it a bug? Any way to get it working correctly?
my_var = 150000; //this var changes often, can go down to 0 or up to 1000000000
function limitNumberOfCharacters() {
x = my_var.toString().length;
$('.my_input_class').attr('maxlength', x);
}
limitNumberOfCharacters(); //this gets called often
EDIT: http://jsfiddle.net/mDw6f/
EDITTTT:
You are using x as a global variable and is probably getting changed from something else in your code. Use var x = my_var.toString().length; (emphasis on var)
Honestly after seeing this code I was afraid there would be many more underlying problems but all I did was add var before the xyz and it works just as you want it to.
Also fixed the issue of the previous bet amount returning to the input field. It now results to a blank field.
Cheers
Real Fiddle Example
Try using this fiddle:
Working Demo
Use the html input like I did in the code, no need to specify the maxlength attribute to it.
<input type="text" class="my_input_class"/>
and the script
my_var = 25; //this var changes often, can go down to 0 or up to 1000000000
function limitNumberOfCharacters() {
x = my_var.toString().length;
$('.my_input_class').attr('maxlength', x);
}
limitNumberOfCharacters();

Javascript time helper? -Interesting problem!

I am new to the world of javascript and even trying google search has not really helped me find what I am looking for.
So I have come here in the hope you can point me in the right direction.
RULE= It must not be click! Can be done by tabbing!
I have many text fields which the user will input times that have been recorded.
E.g. Event 1 happened at 11:31am
Event 2 happened at 11:59am
I want to make this process as easy as possible for the user by having the textbox formatted in hours and seconds in 24hr format:
So the textbox value= 00:00 and when the user selects the text box they can enter the hours part. Then it will jump to the seconds part.
Any idea if there is something that can do that if so could you link me. If not could you give me an idea of what the coding will be like and if there are easier alternatives.
I have made some pseudo code to help you understand my implementation goal:
for count = 0 , while count is less than 20, count++
{
create a texbox with name time+count, set the value to ="00:00"
}
when the user enters numbers they go into the hour segment until that is completed
the script then jumps the cursor to the minutes segment
if time+count+1 is lesser thatn time+count message user that time error "An event cannot occur before the previous event"
Thankyou for hearing me out!
I don't really know of any time pickers that would suit your needs, but here's a basic idea of how one would be implemented:
You have two textboxes, or multiple pairs of textboxes
In each textbox, you put an event handler to handle "onkeyup" event
In onkeyup handler, check if lenght of text in box is 2
If length is 2 -> focus the next textbox
This way the user can simply keep on typing the numbers.
You may need to add some additional checks into the event listener, for example to make sure that if the user comes back to the field, they can edit it easily (eg. if they press shift-tab, it won't focus an incorrect field)
If you wanted to be really fancy, you could have a single textbox for times. Then, each time user presses a key, you'd check if it's a number. If user first types two numbers, it would then insert a : as the separator if the third key is a number, and so on.
This might be a beginning. Using jQuery this is not such a painful task.
http://jsfiddle.net/sArjQ/
for(var i = 0; i < 20; i++) {
var input = $("<input>", { name: 'time' + i, // create input element
val: '00:00' });
input.click(function() {
$(this).prop({ selectionStart: 0, // move caret to beginning on click
selectionEnd: 0 });
}).keydown(function() {
var sel = $(this).prop('selectionStart'),
val = $(this).val(),
newsel = sel === 2 ? 3 : sel; // so that it moves two positions for :
$(this).val(val.substring(0, newsel) // automatically set value
+ val.substring(newsel + 1))
.prop({ selectionStart: newsel, // move caret along
selectionEnd: newsel });
});
$('body').append(input);
}

Categories

Resources