I'm trying to grab the article elements id value for all the article elements one by one so I can add it to the
countCharacters() function so I can have a unique character count for each textarea but both my jquery functions dont seem to work correctly. For example my character count should look something like this.
countCharacters('#comment-1535 .review-info', '#comment-1535 .review-info + div .count', 5000);
countCharacters('#comment-553 .review-info', '#comment-553 .review-info + div .count', 5000);
countCharacters('#comment-6547 .review-info', '#comment-6547 .review-info + div .count', 5000);
Here is my JSFiddle https://jsfiddle.net/jm52wg9k/
HTML
<article class="review" id="comment-1535">
<div class="review-details">
<div class="review-stats">
<!-- content -->
</div>
<form method="post" action="" class="review-form">
<fieldset>
<ol>
<li><label for="review-info">Review Info:</label></li>
<li><textarea name="review_info" class="review-info"></textarea><div class="some"><span class="count"></span></div></li>
</ol>
</fieldset>
<fieldset>
<ol>
<li><input type="submit" name="submit_review" value="Submit Review" class="submit-review" /></li>
</ol>
</fieldset>
</form>
</div>
</article>
<article class="review" id="comment-553">
<div class="review-details">
<div class="review-stats">
<!-- content -->
</div>
<form method="post" action="" class="review-form">
<fieldset>
<ol>
<li><label for="review-info">Review Info:</label></li>
<li><textarea name="review_info" class="review-info"></textarea><div class="some"><span class="count"></span></div></li>
</ol>
</fieldset>
<fieldset>
<ol>
<li><input type="submit" name="submit_review" value="Submit Review" class="submit-review" /></li>
</ol>
</fieldset>
</form>
</div>
</article>
<article class="review" id="comment-6547">
<div class="review-details">
<div class="review-stats">
<!-- content -->
</div>
<form method="post" action="" class="review-form">
<fieldset>
<ol>
<li><label for="review-info">Review Info:</label></li>
<li><textarea name="review_info" class="review-info"></textarea><div class="some"><span class="count"></span></div></li>
</ol>
</fieldset>
<fieldset>
<ol>
<li><input type="submit" name="submit_review" value="Submit Review" class="submit-review" /></li>
</ol>
</fieldset>
</form>
</div>
</article>
Jquery
$(document).ready(function() {
function countCharacters( input, output, max ) {
var $input = $(input);
var $output = $(output);
$output.text(max + ' characters left');
$input
.keydown(function(event) {
if (event.keyCode != 8 &&
event.keyCode != 46 &&
$input.val().length >= max)
event.preventDefault();
})
.keyup(function() {
var val = $input.val().slice(0, max);
var left = max - val.length;
$input.val(val);
$output.text(left + ' characters left');
});
}
countCharacters(reviewInfo() + '.review-info', reviewInfo() + '.review-info + div .count', 5000);
});
$(document).ready(function(){
function reviewInfo(){
var review = $('.review-info').closest('article').attr('id');
var review2 = '#' + review;
return review2;
};
});
CSS
*{
border: 0;
margin: 0;
padding: 0;
}
article{
margin-top: 1em;
}
textarea{
width: 90%;
}
input{
margin: 1em 0;
color: #fff;
background: green;
padding: .5em;
}
DEMO
Your code was fine but the way you were implementing it wasn't proper. Below changes I have made to your code.. See inline comments for more details
function countCharacters(input, output, max,event) {
//Only changes here is I removed .keyup and .keydown which I've binded outside
var $input = $(input);
var $output = $(output);
if (event.keyCode != 8 && event.keyCode != 46 &&
$input.val().length >= max)
event.preventDefault();
var val = $input.val().slice(0, max);
var left = max - val.length;
$input.val(val);
$output.text(left + ' characters left');
}
$(".review-info").on('keyup keypress',function(event){
var _this=$(this);//key up and key press out side document.ready
var _thisCount=_this.next('.some').find('.count');
//find the span using current control's next .some div and its child .count
var max=5000; //also you can add as an data-* attribute to your controls
countCharacters(_this,_thisCount,max,event);//call the function with necessary params
})
Related
I'm relatively new to HTML and I want to create a form so that the user can get a customized output based on their answers. I have a basic form with button inputs, with multiple tabs of buttons. Is there some way for me to collect the data that the user selects by pressing multiple buttons, and assign it to a js variable? This is the code I have so far.
<!DOCTYPE HTML>
<html>
<head>
</head>
<style>
/* Hide all steps by default: */
.tab {
display: none;
}
#myButton {
padding: 0;
border: none;
background: none;
font-family: monospace;
font-size: 25px;
margin-right: 2%;
transition: margin-left 1s;
}
#myButton:hover {
color: rgb(77, 77, 77);
padding-left: 1%;
}
#main {
padding-bottom: 25vh;
padding-top: 25vh;
padding-left: 5%;
padding-right: 5%;
}
/* Header */
#heade {
position: fixed;
top: 0;
left: 0;
width: 100%;
background: #0F1116;
color: #fff;
padding: 3.25em 1.5em 1.5em 1.5em;
z-index: 100;
}
header {
padding-bottom: 30px;
margin-top: -3px;
padding-right: 80%;
}
</style>
<body>
<form id="regForm" style="text-align: center;" method="GET">
<!-- One "tab" for each step in the form: -->
<div class="tab">
<input onmousedown="myFunction()" name="qty" type="button" value="3" onclick="nextPrev(1)" id="myButton">
</div>
<div class="tab">
<ul style="list-style-type:none;">
<li><input name="qty" type="button" value="3" onclick="nextPrev(1)" id="myButton"></li>
<li><input type="button" name=parameter value="Click me" onclick="nextPrev(1)" id="myButton"></li>
<li><input type="button" value="Click me" onclick="nextPrev(1)" id="myButton"></li>
</ul>
</div>
<div class="tab">
<ul style="list-style-type:none;">
<li><input name="qty" type="button" value="3" onclick="nextPrev(1)" id="myButton"></li>
<li><input type="button" value="Click me" onclick="nextPrev(1)" id="myButton"></li>
</ul>
</div>
<div class="tab">
<ul style="list-style-type:none;">
<li><input name="qty" type="button" value="3" onclick="nextPrev(1)" id="myButton" class="ug"></li>
<li><input type="submit" value="Click me" onclick="nextPrev(1)" id="myButton" class="ug"></li>
</ul>
</div>
<div style="overflow:auto;"></div>
<div style="text-align:center;">
<!-- Circles which indicates the steps of the form: -->
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
</div>
</div>
</form>
</body>
<script>
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab
function showTab(n) {
// This function will display the specified tab of the form...
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
//... and fix the Previous/Next buttons:
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
document.getElementById("nextBtn").innerHTML = "Submit";
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
//... and run a function that will display the correct step indicator:
fixStepIndicator(n)
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("tab");
// Exit the function if any field in the current tab is invalid:
if (n == 1 && !validateForm()) return false;
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form...
if (currentTab >= x.length) {
// ... the form gets submitted:
document.getElementById("regForm").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
</script>
</html>
There may be some extra code in there as this is part of a larger webpage.
I have a bunch of input elements and with javascript on click i'm getting the values of these inputs and paste it in a div somewhere
Please run the code snipped below to check
$('#getthelist').click(function() {
$('.inputs>li .color').map(function() {
return {
name: this.closest('[id]').id,
value: $(this).val()
}
}).get().forEach(function(e) {
$('.list').append('<div>' + '\"' + e.name + '\": \"' + e.value + '\",</div>');
});
});
ul,li {
list-style: none;
margin: 0;
padding: 0;
}
.list {
margin: 10px;
width: 270px;
padding: 25px;
background-color: #fafafb;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li id="color_white">
<ul class="inputs">
<input type="radio" value="getthelist" id="getthelist"> Click to get the color values
<li id="color_white">
<div>
<input type="text" value="#fff" class="color">
</div>
</li>
<li id="color_black">
<div>
<input type="text" value="#000" class="color">
</div>
</li>
</ul>
<div class="list"></div>
So i have got one question and a problem i cant figure out how to fix.
The problem is, each time you click the button it pastes the values in the div repeatedly. It is a mess to me for what i'm trying to do. so, How do i force it not to repeat the same values when you click every time.
Question: How do i copy the input values to clipboard with the same click function?
Please check my snippet codes.
function copyToClipboad(texts) {
var textareaElCloned = $('<textarea>' + texts + '</textarea>');
$('.list').append(textareaElCloned);
/* Select the text field */
textareaElCloned[0].select();
/* Copy the text inside the text field */
document.execCommand("copy");
}
$('#getthelist').click(function() {
var html = '';
var texts = '';
var itemEls = $('.inputs > li .color');
itemEls.map(function() {
return {
name: this.closest('[id]').id,
value: $(this).val()
}
}).get().forEach(function(e, index) {
var text = '\"' + e.name + '\": \"' + e.value + '\",';
texts += text;
html += ('<div>' + text + '</div>');
if (index === itemEls.length-1) {
copyToClipboad(texts);
}
});
$('.list').html(html); // the textarea will be removed at this moment
});
ul,li {
list-style: none;
margin: 0;
padding: 0;
}
.list {
margin: 10px;
width: 270px;
padding: 25px;
background-color: #fafafb;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li id="color_white">
<ul class="inputs">
<input type="radio" value="getthelist" id="getthelist"> Click to get the color values
<li id="color_white">
<div>
<input type="text" value="#fff" class="color">
</div>
</li>
<li id="color_black">
<div>
<input type="text" value="#000" class="color">
</div>
</li>
</ul>
<div class="list" tabindex="1"></div>
save your data in localStorage.setItem (return value of .map must save in localstorage)
get your data with localStorage.getItem (get data from localstorage with key that you set for item)
create a template with handlebar.js, and when click on checkbox, render template with data that get from localstorage.
for new data, you must update localstorage.
I have tested the solution from Dipak chavda but it does not work for me also. The problem is that the input is type of hidden. So I changed it to hidden textarea. When you try to copy, I make it visible for a while, focus it, select it's value and then exec the copy. And it works ;)
function copyData(copyText) {
var $txtCopyArea = $("#txtCopyArea");
// set the text as value
$txtCopyArea.val(copyText);
// make textarea visible
$txtCopyArea.removeClass('hidden');
/* focus & select the text field */
$txtCopyArea.focus().select();
/* Copy the text inside the text field */
document.execCommand("copy");
/* Alert the copied text */
alert("Copied the text: " + copyText);
// hide textarea
$txtCopyArea.addClass('hidden');
}
$('#getthelist').click(function() {
// Clear html div content
$('.list').html("");
var copyText = "";
$('.inputs>li .color').map(function() {
return {
name: this.closest('[id]').id,
value: $(this).val()
}
}).get().forEach(function(e) {
var _data = '<div>' + '\"' + e.name + '\": \"' + e.value + '\",</div>';
$('.list').append(_data);
copyText += _data;
});
copyData(copyText);
});
ul,
li {
list-style: none;
margin: 0;
padding: 0;
}
.list {
margin: 10px;
width: 270px;
padding: 25px;
background-color: #fafafb;
}
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li id="color_white">
<ul class="inputs">
<input type="radio" value="getthelist" id="getthelist"> Click to get the color values
<li id="color_white">
<div>
<input type="text" value="#fff" class="color">
</div>
</li>
<li id="color_black">
<div>
<input type="text" value="#000" class="color">
</div>
</li>
</ul>
<textarea id="txtCopyArea" class="hidden"></textarea>
<div class="list"></div>
I tried to give you both questions answer.
Answer of Q1
you should reset HTML content before set new value.
Answer of Q2
you should use document.executeCommand("copy") to copy the text.
Hope it may help to resolve your issue.
function copyData(copyText) {
$("body").append($("<textarea/>").val(copyText).attr({id:"txtareaCopyData"}));
var copyText = document.querySelector("#txtareaCopyData");
copyText.select();
document.execCommand("copy");
$("#txtareaCopyData").remove();
}
$('#getthelist').click(function() {
// Clear html div content
$('.list').html("");
var copyText = "";
$('.inputs>li .color').map(function() {
return {
name: this.closest('[id]').id,
value: $(this).val()
}
}).get().forEach(function(e) {
var _data = '<div>' + '\"' + e.name + '\": \"' + e.value + '\",</div>';
$('.list').append(_data);
copyText += _data;
});
copyData(copyText);
document.querySelector("#txtCopyArea").addEventListener("click", copyData);
});
ul,
li {
list-style: none;
margin: 0;
padding: 0;
}
.list {
margin: 10px;
width: 270px;
padding: 25px;
background-color: #fafafb;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li id="color_white">
<ul class="inputs">
<input type="radio" value="getthelist" id="getthelist"> Click to get the color values
<li id="color_white">
<div>
<input type="text" value="#fff" class="color">
</div>
</li>
<li id="color_black">
<div>
<input type="text" value="#000" class="color">
</div>
</li>
</ul>
<input type="hidden" id="txtCopyArea" name="txtCopyArea" />
<div class="list"></div>
On my script I can preview my out put by clicking on my preview button.
In side my pre tags if there is a open <div> and close </div> found with < and > how can I just replace it with the html entities I have tried
$('.preview pre').html(str.replace(/</g, "<").replace(/>/g, ">"));
But because there are br tags in there it replaces the ones around br also which I do not want. I only just want to replace the ones around the open and close div's in side my pre tag.
Question: how can I just replace it with the html entities < and
> only round the open and close divs
Codepen Example Here
Script
<script type="text/javascript">
$('#preview-question').on('click', function (e) {
var editor = $('#question').val();
$('.preview').html(editor.replace(/\n/g, '<br/>'));
$('.preview pre').next('br').remove();
if ($('.preview').find("pre").length > 0){
var str = $('.preview pre').html();
$(".preview pre div").replaceWith("<div>");
//$('.preview pre').html(str.replace(/</g, "<").replace(/>/g, ">").next('div'));
$('.preview pre').html(str);
$('pre').each(function(i, block) {
hljs.highlightBlock(block);
});
}
});
</script>
I have make a for loop for detect only div element and remove all <br>. It's a bit ugly but work fine.
$('#preview-question').on('click', function (e) {
var editor = $('#question').val();
$('.preview').html(editor.replace(/\n/g, '<br/>'));
$('.preview pre').next('br').remove();
if ($('.preview').find("pre").length > 0){
var $str = $('.preview pre');
var pre = $str.html();
$str.html("");
pre = pre.replace(/<br>/g,"\n")
for(t=0;t<pre.length;t++){
if(pre.substr(t,1) == "<" && pre.substr(t+1,3) == "div"){
$str.html($str.html() + pre.substr(0,t).replace(/</g, '<'))
}else if(pre.substr(t,1) == "<" && pre.substr(t+1,4) == "/div"){
$str.html($str.html() + pre.substr(0,t+5).replace(/</g, '<'))
}
if(pre.substr(t,1) == ">" && pre.substr(t-3,3) == "div"){
$str.html($str.html() + pre.substr(t,1).replace(/>/g, '>'))
}
}
}
});
body {
background-color: #F0F0F0;
}
.panel {
box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.08), 0 2px 4px 0 rgba(0, 0, 0, 0.12);
}
.panel-default > .panel-heading {
background-color: #4d525b;
border-color: none;
color: #FFFFFF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel panel-default">
<div class="panel-heading">
<h1 class="panel-title"></h1>
</div>
<div class="panel-body">
<div class="form-group">
<label class="col-lg-2">Title</label>
<div class="col-lg-10">
<input type="text" name="title" class="form-control" placeholder="Title" />
</div>
</div>
<div class="form-group">
<label class="col-lg-2">Question</label>
<div class="col-lg-10">
<textarea name="question" id="question" class="form-control" rows="10">
Hello this is some code
<pre>
<div class="">
</div>
</pre>
</textarea>
</div>
</div>
<div class="form-group">
<label class="col-lg-2"></label>
<div class="col-lg-10">
<div class="preview"></div>
</div>
</div>
</div>
<div class="panel-footer">
<div class="btn-group text-center">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="button" id="preview-question" class="btn btn-default">Preview</button>
Cancel
</div>
</div>
</div>
Hi i am creating a project like eCommerce site calculator
like below,
if i click on + then add one in input field and multiple by the price and show as actual price
and show price sub total with vat total like below
but i didn't got any solution in the google search please help me.
$(document).ready(function(){
$(".button-click a").on("click", function() {
var $button = $(this);
var oldValue = $button.closest("ul").prev().val();
if ($button.text() == "+") {
var newVal = parseInt(oldValue) +1;
var price = $button.parents('ul').next('.price').find('.js-applePrice').text();
var totalAdd = newVal* parseInt(price);
alert(totalAdd) ;
} else {
// Don't allow decrementing below zero
if (oldValue > 0) {
var newVal = parseInt(oldValue - 1);
} else {
newVal = 0;
}
}
$button.closest("ul").prev().val(newVal);
});
});
.some-div{
overflow:hidden;
padding:5px;
border:solid 1px green;
margin:2px;
}
.some-div> *, .some-div > ul li{
float:left;
}
.some-div > ul, .some-div > ul li{
list-style:none;
margin:0;
padding:0;
}
.some-div > ul > li a{
display:block; text-decoration:none;color:#fff; padding:5px; font-size:15px; background:#000;margin-right:5px;
}
.price{padding:0 10px;border:solid 1px green;font-weight:bold;}
.totalprice{
padding:0 10px;border:solid 1px green;font-weight:bold; color:red;margin-left:10px;
}
.remove{
float:right;
background:red;
color:#fff;
font-size:20px;
font-weight:bold;
text-decoration:none;
padding:5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="some-div">
<label for="">Apple:</label>
<input type="text" name="a" maxlength="100" value="0" />
<ul class="button-click">
<li>+</li>
<li>-</li>
</ul>
<span class="price">Price:<i class="js-applePrice">25.41</i></span>
<span class="totalprice">Total Rs. <i class="js-total">250</i></span>
*
</div>
<div class="some-div">
<label for="">Orange:</label>
<input type="text" name="b" maxlength="100" value="0" />
<ul class="button-click">
<li>+</li>
<li>-</li>
</ul>
<span class="price">Price:<i class="js-applePrice">12.00</i></span>
<span class="totalprice">Total Rs. <i class="js-total">150</i></span>
*
</div>
<div class="some-div">
<label for="">Sampu:</label>
<input type="text" name="c" maxlength="100" value="0" />
<ul class="button-click">
<li>+</li>
<li>-</li>
</ul>
<span class="price">Price:<i class="js-applePrice">15</i></span>
<span class="totalprice">Total Rs. <i class="js-total">250</i></span>
*
</div>
<!-- ---------------- -->
<div class="totalPrice">
<div class="">Sub Total :- <span class="js-Sub-total"></span></div>
<div class="">Vat :- 22%</div>
<div class="">Total :- <span class="js-total"></span></div>
</div>
Just added some logic to make it a complete example.
I've made this change in HTML to make the VAT to be configurable.
<div class="">Vat :- <span class="vat">22</span>%</div>
Few things which i noticed in your code are:
You're redefining variables in multiple places in the same function. Better practice would be declare all variables at top of the function and assign values as required. No need to use var keyword everywhere.
$(document).ready(function () {
$(".button-click a").on("click", function () {
var $button = $(this);
var oldValue = $button.closest("ul").prev().val();
var newVal, price,totalAdd ;
price = $button.parents('ul').next('.price').find('.js-applePrice').text();
if ($button.text() == "+") {
newVal = parseInt(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 0) {
newVal = parseInt(oldValue - 1);
} else {
newVal = 0;
}
}
totalAdd = newVal * parseFloat(price);
$(this).closest("ul").siblings(".totalprice").find(".js-total").text(totalAdd);
$button.closest("ul").prev().val(newVal);
var tol = 0;
$("span i.js-total").each(function (index, value) {
tol += parseFloat($(this).text());
});
$("div.totalPrice").find("div .js-Sub-total").text(tol);
var vat = parseFloat($(".vat").text());
var vatCalc = parseFloat(tol * vat) / 100;
$("div.totalPrice").find("div .js-total").text((tol + vatCalc).toFixed(2));
});
});
.some-div{
overflow:hidden;
padding:5px;
border:solid 1px green;
margin:2px;
}
.some-div> *, .some-div > ul li{
float:left;
}
.some-div > ul, .some-div > ul li{
list-style:none;
margin:0;
padding:0;
}
.some-div > ul > li a{
display:block; text-decoration:none;color:#fff; padding:5px; font-size:15px; background:#000;margin-right:5px;
}
.price{padding:0 10px;border:solid 1px green;font-weight:bold;}
.totalprice{
padding:0 10px;border:solid 1px green;font-weight:bold; color:red;margin-left:10px;
}
.remove{
float:right;
background:red;
color:#fff;
font-size:20px;
font-weight:bold;
text-decoration:none;
padding:5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="some-div">
<label for="">Apple:</label>
<input type="text" name="a" maxlength="100" value="0" />
<ul class="button-click">
<li>+</li>
<li>-</li>
</ul>
<span class="price">Price:<i class="js-applePrice">25.41</i></span>
<span class="totalprice">Total Rs. <i class="js-total">0</i></span>
*
</div>
<div class="some-div">
<label for="">Orange:</label>
<input type="text" name="b" maxlength="100" value="0" />
<ul class="button-click">
<li>+</li>
<li>-</li>
</ul>
<span class="price">Price:<i class="js-applePrice">12.00</i></span>
<span class="totalprice">Total Rs. <i class="js-total">0</i></span>
*
</div>
<div class="some-div">
<label for="">Sampu:</label>
<input type="text" name="c" maxlength="100" value="0" />
<ul class="button-click">
<li>+</li>
<li>-</li>
</ul>
<span class="price">Price:<i class="js-applePrice">15</i></span>
<span class="totalprice">Total Rs. <i class="js-total">0</i></span>
*
</div>
<!-- ---------------- -->
<div class="totalPrice">
<div class="">Sub Total :- <span class="js-Sub-total"></span></div>
<div class="">Vat :- <span class="vat">22</span>%</div>
<div class="">Total :- <span class="js-total"></span></div>
</div>
Instead of alerting, set the value back to the DOM.
And for computing monetary unit use parseFloat instead.
var price = $button.parents('ul').next('.price').find('.js-applePrice').text();
var totalAdd = newVal * parseFloat(price); ;
$button.parents('ul').next('.price').find('.js-applePrice').text(totalAdd);
In the code var oldValue = $button.closest("ul").prev() refers to div. You need to get the input's value in that div. Use $button.closest("ul").prev().find("input")
$(".button-click a").on("click", function() {
var $button = $(this);
var inputText = $button.closest("ul").prev().find("input");
var oldValue = inputText.val();
var newVal;
if ($button.text() == "+") {
newVal = parseFloat(oldValue) + 1;
} else {
newVal = parseFloat(oldValue) - 1;
if (newVal == -1)
newVal = 0;
}
inputText.val(newVal)
var price = $button.parents('ul').next('.price').find('.js-applePrice').text();
var totalAdd = newVal * parseFloat(price);
$button.closest(".some-div").find(".totalprice .js-total").text(totalAdd);
});
Fiddle
This is what I wrote some time ago. So you add and subtract buttons will both have a class called js-qty-adjuster, and an additional js-add class on the addition button.
function updatePrice(qty){
var priceOfSingleItem = //get the price of a single item here,
newPrice = priceOfSingleItem * qty;
$.ajax({
url: 'basket.php',
type: 'POST',
data: newPrice//the update price,
success: function(result){
$('#total-price').html( newPrice )
}
});
}
$('.js-qty-adjuster').on('click', function() {
var el = $(this),
id = el.data('id'),
qtySelector = el.siblings('.js-quantity'),
qty = parseInt( qtySelector.val() );
// Add or subtract from the current quantity
if (el.hasClass('js-add')) {
qty = qty + 1;
} else {
qty = qty - 1;
if (qty <= 1) {
qty = 1;
}
}
// Update the input's number
qtySelector.val(qty);
updatePrice(qty);
});
html for quantity adjuster:
<div id="quantity-wrapper" class="quantity-selector-wrapper left">
<input type="text" id="quantity" name="quantity" value="1" min="1" class="quantity-selector text-center js-quantity">
<a class="downer js-qty-adjuster qty-adjuster text-center js-add add" data-property="add" field="quantity">+</a>
<a class="up js-qty-adjuster qty-adjuster text-center js-minus minus" data-property="minus" field="quantity">-</a>
</div>
Once you change the quantity, you could simply fetch the price of a single item(using ajax or output the value in the template as a data-attribute that you can access) and multiply the values in the same function. Use Ajax to do a post request of the updated value and if the request is a success, update your html as well.
Try this, updating total price for each item :
$(document).ready(function(){
$(".button-click a").on("click", function() {
var $button = $(this);
var oldValue = $button.closest("ul").prev().val();
if ($button.text() == "+") {
var newVal = parseInt(oldValue) +1;
var price = $button.parents('ul').next('.price').find("i").text();
var totalAdd = parseFloat(newVal* parseFloat(price));
// $button.closest(".totalprice > i").text(totalAdd) ;
} else {
// Don't allow decrementing below zero
if (oldValue > 0) {
var newVal = parseInt(oldValue - 1);
} else {
newVal = 0;
}
}
$button.closest("ul").prev().val(newVal);
$button.closest("ul").siblings(".totalprice").find("i").text(totalAdd) ;
});
});
DEMO FIDDLE
When you click on the button, all checkbox inside the list element should get active. But by clicking on the button, the button disappears itself.
What do I do wrong?
Here is my code:
Here JavaScript:
$('.filter-arrow').click(function () {
//get id from clicked element
var id = $(this).attr("id");
//switch class to display open arrow
$(this).toggleClass("arrow-close");
//get function to enable checkbox
checkbox($('.parentcheck'), $(this))
});
function checkbox(check, arrow){
if(arrow.attr("class","checkAll")){
for( var i=0; i<check.length; i++){
check[i].checked = true;
var arrow_id = arrow.attr("id");
arrow_id.toggleClass("uncheckAll");
}
}else{
for(var i=0; i<check.length; i++){
check[i].checked = false;
var arrow_id = arrow.attr("id");
arrow_id.toggleClass("checkAll");
}
}
}
Here the HTML:
<ul>
<li class="checkbox">
<!--Button-->
<div id="first-arrow" class="filter-arrow checkAll arrow-open"></div>
<input id="check" class="parentcheck" name="parentcheck" type="checkbox"/>
<p>first-element</p>
<!-- begin sub content -->
<ul>
<li class="checkbox">
<div id="first-sub-arrow" class="arrow-open"></div>
<input class="input-checkbox" name="checkbox" type="checkbox"/>
<p>first-sub-element</p>
<!-- begin subsub content -->
<ul>
<li class="checkbox ">
<input class="checkbox" type="checkbox" name="subcheckbox" />
<p>first-sub-sub-element</p>
</li>
<li>
<input class="checkbox" type="checkbox" name="subcheckbox" />
<p> first-sub-sub-element(2)</p>
</li>
</ul>
</li>
</ul>
</li>
<li>
…
</li>
</ul>
CSS:
.filter-arrow{
clear:both;
float:right;
height: 12px;
width: 22px;
}
.arrow-open{
background:url(pic/arrow-close.png) no-repeat left top;
}
.arrow-close{
background: url(pic/arrow-open.png) no-repeat left top;
}
now its working... Im doing it without the class "checkAll" and "uncheckAll"
for now I wont do it with the click on the button - just with cklicking on the parent checkbox...
Just like this:
var filterGeschichte;
filterGeschichte = function( $filterContainer,$categoryToggler ){
$categoryToggler.click(function(e){
var $toggler = $(this);
$toggler.nextAll("ul.filter-sub").eq(0).slideToggle(300).find("li").show();
});
$filterContainer.each(function(){
$(this).find("input[type=checkbox]").change(function(){
var $that = $(this);
//console.log( $that.is(":checked") )
if( $that.parent().find("ul.filter-sub").length ) {
$that.parent().find("ul.filter-sub").find("input[type=checkbox]").attr("checked", $that.is(":checked") );
}
});
});
};
// JavaScript Document
$(document).ready(function(){
filterGeschichte( $("#scrollthefilter form:eq(0)"), $("div.filter-arrow") )
Checking all checkboxes should be as easy as this:
$('.first-arrow').click(function () {
$(":checkbox").attr('checked', 'checked');
});