Hi Guys I have been working on this script for some time and I just cant make it work well I may be missing an important argument to get it to work properly..
I need to calculate the values from inside of a tag and add up the total to a heres the HTML:
<div class="catProdAttributeItem">
<input type="radio" id="5583116" name="752526">
<span>Ford £19.99</span>
<img src="http://www.breakerlink.com/blog/wp-content/uploads/2014/01/Ford.png">
</div>
<div class="catProdAttributeItem">
<input type="radio" id="5971554" name="752526">
<span>Ferrary £19.99</span>
<img src="http://www.assettocorsa.net/wp-content/uploads/2013/09/logo2.png">
</div>
<br><br>
<span style="display:none;" class="original_price">£0.00</span>
<div class="updated_price" id="show-price">£0.00</div>
And here is my Script:
$('.catProdAttributeItem img').on("click", function() {
$(this).siblings('input[type=radio]').attr('checked', true);
var original_price = $('.original_price').text().replace(/[^0-9\.]/g, '');
parseFloat(this.original_price);
var warehouse_price = $(this).siblings('.catProdAttributeItem span').text().replace(/[^0-9\.]/g, '');
warehouse_price = parseFloat(warehouse_price);
var total_price = parseFloat(original_price) + parseFloat(warehouse_price);
$('.updated_price').html('£' + total_price.toFixed(2));
})
I can only get the result of the clicked siblings, please some help is much appreciated..
I was expecting to add up the values displayed on the .updated_price when the input is selected but it will work on a wider set of inputs where you can check more inputs and you would get the result from all the inputs checked
DEMO FIDDLE
You need the checkbox for each car (not radio). See below:
$(document).ready(function() {
$('.catProdAttributeItem img').on("click", function() {
// Make checkbox adjustment
$(this).siblings('input:checkbox').click();
});
$(document).on('click', 'input:checkbox', calcTotal);
});
function calcTotal() {
var total_price = 0;
// find all .catProdAttributeItem divs
$(document).find('.catProdAttributeItem').each(function() {
// see if the checkbox is checked to add to the total_price
var $checkbox = $(this).find('input:checkbox');
if ($checkbox.is(':checked')) {
var text = $(this).find('span').html();
total_price += parseFloat(text.replace(/[^0-9\.]/g, ''))
}
});
// finally display the price
$('.updated_price').html('£' + total_price.toFixed(2));
}
.catProdAttributeItem {
width: 300px;
float: left;
display: inline-block;
text-align: center;
}
img {
width: 100px;
height: auto;
}
.updated_price {
clear: both;
margin: 20px 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="catProdAttributeItem">
<input type="checkbox" id="5583116" name="752526">
<span>Ford £19.99</span>
<img src="http://www.breakerlink.com/blog/wp-content/uploads/2014/01/Ford.png">
</div>
<div class="catProdAttributeItem">
<input type="checkbox" id="5971554" name="752526">
<span>Ferrary £19.99</span>
<img src="http://www.assettocorsa.net/wp-content/uploads/2013/09/logo2.png">
</div>
<br>
<br>
<div class="updated_price" id="show-price">£0.00</div>
From my understanding of what you're trying to do, you will want to simply iterate over all .catProdAttributeItem elements and add the price only if the radio button is checked:
var warehouse_price = 0;
$('.catProdAttributeItem')
.filter(function() {
// only interested in checked radio boxes
return $('input:checked', this).length > 0;
})
.each(function() {
var price = parseFloat($('span', this).text().replace(/[^\d.]/, ''));
warehouse_price += price;
});
$('.updated_price').html('£' + total_price.toFixed(2));
This answer is a combination of Sigismundus answer + A bit of twicks to be able to grab the results from both either the radio buttons and check boxes the img click didn't work quite well, but now if added a new function to get the images as radio buttons it would work.
var priceSelect = parseFloat(document.getElementById("totalprice").value);
$('.catProdAttributeItem input[type=radio], .catProdAttributeItem input[type=checkbox] ').on("click", function() {
var total_price = 0;
$(document).find('.catProdAttributeItem').each(function() {
var $checkbox = $(this).find('input:radio, input:checkbox');
if ($checkbox.is(':checked')) {
var text = $(this).find('span').html();
total_price += parseFloat(text.replace(/[^0-9\.]/g, ''))
}
});
$('#totalprice').html('£' + total_price.toFixed(2));
document.getElementById('totalprice').value = total_price+priceSelect;
});
Related
I currently am building a form that has 3 checkboxes and a dynamic button that appears below.
My current issue is when you select more than one then tick off one more both the active state and deactivate state buttons appear
https://staging-homecarepulse.kinsta.cloud/demo-select/ here is my demo link
Here is the script im using
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>$(document).on("change", ".mod-link", function() {
var arr = []
$(".mod-link:checked").each(function() {
arr.push($(this).val());
})
if ($(this).is(":checked")) {
$('#picture').attr('src', '');
} else {
$('#picture').attr('src', 'https://staging-homecarepulse.kinsta.cloud/wp-content/uploads/2021/06/greyBTN.jpg');
}
var vals = arr.join(",")
var str = "/demo/?demo_request_type=" + vals;
var link = arr.length > 0 ? '<a class="dynabtn" href="'+str+'">Continue</a>': '' ;
$('.link-container').html(link);
});
</script>
here is my html
<input type="checkbox" id="checkbox1" class="mod-link" name="selected" value="es" hidden>
<label for="checkbox1" style="cursor: pointer;">CHECK BOX styling and info HERE</label>
<div class="link-container" style="text-align:center;"></div>
<div style="text-align:center;">
<span class="result_img">
<img id="picture" src="https://staging-homecarepulse.kinsta.cloud/wp-content/uploads/2021/06/greyBTN.jpg"/>
</span>
</div>
I would like to figure out how to hide the grey image button until ALL OR NO checkboxes are selected. so for short #picture should not display until ALL OR NO CHECKBOXES ARE SELECTED
Any help is appreciated
You can check arr.length earlier for showing and hiding gray button as well. Please see below code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>$(document).on("change", ".mod-link", function() {
var arr = []
$(".mod-link:checked").each(function() {
arr.push($(this).val());
})
if (arr.length > 0) {
$('#picture').attr('src', '');
} else {
$('#picture').attr('src', 'https://staging-homecarepulse.kinsta.cloud/wp-content/uploads/2021/06/greyBTN.jpg');
}
var vals = arr.join(",")
var str = "/demo/?demo_request_type=" + vals;
var link = arr.length > 0 ? '<a class="dynabtn" href="'+str+'">Continue</a>': '' ;
$('.link-container').html(link);
});
</script>
Hope it resolve your issue.
I have this code from #Snowmonkey
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function() {
$("#submitBtn").on("click", submitted);
// Created an 'add new row' button, which non-destructively adds a row to the container.
$(".add-row-btn").on("click", function(evt) {
evt.preventDefault();
evt.stopPropagation();
$(".container").append(createNewRow());
})
// When the user chooses a different number, completely reset all the rows?
$('#amount').on('change', function() {
// Save a reference to the row container.
var containerEl = $(".container");
// wipe out completely the contents of the container.
containerEl.empty();
// get the number of rows to be created.
var startingNumberOfLines = parseInt($("#amount").val());
// loop the number of times requested, and append a new row each time.
// createNewRow() is defined below.
for (var i = 0; i < startingNumberOfLines; i++) {
$(".container").append(createNewRow());
}
});
// Start with an initial value.
$(".add-row-btn").trigger("click");
})
/*****
* createNewRow() -- function to create a new row, composed of a text input,
* and two labels containing number inputs.
*****/
var createNewRow = function() {
/****
* first, we'll define all the elements that will be placed
* in this row -- the text input, the labels and the inputs.
****/
var lineTitleEl = $("<input>").attr("placeholder", "enter text here")
.addClass("line-title");
var labelEl = $("<label>");
var inputEl = $("<input>").attr("step", "0.05").attr("type", "number")
.addClass("line-number");
// The firstNumberEl is a label containing an input. I can simply
// clone my label el, and input el, and use them. Don't need to,
// but i CAN.
var firstNumberEl = labelEl.clone();
firstNumberEl.text("number1: ").attr("class", "first-number-el").append(inputEl.clone());
var secondNumberEl = labelEl.clone();
secondNumberEl.text("number2: ").attr("class", "second-number-el").append(inputEl.clone());
// Now create the row, which is a div containing those elements.
var newRowEl = $("<div>").append(lineTitleEl, firstNumberEl, secondNumberEl);
// Simply return that row -- the user can send it to the console or
// can append it wherever they like.
return newRowEl;
}
/******
* submitted() -- function to handle the submit button. We want to
* iterate over all the rows, and given that they now have a consistent
* format, parse out the required data and display it.
******/
function submitted() {
console.log("submitted");
$(".container").children("div").each(function() {
var title = $(this).find(".line-title").val();
var firstNum = $(this).find(".first-number-el input").val();
var secondNum = $(this).find(".second-number-el input").val();
console.log(title + ", " + firstNum + ", " + secondNum);
})
}
</script>
<style>
.line-title {
width: 259px;
margin: 0px;
height: 15px;
clear: left;
}
.line-number {
width: 45px;
}
.container {
margin: 10px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset style=" margin: 0 0 5px 0;">
<!--<div>enter amount of text + number boxes:
<input id="amount" step="1" style=" width: 45px;" type="number" value="1">
</div>-->
<div class="container">
</div>
<button class="add-row-btn">
Add row
</button>
<button class="remove-row-btn">
Remove row
</button>
<input class="button" id="submitBtn" style="margin-left: 85%;" type="button" value="Submit">
</fieldset>
</form>
At the moment the code add new rows when the add row button is clicked. I want to add a similar function to the button 'remove row'. If it were clicked I want the last row to be removed, without affecting the content in the other textboxes. I have tried this, but it did not work:
$(".remove-row-btn").on("click", function(evt) {
evt.preventDefault();
evt.stopPropagation();
$(".container").remove(createNewRow());
})
How can I do this?
Thanks.
You could index the last element and remove it.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function() {
$("#submitBtn").on("click", submitted);
// Created an 'add new row' button, which non-destructively adds a row to the container.
$(".add-row-btn").on("click", function(evt) {
evt.preventDefault();
evt.stopPropagation();
$(".container").append(createNewRow());
})
$(".remove-row-btn").on("click", function(evt) {
evt.preventDefault();
evt.stopPropagation();
$(".container div").eq($(".container div").length - 1).remove();
})
// When the user chooses a different number, completely reset all the rows?
$('#amount').on('change', function() {
// Save a reference to the row container.
var containerEl = $(".container");
// wipe out completely the contents of the container.
containerEl.empty();
// get the number of rows to be created.
var startingNumberOfLines = parseInt($("#amount").val());
// loop the number of times requested, and append a new row each time.
// createNewRow() is defined below.
for (var i = 0; i < startingNumberOfLines; i++) {
$(".container").append(createNewRow());
}
});
// Start with an initial value.
$(".add-row-btn").trigger("click");
})
/*****
* createNewRow() -- function to create a new row, composed of a text input,
* and two labels containing number inputs.
*****/
var createNewRow = function() {
/****
* first, we'll define all the elements that will be placed
* in this row -- the text input, the labels and the inputs.
****/
var lineTitleEl = $("<input>").attr("placeholder", "enter text here")
.addClass("line-title");
var labelEl = $("<label>");
var inputEl = $("<input>").attr("step", "0.05").attr("type", "number")
.addClass("line-number");
// The firstNumberEl is a label containing an input. I can simply
// clone my label el, and input el, and use them. Don't need to,
// but i CAN.
var firstNumberEl = labelEl.clone();
firstNumberEl.text("number1: ").attr("class", "first-number-el").append(inputEl.clone());
var secondNumberEl = labelEl.clone();
secondNumberEl.text("number2: ").attr("class", "second-number-el").append(inputEl.clone());
// Now create the row, which is a div containing those elements.
var newRowEl = $("<div>").append(lineTitleEl, firstNumberEl, secondNumberEl);
// Simply return that row -- the user can send it to the console or
// can append it wherever they like.
return newRowEl;
}
/******
* submitted() -- function to handle the submit button. We want to
* iterate over all the rows, and given that they now have a consistent
* format, parse out the required data and display it.
******/
function submitted() {
console.log("submitted");
$(".container").children("div").each(function() {
var title = $(this).find(".line-title").val();
var firstNum = $(this).find(".first-number-el input").val();
var secondNum = $(this).find(".second-number-el input").val();
console.log(title + ", " + firstNum + ", " + secondNum);
})
}
</script>
<style>
.line-title {
width: 259px;
margin: 0px;
height: 15px;
clear: left;
}
.line-number {
width: 45px;
}
.container {
margin: 10px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset style=" margin: 0 0 5px 0;">
<!--<div>enter amount of text + number boxes:
<input id="amount" step="1" style=" width: 45px;" type="number" value="1">
</div>-->
<div class="container">
</div>
<button class="add-row-btn">
Add row
</button>
<button class="remove-row-btn">
Remove row
</button>
<input class="button" id="submitBtn" style="margin-left: 85%;" type="button" value="Submit">
</fieldset>
</form>
I have a function written in jquery that copies the value of the checkbox to the textarea #msg
$(document).ready(function(){
$("input:checkbox").click(function() {
var output = "";
$("input:checked").each(function() {
output += $(this).val() + "";
});
$("#msg").val(output.trim());
});
});
Clicking any checkbox on side copies of its value to the #msg field
How to reduce this effect that only checkboxes in the <ul> or a selected div operate in such a manner?
I want this:
<ul>
<input name="foo2" type="checkbox" value="Hello" id="tel_1">
<label for="tel_1">Hello</label>
</ul>
To be copied to the #msg textarea and this :
<input name="foo" value="123123123" id="tel_11" type="checkbox">
<label for="tel_11">Alan</label>
Not to be copied. I played with this :
$("input:checkbox").click(function()
And changed input:checkbox to ul:input:checkbox but I do not want to work.
You could use the id :
$(document).ready(function(){
$("#tel_1").click(function() {
var output = "";
output += $(this).val() + "";
$("#msg").val(output.trim());
});
});
Or if you want to exclude just #tel_11 you could use :not() selector like :
$(document).ready(function(){
$("input:checkbox:not('#tel_11')").click(function() {
var output = "";
$("input:checked:not('#tel_11')").each(function() {
output += $(this).val() + "";
});
$("#msg").val(output.trim());
});
});
Update :
If you have several id's as you sain in the comment (answers example) you could use start with selector like $("[id^='answer_'") ans that will include all of your 18 answers, e.g :
$(document).ready(function(){
$("[id^='answer_'").click(function() {
var output = "";
output += $(this).val() + "";
$("#msg").val(output.trim());
});
});
Hope this helps.
Use a selector that just matches checkboxes that are children of <ul>.
$("ul > :checkbox").click(function() {
...
});
I'm currently adding some input fields to a div. There is also the option to remove the just added input fields.
Now the problem is, if you add 4 input fields and let's say you removed number 2.
You will get something like this
id=1
id=3
id=4
Now when you will add a new one it will add id=5.
So we end up with:
id=1
id=3
id=4
id=5
JS :
var iArtist = 1,
tArtist = 1;
$(document).on('click', '#js-addArtist', function() {
var artist = $('#js-artist');
var liData = '<div class="js-artist"><input id="artiestNaam_' + iArtist + '"><input id="artiestURL_' + iArtist + '"><span class="js-removeArtist">remove</span></div>';
$(liData).appendTo(artist);
iArtist++;
tArtist++;
});
$(document).on('click', '.js-removeArtist', function() {
if (tArtist > 1) {
$(this).parents('.js-artist').slideUp("normal", function() {
$(this).remove();
tArtist--;
});
}
});
$(document).on('click', '#js-print', function() {
var historyVar = [];
historyVar['artiestNaam_0'] = $('#artiestNaam_0').val();
historyVar['artiestURL_0'] = $('#artiestURL_0').val();
console.log(historyVar);
});
HTML :
<span id="js-addArtist">add</span>
<div id="js-artist">
<div class="js-artist">
<input id="artiestNaam_0">
<input id="artiestURL_0">
<span class="js-removeArtist">remove</span>
</div>
</div>
<span id="js-print">print</span>
For now it's okay.
Now for the next part I'm trying to get the data from the input fields:
historyVar['artiestNaam_0'] = $('#artiestNaam_0').val();
historyVar['artiestURL_0'] = $('#artiestURL_0').val();
How can I make sure to get the data of all the input fields?
Working version
You could do with a whole lot less code. For example purposes I'm going to keep it more simple than your question, but the priciple remains the same:
<input name="artiest_naam[]" />
<input name="artiest_naam[]" />
<input name="artiest_naam[]" />
The bracket at the end make it an array. We do not use any numbers in the name.
When you submit, it will get their index because it´s an array, which returns something like:
$_POST['artiestnaam'] = array(
[0] => "whatever you typed in the first",
[1] => "whatever you typed in the second",
[2] => "whatever you typed in the third"
)
If I would add and delete a hundred inputs, kept 3 random inputs and submit that, it will still be that result. The code will do the counting for you.
Nice bonus: If you add some javascript which enables to change the order of the inputs, it will be in the order the user placed them (e.g. if I had changed nuymber 2 and 3, my result would be "one, third, second").
Working fiddle
You could use each() function to go through all the divs with class js-artist:
$('.js-artist').each(function(){
var artiestNaam = $('input:eq(0)',this);
var artiestURL = $('input:eq(1)',this);
historyVar[artiestNaam.attr('id')] = artiestNaam.val();
historyVar[artiestURL.attr('id')] = artiestURL.val();
});
Hope this helps.
var iArtist = 1,
tArtist = 1;
$(document).on('click', '#js-addArtist', function() {
var artist = $('#js-artist');
var liData = '<div class="js-artist"><input id="artiestNaam_' + iArtist + '"><input id="artiestURL_' + iArtist + '"><span class="js-removeArtist">remove</span></div>';
$(liData).appendTo(artist);
iArtist++;
tArtist++;
});
$(document).on('click', '.js-removeArtist', function() {
if (tArtist > 1) {
$(this).parents('.js-artist').slideUp("normal", function() {
$(this).remove();
tArtist--;
});
}
});
$(document).on('click', '#js-print', function() {
var historyVar = [];
$('.js-artist').each(function(){
var artiestNaam = $('input:eq(0)',this);
var artiestURL = $('input:eq(1)',this);
historyVar[artiestNaam.attr('id')] = artiestNaam.val();
historyVar[artiestURL.attr('id')] = artiestURL.val();
});
console.log(historyVar);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="js-addArtist">add</span>
<div id="js-artist">
<div class="js-artist">
<input id="artiestNaam_0">
<input id="artiestURL_0">
<span class="js-removeArtist">remove</span>
</div>
</div>
<span id="js-print">print</span>
Initialize a count variable. This way if an input field is removed, a new id still gets initialized. To get the data for each of them, jQuery has a convenient each function to iterate over all elements.
Hope this helps
count = 0;
$("#add").on("click", function() {
count++;
$("body").append("<input id='" + count + "'</input>");
});
$("#remove").on("click", function() {
var index = prompt("Enter the index of the input you want to remove");
$("input:eq(" + index + ")").remove();
});
$("#log-data").on("click", function() {
$("input").each(function() {
console.log($(this).val());
});
});
#btn-group {
margin-bottom: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="btn-group">
<button id="add">Add Input Fields</button>
<button id="remove">Remove Input Fields</button>
<button id="log-data">Log Data</button>
</div>
I'm trying to create a simple "search field", what it does is it searches if typed in text is equal to any data-attr of the boxes in the content and if so, hide everything but what found, something similar (this ain't working):
css:
.filter-div {
display: none;
}
html:
<label for="search">Search Input:</label>
<input type="search" name="filter" id="search" value="" />
<div class="filter-div" data-filter="one">one</div>
<div class="filter-div" data-filter="two">two</div>
<div class="filter-div" data-filter="three">three</div>
<div class="filter-div" data-filter="four">four</div>
<div class="filter-div" data-filter="five">five</div>
jquery:
// save the default value on page load
var filter = $('.input').val();
// on submit, compare
if ( $('.input').val() = $("data-filter") {
$(this).show();
}
I am also not sure if the content should be filtered with a button click or found content should pop up as click-able text in the search, or should all happen auto? Finally probably I will have to check it against more than one data-attr.
Anyone?
$('#search').on('keyup', function() {
var val = $.trim(this.value);
if (val) {
$('div[data-filter=' + val + ']').show();
} else $('div[data-filter]').hide();
});
Working sample
According to demo fiddle example in comment
var divs = $('div[data-filter]');
$('#search').on('keyup', function() {
var val = $.trim(this.value);
divs.hide();
divs.filter(function() {
return $(this).data('filter').search(val) >= 0
}).show();
});
divs.on('click', function() {
divs.not(this).hide();
var text = $.trim($(this).text());
$('#search').val(text);
});
Working sample
JavaScript:
var filter_div = $('[data-filter]');
$('#search').keyup(function(){
var val = $.trim(this.value);
filter_div.hide();
if(val.length == 0) return;
filter_div.filter(function(){
return $(this).data('filter').indexOf(val)>-1
}).show();
});
Fiddle: http://jsfiddle.net/iambriansreed/xMwS5/