Get the <div> outside of this <div> - javascript

I would like to get the second div (total-price), instead of the first div.
Additionally I would like to add a $ sign to the div, yet when it tries to convert the data into an Int, obviously "$" will cause an error.
I have a work around method for this, but is there anyway to concatenate the $?
Many thanks.
<!-- Product #1 -->
<div class="item">
<div class="quantity">
<button class="plus-btn" type="button" name="button">
</button>
<div class="total-price">22</div> <!--I dont want this one -->
</div>
<div class="total-price">22</div> <!--I want to access this div -->
</div>
JQuery
$('.plus-btn').on('click', function(e) {
e.preventDefault();
//Increase cost
var $this = $(this);
var $cost = $this.closest('div').find('div');
var costValue = parseInt($cost.html());
costValue += costValue;
$cost.html(costValue);
});

$('.plus-btn').on('click', function(e) {
e.preventDefault();
var $this = $(this);
var $cost = $this.closest('.quantity').siblings('.total-price');
var costValue = parseInt($cost.html());
costValue += costValue;
$cost.html(costValue);
});

The closest('div') to the button is the div you don't want.
You can simply traverse one level up the DOM tree and to the parent div and find '.total_price' in its sibling.
$('.plus-btn').on('click', function(e) {
e.preventDefault();
var $this = $(this);
var $cost = $this.parent().siblings('.total-price');
var costValue = parseInt($cost.html());
costValue += costValue;
$cost.html(costValue);
});

Related

Clone HTML div while changing all ids

