I'm just learning the basics of javaScript and jquery and have tried to put together this simple program http://codepen.io/mike-grifin/pen/oXjVYW. It's simply a box that displays a number and there is two buttons, one adds 10 and the other button subtracts 10. Ive set the output to alert and it seems to be working fine but if I remove the alert (below) it's not inputting the results into the container div.
$(document).ready(function(){
var startPoint = +90;
$(document).find('#container').append(startPoint);
if($('.increase').click(function(){
startPoint += +10;
}));
I've also tried to append the startPoint var again but it doesn't overwrite the original:
$(document).ready(function(){
var startPoint = +90;
$(document).find('#container').append(startPoint);
if($('.increase').click(function(){
startPoint += +10;
$(document).find('#container').append(startPoint);
}));
All the code is at the codepen link. I'm just learning so sorry if it's really obvious or easy. Any educational input or advice would be greatly appreciated. Thanks.
That's because you're appending the value to the #container element. If you want to directly alter the text, you can use jQuery's text() method:
$(document).find('#container').text(startPoint);
CodePen Demo
This will overwrite the current text with the new text you're passing in.
.text(text)
Set the content of each element in the set of matched elements to the specified text.
– jQuery's text() documentation
It's worth also noting that your if (startPoint >= 100) check will only be executed when your CodePen demo first loads. If you want to use this check, you'd need to place the if statement within your click event handlers.
You need to remove the contents before appending
i used empty()
$(document).ready(function(){
var startPoint = 90;
$('#container').empty().append(startPoint);
if($('.increase').click(function(){
startPoint += 10;
$('#container').empty().append(startPoint);
}));
if($('.decrease').click(function(){
startPoint -= 10;
$('#container').empty().append(startPoint);
}));
if(startPoint >= +100){
$('#container').empty().append(startPoint);
}
});
first of all .. for div you can use .text() or .html()
2nd .. move your if statement into .increase click event
$(document).ready(function(){
var startPoint = +90;
$(document).find('#container').append(startPoint);
$('.increase').on('click',function(){
if(startPoint >= +100){
alert('dayum!!');
}else{
$('#container').text(startPoint += +10);
}
});
$('.decrease').on('click',function(){
$('#container').text(startPoint -= +10);
});
});
You need to either set the .text() of the #container to the new value, or .empty() the old data out of it before you .append() any more.
$('.increase').click(function(){
$('#container').text(startPoint += +10);
});
Also, you don't need to wrap the $('.increase').click() in an if
It will fire when it is clicked, you don't need to say "if (this is clicked)"
It is implied by the .click() function
Read this : http://www.w3schools.com/jquery/html_html.asp And
.html() and .append() without jQuery
$(document).ready(function(){
var startPoint = +90;
$(document).find('#container').append(startPoint);
if($('.increase').click(function(){
alert(startPoint += +10);
$("#container").html(startPoint) //added
}));
if($('.decrease').click(function(){
alert(startPoint -= +10);
$("#container").html(startPoint) //added
}));
if(startPoint >= +100){
alert('dayum!!');
}
});
use this code, this helps you :)
Related
How to 1) get and 2) output the current value of my odometer on button click? The snipet which should do that is at the bottom of the JavaScript but it does not work.
My code: https://jsfiddle.net/aht87opr/8/
Documentation of odometer might come in handy:
http://brock-family.org/gavin/software/web/odometer.html (where it says "Get the current value from the odometer: val = myOdometer->get();")
//My attempt to output the current value from the odometer:
$('button').click(function() {
n = myOdometer.get();
return n;
});
You should just use myOdometer.get(), which already gives you the number you are looking for.
If you want to put the value inside the #value element you can use the following:
$('button').click(function() {
var mefedron = myOdometer.get();
$('#value').text(mefedron);
});
Here is the fix in your jsfiddle:
https://jsfiddle.net/aht87opr/14/
Here's a working fiddle - https://jsfiddle.net/6abu3ruf/ (you'll have to fix the CSS)
There are two issues with the fiddle you shared:
You don't have to do mefedron.val();, mefedron has the value you are looking for.
You are not setting that value anywhere.
So basically, just change your onclick to:
$('button').click(function() {
var mefedron = myOdometer.get(n);
$("#value").text(mefedron);
});
I tried your code and confirm(Math.floor(mefedron*10)); works.
$('button').click(function() {
var mefedron = myOdometer.get(n);
confirm(Math.floor(mefedron*10)); // it works
function number() {
return mefedron.val();
}
number();
});
So, if you just want to return the odometer, then on the button click event just return Math.floor(mefedron*10);
To display it on div#value, $("div#value").html(Math.floor(mefedron*10));
just update your button event handler with the following:
$('button').click(function() {
var mefedron = myOdometer.get(n);
mefedron= Math.round(mefedron * 100) / 100
$("#value").text(mefedron)
});
Here is a working version of the code hosted on jsFiddle jsFiddle
I'm creating a <table> element in the DOM and using javascript to dynamically append many cells to it. For the sake of explanation let's say I create 10 rows with 10 fields per row. I'm using simple counters to assign unique IDs for the div containers inside of those fields. Easy enough. This is what I get:
<table>
<tr><td><div id="field0"><div id="handle0"></div></div></td></tr>
.....
<tr><td><div id="field99></div id="handle99"></div></div></td></tr>
</table>
Note that the numbers 0-99 are what is dynamically appended to each element ID.
I now want to go ahead and attach the jQueryUI .draggable function to each handle and retrieve the coordinates of each handle relative to each surrounding parent div like so:
for (var counter = 0; counter < 100; counter++) {
var dragHandle = $('#handle' + counter);
var dragField = $('#field' + counter);
dragHandle.draggable({
containment: dragField,
scroll: false,
drag: function () {
var offset = $(this).offset();
var xPos = (offset.left) - $(this).offsetParent().offset().left;
var yPos = (offset.top) - $(this).offsetParent().offset().top;
console.log(xPos);
console.log(yPos); // These add up?!
}
});
}
Now, the functions work, the table gets properly initialized and all of the individual handles in the table are now draggable.
The problem is that the xPos and yPos values that are returned by the above function are not the correct coordinates relative to each field but instead they add up.
I feel like I'm missing something terribly obvious and would really appreciate if someone could help.
Edit: The example above uses console.log for simplification. My original script performs more complex computations in the on drag event. I won't be able to use a class selector to go through all of the elements like someone suggested in the comments because I need to retrieve unique offset and position values for each unique handle ID relative to its unique containment ID.
var xPos=(offset.left)-$(this).position( ).left
var yPos=(offset.top)-$(this).position( ).top
Instead of offsetParent you can modify.
var xPos = (offset.left) - $(this).parent().offset().left;
var yPos = (offset.top) - $(this).parent().offset().top;
I have a span field that has a number generated by counting items in a session array. when a user adds an item to the cart I need to increment this value by 1. I've tried the parseInt function but it doesn't seem to work. console shows the id is being selected. Just can't seem to increment by 1.
jQuery code is:
var checkout_number = parseInt($('#checkout-count').html());
console.log(checkout_number); // Shows value 2 etc
upon success increment by current checkout_number by 1:
$.parseInt($("#checkout-count").val(),10) + 1;
Any help would be great
In your example you're not actually incrementing the HTML value of the checkout-count element - try this instead:
// use the HTML of the checkout-count span as the current checkout number
var checkout_number = parseInt($('#checkout-count').html(), 10);
// replace the HTML of the checkout-count span with the old value plus one
$('#checkout-count').html(checkout_number + 1);
You need to use parseInt function to adding the value in jquery
var checkout_number = parseInt($('#checkout-count').text(), 10);
$('#checkout-count').text(checkout_number + 1);
Try this this works fine.
$('#checkout-count').text(parseInt($("#checkout-count").text()) + 1);
Working Demo
$(function() {
$('#checkout-count').text(function() {
return +(this.innerHTML) + 1;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span id="checkout-count">2</span>
I am having some issues, and cannot solve this, since I cannot get my head around this. It's kinda a big issue. I want to dynamically attach a char limit and a submit comment button to each post, and each commentArea to be a form of its own. Any help is welcome, I want to make it dynamic, independent from each other.
Thanks!
$(".comment-box").keyup(function(){
var text_max = 140;
var length_reached = $(this).val().length;
var remaining = text_max - length_reached;
$('.counter').html(remaining);
if(remaining < 5 || remaining > text_max)
$(".btn").prop("disabled", true);
else
$(".btn").prop("disabled", false);
});
Here's my jsfiddle: http://jsfiddle.net/3sCfG/25/
EDIT: Trying to make something similar to Twitter's Reply section which is attached to each micropost on their Timeline, but not sure if IDs should be used, found IDs on Twitter's, but not fully clear. I am trying to make a similar comment box to that of Twitter's.
have a look here: http://jsfiddle.net/3sCfG/38/
CODE
$(".comment-box").keyup(function () {
var parent = $(this).parent();
var text_max = 140;
var length_reached = $(this).val().length;
var remaining = text_max - length_reached;
$(parent).find('.counter').html(remaining);
if (remaining < 5 || remaining >= text_max)
$(parent).find(".btn").prop("disabled", true);
else
$(parent).find(".btn").prop("disabled", false);
});
hope it helps
EDIT cleaned up code a little
Your problem is using classes (hence affecting multiple elements) without specifying which part of the DOM you're trying to update.
The simplest solution is to add a "search context" to the selectors in your handler.
I've used $(selector, parent) as a shorthand for $(parent).find(selector):
$(".comment-box").keyup(function() {
var parent = this.parentNode; // new
var text_max = 140;
var length_reached = this.value.length;
var remaining = text_max - length_reached;
$('.counter', parent).html(remaining);
$('.btn', parent).prop('disabled', (remaining < 5 || remaining >= text_max));
});
I've also refactored the .prop call, since:
if (condition) {
.prop('disabled', true);
} else {
.prop('disabled', false);
}
is exactly equivalent to:
.prop('disabled', condition);
and I changed the > text_max to >= text_max, since I presume the intent was to disable the "submit" button if there's no input.
See http://jsfiddle.net/alnitak/ATW9u/
Maybe add a data- attribute to text area and use that to set the max length?
<textarea class="comment-box" type="text" data-limit="10" placeholder="Write a comment"><textarea>
along with that, instead of referring to the counter with its class, navigate to it and reduce the no. of characters from it. (Like this)
$(this).next(".tools").find("span").html(remaining);
Gives the textareas the inpedendance you wanted to give them. Heres your updated fiddle : http://jsfiddle.net/3sCfG/28/
This may have been answered before, but I cannot find a solution that works.
I need to add the subtotal input boxes up and output them as a grandTotal. Sounds simple, and I thought it would be, but for some reason I cannot get it to function properly.
To save time I have created a jsFiddle - http://jsfiddle.net/wgrills/hKxgU/4/
Edit: Sorry to be poor at posting the question.
I missed out most of the items because I wanted to speed the jsfiddle up. I have updated the jsFiddle - http://jsfiddle.net/wgrills/hKxgU/7/.
If you click on the + or - buttons the subtotal changes, that is all good. But I can't get the #grandTotal input to update. The problem appears to be with the:
var grandTotal = 0;
$(".subtotal").each(function() {
$(this).css("border-color","#f00");
grandTotal += $(this).val.split("£")[1];
});
$("#grandTotal").val("£" + grandTotal);
alert(grandTotal);
part of the js. Note the css border change and the alert is just there for me to make sure the script is working.
The code is all early days, this is just a quick mock up.
You gave two problems, very easy to solve!
You are correct that the piece above that you posted is part of the problem. In particular the line:
grandTotal += $(this).val.split("£")[1];
You missed the () after val, so the code WOULD have broken here, because it doesn't know what .val. is.
Also, the code you posted was after a return false; this effectively tells the function is has finished, don't bother doing anything after that line.
However, as you need that section of code in both functions (clicks) its worth wrapping it in a function of its own:
function updateGrandTotal() {
var grandTotal = 0;
$(".subtotal").each(function() {
$(this).css("border-color", "#f00");
grandTotal += parseFloat($(this).val().split("£")[1]);
});
$("#grandTotal").val("£" + grandTotal);
alert(grandTotal);
}
And calling it just before you inform the function its finished:
updateGrandTotal();
return false;
See it partially working here
However, while this will work on the plus of an item, you have another problem, when you are minusing an item, and the box gets to zero, instead of setting £0.00 you set it to 0, hence when it try's to split on the "£" it can't. To combat this simply copy the bit where you turn your price value into a price from the plus function into the minus function:
Replace:
newprice = price * x;
$('#' + update).val(x);
$('#' + update + '_subtotal').val(newprice);
With the working version:
newprice = (price * x) / 100;
newprice = newprice.toFixed(2);
newprice = '£' + newprice;
$('#' + update).val(x);
$('#' + update + '_subtotal').val(newprice);
See it fully working here
Your problem is with the following line:
grandTotal += $(this).val.split("£")[1];
val is a function, not a property on the returned object. You want the following instead:
grandTotal += $(this).val().split("£")[1];
Also in your fiddle you have a return false; in the middle of your function, which lies above the code you're calling val incorrectly on. Remove that return as well.