I have this, simplified for testing, architecture :
<div class="container">
<div class="row" id="row_0">
<div class="col-md-12">
<form id="form_0">
<select name="test1" id="test1_0"></select>
<select name="test2" id="test2_0"></select>
<input name="test3" id="test3_0"/>
</form>
</div>
</div>
</div>
And my goal is to clone that row in the container, while changing EVERY _0 and incrementing it by 1.
I'm able to clone a the row, get the numeric value of the row and create another row with an incremented id.
var div = $('div[class^="row"]:last');
var num = parseInt( div.prop("id").match(/\d+/g), 10 ) +1;
var clone = div.clone().prop('id', 'row_'+num );
div.after( clone );
But I have no idea how to change each and every id that has a _0 to _1, can anyone help me please?
Fiddle exemple : https://jsfiddle.net/L5mn63g7/1/
var $row = $('.row').last(); //Select the row
var num = parseInt($row.attr('id').match(/\d+$/)[0]) + 1; //get the current index
var clone = $row.clone(); //clone the row
clone.attr('id', 'row_' + num); //change its id
clone.children('[id]').each(function() {//go through all elements with an id
$(this).attr('id', $(this).attr('id').replace(/\d+$/, num)); //change the id
});
clone.appendTo('body'); //append the result to the body (replace 'body' with where you want it)
This code has not been tested, it might contain bugs or errors.
However I agree with Rory McCrossan :
You could just place each row in a div with a specific id, then call insider classes with var $row = $('#div_id'); $row.find('.class') (I'm using this for an included form)
var div = $('div[id^="row"]:last');
var num = parseInt( div.prop("id").match(/\d+/g), 10 ) +1;
var clone = div.clone().prop('id', 'row_'+num );
clone.find('[id]').each(function(){var $this = $(this); $this.prop('id', $this.prop('id').split('_')[0] + '_' + num);});
div.after( clone );

jQuery toggle change inner html of a button in function

I have two elements
<div id="searchInput">
This is something
</div>
<button type="button" id="dugme" onclick="th()" > Show </button>
I want to toggle (in jQuery) the searchInput (hide and show) and change the button text from Show to Hide.
The searchInput isn't the problem, I just do this:
function th(){
$(document).ready(function(){
var forma = document.getElementById("searchInput");
var dugme = document.getElementById("dugme");
$(forma).toggle();
});
}
But when I want to change the innerHTML in the toggle nothing happens. This is what I tried:
function th(){
$(document).ready(function(){
var forma = document.getElementById("searchInput");
var dugme = document.getElementById("dugme");
$(forma).toggle(function(){
$(dugme).innerHTML = "Hide";
});
});
}
You need to use $(dugme).html("Hide"); because $(dugme) is a jQuery object. You also do not require a document.ready handler within a function.
function th() {
var forma = document.getElementById("searchInput");
var dugme = document.getElementById("dugme");
$(forma).toggle(function() {
$(dugme).html("Hide");
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="searchInput">
This is something
</div>
<button type="button" id="dugme" onclick="th()"> Show </button>
innerHTML do not work in jQuery objects so you need to remove $ as:
function th() {
var forma = document.getElementById("searchInput");
var dugme = document.getElementById("dugme");
$(forma).toggle(function() {
dugme.innerHTML = "Hide";
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="searchInput">
This is something
</div>
<button type="button" id="dugme" onclick="th()"> Show </button>
Try this:
function th(){
var forma = $("#searchInput");
var dugme = $("#dugme");
forma.toggle(function(){
var txt = forma.is(':visible') ? 'Hide':'Show';
gugme.text(txt);
});
}
The problem comes when you're trying to call the element property innerHTML on jQuery object, you could use html() instead but since you're changing just the text it will be better to use .text() like:
$(dugme).text("Hide");
You could use .is(':visible') to toggle the text like:
forma.toggle(function() {
dugme.text(forma.is(':visible') ? "Hide" : "Show");
});
function th() {
$(document).ready(function() {
var forma = $("#searchInput");
var dugme = $("#dugme");
forma.toggle(function() {
dugme.text(forma.is(':visible') ? "Hide" : "Show");
});
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="searchInput">
This is something
</div>
<button type="button" id="dugme" onclick="th()"> Hide </button>
Html
<div id="searchInput">
This is something
</div>
<button type="button" id="dugme">Hide</button>
Jquery
$('#dugme').click(function(){
if ($.trim($(this).text()) == 'Hide') {
$(this).text('Show');
$('#searchInput').hide();
} else {
$('#searchInput').show();
$(this).text('Hide');
}
});
jsFiddle

Remove clicked id from the input value

I am trying to delete clicked id to remove input value. For example i have this input <input type='hidden' id='uploadvalues' value="8,9"/> you can see the values 8,9 and the button is <div class="delete" id="9"></div> .
When i click the id="9" then the input value 9 should be remove . After clicked id="9" ==> <input type='hidden' id='uploadvalues' value="8"/>
How can i do that anyone can teach me?
Demo from CodeCanyon
<div class="container">
<div class="area">
<div class="image"><img src="https://s-media-cache-ak0.pinimg.com/736x/05/2f/1b/052f1b3a2361eb4f3c1385c1fd4f75ed.jpg"></div>
<div class="delete" id="8"></div>
</div>
<div class="area">
<div class="image"><img src="http://www.wallpapermade.com/images/wallpapers/originals/tip-and-oh-laugh-together-home-2015-movie-wallpaper-4612.jpg"></div>
<div class="delete" id="9"></div>
</div>
<input type='hidden' id='uploadvalues' value="8,9"/>
</div>
JS
$(document).ready(function(){
$("body").on("click", ".delete", function(){
// Remove clicked id from the input value
});
});
One way on the approach you want is
$("body").on("click", ".delete", function(){
var id = this.id, //extract the id from the clicked element
values = $('#uploadvalues').val().split(','), // get the existing values in the #uploadvalues element
remaining = values.filter(function(val){ // filter out the ones equal to the id of the clicked element
return val !== id;
});
$('#uploadvalues').val(remaining.join()); // update the changed values
});
make it
$(document).ready(function(){
$("body").on("click", ".delete", function(){
var val = $(this).attr("id");
var values = $( "#uploadvalues" ).val().split(",");
var valIndex = values.indexOf(val);
if (valIndex > -1)
{
values.splice(valIndex,1);
}
$( "#uploadvalues" ).val( values.join(",") )
});
});
Try to make use of regular expression at this context,
$(document).ready(function() {
$("body").on("click", ".delete", function(){
var id = this.id;
$("#uploadvalues").val(function(val){
return val.replace(new RegExp(id + "\,|\,"+ id +"$"),"")
});
});
});
when you click the delete button, in the callback function grab the id:
var valueToRemove = this.id;
// now you need to look to see if that value is inside the hidden input
var valueToRemove = this.id;
console.log(valueToRemove);
var values = $("#uploadvalues").val();
if(values.indexOf(valueToRemove) >= 0){
$("#uploadvalues").val(values.replace(valueToRemove,""));
}
also its best practice to cache the dom so you dont have to constantly query it.
Is this what you wanted? and this method does not get rid of the comma within the values.

Button Group Click Handler - How to get text content of clicked button?

I am trying to set up two button groups. A click on any button in the second group should add a new button to the first group. The new button shall get the same label as the clicked button.
var name = this.textContent works if the click handler is attached to a single button. How do you get the text content of the clicked button when the click handler is instead attached to a group of buttons?
HTML:
<body>
<div id="group1">
<button> nameA </button>
<button> nameB </button>
</div>
<hr>
<div id="group2">
<button> nameC </button>
<button> nameD </button>
</div>
</body>
Javascript:
$('#group2').on('click', function(event) {
var name = this.textContent // wrong!
var r = $('<input type="button" value="' + name + '">');
$("div#group1").append(r);
});
JSFiddle Demo
Use event delegation:
$('#group2').on('click', 'button', function(event) {
var name = this.textContent
var r = $('<input type="button" value="' + name + '">');
$("div#group1").append(r);
});
Second parameter in 'on' method can be selector string to filter the descendants of the selected elements that trigger the event.
Check this https://jsfiddle.net/q6b6g3xm/
In your case, this should be enought:
$('#group2 button').click(function(event) {
var name = this.textContent
var r = $('<input type="button" value="' + name + '">');
$("div#group1").append(r);
});
Prefer the RobHil solution if you other buttons will be created in #group2 after the execution of the jQuery code.
Else, I see two other possibilities:
$('#group2 button').each(function () {
var $button = $(this).click(function(event) {
var r = $('<input type="button" value="' + $button.text() + '">');
$("div#group1").append(r);
});
});
or:
$('#group2').click(function(event) {
var $button = $(event.target);
var r = $('<input type="button" value="' + $button.text() + '">');
$("div#group1").append(r);
});
But keep in mind the target depend on where you click if you have nested blocks in the clicked zone: https://api.jquery.com/event.target/
Here is my own approach to the problem. I modified HTML code a little by adding individual id to the buttons.
HTML:
<div id="group1" >
<button id="btn-A">nameA</button>
<button id="btn-B">nameB</button>
<button id="btn-C">nameC</button>
</div>
<hr />
<div id="group2">
<button id="btn-D">nameD</button>
<button id="btn-E">nameE</button>
<button id="btn-F">nameF</button>
</div>
JavaScript:
// click on the button
$(document).on('click','button', function(){
//store the value of the id and
// split it # '-' into array ['btn','A']
$id = $(this).attr('id').split('-');
// store the value at index 1 into $id
$id = $id[1];
//get the Id of the current div group
$divId = $(this).closest('div').attr('id');
//check which div group is current and
//Assign the reversed value as appropriate
if($divId === "group1"){
$addId = "#group2";
}else {
$addId = "#group1";
}
//Remove the button from the group
$(this).remove();
//Add the button to the second div group
$($addId).append('<button id="btn-'+$id+'">'+$(this).text()+'</button>');
});

Update price after checkbox is selected

I have a fairly simple problem (I think) that involves updating a number using jQuery. I have a DIV that holds a price for an item. Users can select a checkbox to add on to the total price. What I need is when someone clicks on a checkbox, it will add the correct amount to the DIV. When a user un-checks a checkbox, the value is subtracted. Here is my code so far:
<div class="cell">
<div class="check">
<input id="check-0" type="checkbox" />
<label for="check-0">$100</label>
<div class="mask"></div>
</div>
</div>
<div class="price">$347</div>
Any help is greatly appreciated!
Hopefully this is something that you could use or help you:
http://jsfiddle.net/VWRAd/
$(".cell").on("click", "input:checkbox", function () {
var $this = $(this);
var $total = $("#price");
var $target = $("label[for='" + $this.attr("id") + "']");
var item_value = +($target.html().replace("$", "") || 0);
var cur_total = +($total.html().replace("$", "") || 0);
if ($this.prop("checked") === true) {
cur_total += item_value;
} else {
cur_total -= item_value;
}
$total.html("$" + cur_total);
});
Although notice that I changed the element with the class of "price" to have an id of "price". It just makes sense, unless you expect to have several "price" elements.
And here is another possible way of doing it...not sure which is better:
http://jsfiddle.net/VWRAd/1/
$(".cell").on("click", "input:checkbox", function () {
var $items = $(".cell").find("input:checkbox:checked");
var $total = $("#price");
var cur_total = 0;
$items.each(function () {
var $this = $(this);
var $target = $("label[for='" + $this.attr("id") + "']");
var item_value = +($target.html().replace("$", "") || 0);
cur_total += item_value;
});
$total.html("$" + cur_total);
});
Some things to consider - it makes sense to separate the "$" from the actual value of the item when displaying it...I'm sure you aren't storing the value with "$", so you might want a structure similar to <label for="whatever">$<span class="the-value">100</span></label>. It would change your jQuery selector logic a little bit, but it would prevent the need for using .replace so often. Also, as someone else already pointed out, it would definitely be easier to store the item's price in the checkbox's value attribute and retrieve it that way (instead of finding the corresponding <label>'s content.
var changePrice = function changePrice(amt, state){
var curPrice = $('.price').text();
curPrice = curPrice.substring(1, curPrice.length);
if(state==true){
curPrice = parseInt(curPrice) + parseInt(amt);
}else{
curPrice = parseInt(curPrice) - parseInt(amt);
}
curPrice = '$' + curPrice;
$('.price').text(curPrice);
}
$(function(){
$('#check-0').on('change', function(){
var itemPrice = $('label[for="check-0"]').text();
itemPrice = itemPrice.substring(1, itemPrice.length);
changePrice(itemPrice, $('#check-0').is(':checked'));
});
})​;​
Demo: http://jsfiddle.net/pratik136/r2Snu/
Even though these may not be form controls intended to hit the server, i would still put the value attribute for each of the inputs.
So for the 'check-0' input, i'd put in a value attribute of 100 (to represent the $100).
Then, a bit of javascript logic should make it easy to update the price value.
So something like this should do it (http://jsbin.com/orodow/1/edit):
<div class="cell">
<div class="check">
<input id="check-0" type="checkbox" value="100" />
<label for="check-0">$100</label>
<div class="mask"></div>
</div>
</div>
<div class="cell">
<div class="check">
<input id="check-1" type="checkbox" value="50" />
<label for="check-1">$50</label>
<div class="mask"></div>
</div>
</div>
<div class="cell">
<div class="check">
<input id="check-2" type="checkbox" value="20" />
<label for="check-2">$20</label>
<div class="mask"></div>
</div>
</div>
<div class="price"></div>
<script>
$(function(){
var inputs = $('.check input:checkbox');
function updatePrice(){
var value = 0;
inputs.filter(':checked').each(function(){
value += parseInt($(this).val(), 10);
});
$('.price').html('$' + value);
}
inputs.change(updatePrice);
});
</script>

Categories