This is a follow up question on an existing question. I am able to get total sub-price tof products that i selected and add up to get the grand total. Now, when an item is deselected, i want to subtract the price of the item being deselected from the existing grand total?
How do i get that done please?
When i try to get the oldtext, it is always 0 .. why is this happening?
HTML
<div class="panel" id="panel">
<div>
<div >
<p> class="mygoods" >Total: <span ></span></p>
</div>
JS
<script type="text/javascript">
function order(food)
{
var ad = JSON.parse(food.dataset.food);
if(food.checked == true) {
$('.panel').append(
'<div class="container" style=" font-size:14px; "> '+
'<p class="total" ><span class="sub-total" name="total" id="total"></span></p>'+
'<input size="50" type="text" class="form-control quantity" id="qty" placeholder=" qty " name="quantity[]" required/>'+
'</div>'
)
}
else{
var total = $(".panel .container [data-id=" + ad.id + "]").parent().find(".total").text();
$(".panel .container [data-id=" + ad.id + "]").parent().remove();
if (total) {
$('.mygoods span').text(function(oldtext) {
console.log('this is my old text '+oldtext)
return oldtext ? oldtext - total : oldtext;
});
}
}
}
$('.panel').on('keyup','.quantity',function()
{
var sum;
container = $(this).closest('div');
quantity = Number($(this).val());
price = Number($(this).closest('div').find('.price').data('price'));
container.find(".total span").text(quantity * price);
sum = 0;
$(".sub-total").each(function(){
sum = sum + Number($(this).text());
})
$('.mygoods span').text(sum);
});
</script>
$( '.mygoods span' ).text( function( oldtext ) {
console.log( 'this is my old text ' + oldtext )
return oldtext ? oldtext - total : oldtext;
} );
the .text method returns the parameters index and text - you only are retrieving one. Therefore the index is being stored in the oldtext variable, not the text.
Type: Function( Integer index, String text ) => String A function
returning the text content to set. Receives the index position of the
element in the set and the old text value as arguments.
http://api.jquery.com/text/
You can fix this by simply adding another parameter.
$( '.mygoods span' ).text( function(index, oldtext ) {
console.log( 'this is my old text ' + oldtext )
return oldtext ? oldtext - total : oldtext;
} );
I tried copying a snippet over to show you, but the code you provided is not enough to build anything. The attempted build is below.
function order( food ) {
var ad = JSON.parse( food.dataset.food );
if ( food.checked == true ) {
$( '.panel' ).append( '<div class="container" style=" font-size:14px; "> ' +
'<p class="total" ><span class="sub-total" name="total" id="total"></span></p>' +
'<input size="50" type="text" class="form-control quantity" id="qty" placeholder=" qty " name="quantity[]" required/>' +
'</div>' )
} else {
var total = $( ".panel .container [data-id=" + ad.id + "]" ).parent().find(
".total" ).text();
$( ".panel .container [data-id=" + ad.id + "]" ).parent().remove();
if ( total ) {
$( '.mygoods span' ).text( function( index, oldtext ) {
console.log( 'this is my old text ' + oldtext )
return oldtext ? oldtext - total : oldtext;
} );
}
}
}
$( '.panel' ).on( 'keyup', '.quantity', function() {
var sum;
container = $( this ).closest( 'div' );
quantity = Number( $( this ).val() );
price = Number( $( this ).closest( 'div' ).find( '.price' ).data( 'price' ) );
container.find( ".total span" ).text( quantity * price );
sum = 0;
$( ".sub-total" ).each( function() {
sum = sum + Number( $( this ).text() );
} )
$( '.mygoods span' ).text( sum );
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel" id="panel">
<div>
<div>
<p class="mygoods"> Total: <span></span></p>
</div>
</div>
</div>
Related
I have a form:
// 10 times
<input type="text" name="cityname" class="autocompletecity">
<input type="text" name="cityID" class="autocompletecityID">
When I enter the city name, it autocompletes the city name and the cityID from database with this code:
<?php for ($i = 0; $i < 10; $i++) { /*in the field class add $i */ ?>
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 1 );
}
$( ".autocompletecity<?php echo $i ?>" ).autocomplete({
source: "/*path to json*/",
select: function( event, ui ) {
var item = ui.item;
if(item) {
$(".autocompletecityID<?php echo $i ?>").val(item.cityID);
$(this).val(item.value +' ' + item.country);
return false;
}
}
//code from J.D.
select: function( event, ui ) {
var item = ui.item;
if(item) {
$('input[name="cityID"]').each(function(index, element) {
var $element = $(element);
if ($element.value() == item.cityID) {
alert('This city has already been selected');
}
});
}
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" +item.value + " " +item.country + "</a>" )
.appendTo( ul );
};
});
<?php } ?>
After it autocompletes the cityID, I would like to show an alert box if same cityID has alredy been entered: Click OK to confirm or Cancel to clear the cityname and cityID with repeated entry.
I tried to search in the jqueryui, but no luck...
Thanks!!
Try this:
select: function( event, ui ) {
var item = ui.item;
if(item) {
$('input[name="cityID"]').each(function(index) {
var $element = $(this);
if ($element.value() == item.cityID) {
alert('This city has already been selected');
}
});
}
}
I'm trying to build something similar to Facebook's posting system.
Goal: Display a new DIV below an INPUT TEXT field upon the user clicking POST. The DIV should display the contents of the text field.
This is what I have tried:
HTML
<div class="update">
<p>Update </p>
<div class="feed-me" ></div>
<input type="text" name="update status" Id="cmm_box" placeholder ="What's on your mind " />
<input type="button" value="post"/>
</div>
JavaScript/jQuery
<script >
var text front = "" ;
var text end = " #user name " ;
$(document).ready ( function ) {
$('input [ type=button] ' ).click(
function ( ) { update( ); }
);
});
function update( ) {
$( ' div.feed_me ' ) .html ( textfront + $ ( ' cmm_box ' ).val( ) + textend ) ;
$( ' div.feed_me ' ) .html ( textfront + $ ( ' cmm_box ' ).val( ) + textend ) ;
$( ' div.feed_me ' ) .html ( textfront + $ ( ' input [ name=update ] ' ).val( ) + textend ) ;
</script >
I have a string in Javascript,
'WorkExperience_0_companydetails_0_name'
I want to get the following string
'WorkExperience_1_companydetails_1_name'
How could I achieve this in jQuery?
Try,
"WorkExperience_0_companydetails_0_name".split("0").join('1');
Or
"WorkExperience_0_companydetails_0_name".replace("0","1");
DEMO
as you want to update its value by 1
var str="WorkExperience_0_companydetails_0_name";
var ar = str.split("_");
var n=parseInt(ar[1],10)+1;
var newStr = str.replace(ar[1],n);
<ul>
<div class="test"></div>
<li id="foo1">foo</li>
<li id="bar1" class="test">bar</li>
<li id="baz1">baz</li>
<div class="test"></div>
</ul>
<div id="last"></div>
var foo = $( "li" );
// This implicitly calls .first()
console.log( "Index: " + foo.index( "li" ) ); // 0
console.log( "Index: " + foo.first().index( "li" ) ); // 0
var baz = $( "#baz1" );
console.log( "Index: " + baz.index( "li" )); // 2
var listItem = $( "#bar1" );
console.log( "Index: " + listItem.index( ".test" ) ); // 1
var div = $( "#last" );
console.log( "Index: " + div.index( "div" ) ); // 2`enter code here`
I am using Jquery to dynamically add elements to my form and then remove them if necessary, I can do this when there is only one form being added, however my next form allows the user to add an ingredient and it adds a quantity element with it, I cant work out how to remove both the elements with a button. I have created a JSfiddle would be great if something could help.
http://jsfiddle.net/w5PKZ/
$(document).ready(function() {
var addDiv2 = $('#addIngredient');
var i = $('#addIngredient p').size() + 1;
$('#addNewIngredient').on('click', function () {
$('<p> <input id="step_' + i + '" size="40" name="ingredient[]' + '" type=text" value="" placeholder="Ingredient" /> </p>').appendTo(addDiv2);
$('<p> <input id="step_' + i + '" size="40" name="quantity[]' + '" type=text" value="" placeholder="Quantity" />Remove </p>').appendTo(addDiv2);
i++;
return false;
});
$(document).on('click','.remNew2', function () {
if (i > 3) {
$(this).parents('p').remove();
i - 2;
}
return false;
});
});
JSFIDDLE DEMO
Add the dynamic elements in a single paragraph <p> instead of 3 different paragraphs. This way you can keep your event handler AS IT IS.
$('#addNewIngredient').on('click', function () {
$('<p> <input id="step_' + i + '" size="40" name="ingredient[]' + '" type=text" value="" placeholder="Ingredient" /><input id="step_' + i + '" size="40" name="quantity[]' + '" type=text" value="" placeholder="Quantity" /> Remove </p> ').appendTo(addDiv2);
i++;
return false;
});
Try this
$(this).parent().prevAll(':lt(2)').remove().end().remove();
Your selection gets only the element "remove", you must also select the newly added using .prevAll()
Note: id's must be unique
DEMO
fiddle Demo
$(document).on('click', '.remNew2', function () {
if (i > 1) {
$(this).parents('p').prev().remove();
$(this).parents('p').prev().remove();
$(this).parents('p').remove();
i--;
}
return false;
});
try this
$('#addNewIngredient').on('click', function () {
console.log('clicked');
var newDiv = $("<div></div>");
$('<p> <input id="step_' + i + '" size="40" name="ingredient[]' + '" type=text" value="" placeholder="Ingredient" /> </p>').appendTo(newDiv);
$('<p> <input id="step_' + i + '" size="40" name="quantity[]' + '" type=text" value="" placeholder="Quantity" />').appendTo(newDiv);
$('<p> Remove </p>').appendTo(newDiv).click(function(){
newDiv.remove();
});
addDiv2.append(newDiv);
i++;
return false;
});
Updated fiddle http://jsfiddle.net/w5PKZ/10/
It is more efficient to build a basic tag and then individually add the arguments rather than passing in a long html string.
You can add the remove event handler directly to the individual anchors and pass in references to the elements you want removing if you do it all in the same scope as you create the elements:
JSFIDDLE
$(document).ready(function() {
var addDiv2 = $('#addIngredient');
var i = $('#addIngredient p').size() + 1;
$('#addNewIngredient').on('click', function () {
var p1 = $( '<p />' )
.appendTo(addDiv2),
p2 = $( '<p />' )
.appendTo(addDiv2),
p3 = $( '<p />' )
.appendTo(addDiv2),
ingredient = $( '<input />' )
.attr( 'id', 'ingredient_' + i )
.attr( 'size', '40' )
.attr( 'name', 'ingredient[]' )
.attr( 'type', 'text' )
.attr( 'placeholder', 'Ingredient' )
.val( $( '#ingredient_1' ).val() )
.appendTo( p1 ),
quantity = $( '<input />' )
.attr( 'id', 'quantity_' + i )
.attr( 'size', '40' )
.attr( 'name', 'quantity[]' )
.attr( 'type', 'text' )
.attr( 'placeholder', 'Quantity' )
.val( $( '#quantity_1' ).val() )
.appendTo( p2 ),
a = $( '<a />' )
.attr( 'href', '#' )
.text( 'Remove' )
.appendTo( p3 )
.on( 'click', function(e) {
p1.remove();
p2.remove();
p3.remove();
e.preventDefault();
// DO NOT DECREMENT i - you may get duplicate IDs
} );
i++;
return false;
});
});
You could also just add all the elements to p1 rather than creating multiple paragraphs (and it would be better semantically if you used div elements rather than p elements).
This code creates a group of elements (four inputs) on the fly. Once you create an element (four inputs) you can select/deselect, when you select an element will bring up the editor for the corresponding element. I've made a function to hide only the first element. The problem is that I can not make it comeback without affecting the other elements.
Instructions:
Click on the "Price" link, an element will be created on the fly (four nested inputs)
Select the element (four nested inputs) to bring up the editor ( one input and a brown little square).
Click on the little brown square to hide the first input of the element (four nested inputs) and that will hide the first input.
I need the little brown square to hide and show the same input.
Go here to see the full code:
To see the problem you have to create more than one element to find out.
http://jsfiddle.net/yjfGx/13/
This is the JS/jQuery code, for the full code go to the link above.
var _PriceID = 1;
$('#Price').on('click',function(){
var label = 'Price'
var Id = 'Price_';
var P = $( '<p class="inputContainer" />' ).fadeIn(100);
var l = $( '<label />' ).attr({'for':Id + _PriceID, 'id':Id + _PriceID, 'class':'priceLb'}).text( label ).after('<br/>');
var l1 = $( '<span class="dollar-sign" />' ).text( '$' ).css({"font-family":"Arial", "color":"#333", "font-weight":"bold"});
var input1 = $( '<input />' ).attr({ 'type':'text', 'name':'', 'class':'inputs',
'maxlength':'3', 'placeholder':'one',
'id':Id + _PriceID, 'class':'pricePh-1' })
.css({ "width":"60px", "paddingLeft":"1.3em", "paddingRight":"0.2em", "margin":"3px" });
var l2 = $( '<span class="priceComma-1" />' ).text( ',' ).css({"font-family":"Arial", "color":"#333", "font-weight":"bold"});
var input2 = $( '<input />' ).attr({ 'type':'text', 'name':'', 'class':'inputs', 'maxlength':'3',
'placeholder':'two', 'id':Id + _PriceID, 'class':'pricePh-2' })
.css({ "width":"68px", "paddingLeft":"0.7em", "paddingRight":"0.2em", "margin":"3px" });
var l3 = $( '<span class="priceComma-2" />' ).text( ',' ).css({"font-family":"Arial", "color":"#333", "font-weight":"bold"});
var input3 = $( '<input />' ).attr({ 'type':'text', 'name':'', 'class':'inputs', 'maxlength':'3',
'placeholder':'three', 'id':Id + _PriceID, 'class':'pricePh-3' })
.css({ "width":"64px", "paddingLeft":"1em", "paddingRight":"0.2em", "margin":"3px" }); var l4 = $( '<span />' ).text( ',' ).css({"font-family":"Arial", "color":"#333", "font-weight":"bold"});
var input4 = $( '<input />' ).attr({ 'type':'text', 'name':'', 'class':'inputs', 'maxlength':'2',
'placeholder':'four', 'id':Id + _PriceID, 'class':'pricePh-4' })
.css({ "width":"37px", "paddingLeft":"0.5em", "paddingRight":"0.2em", "margin":"3px" });
P.append( l, l1, input1, l2, input2, l3, input3, l4, input4);
var D = $( 'form' );
P.on({
mouseenter: function() {
$(this).addClass("pb");
},
mouseleave: function() {
$(this).removeClass("pb");
}
});
P.appendTo(D);
_PriceID++;
});
/*** Select element individually and load editor. ***/
var flag = false;
$("form").on("click", "p", function () {
var cur = $(this).css("background-color");
if (cur == "rgb(255, 255, 255)") {
if (flag == false) {
$(this).css("background-color", "#FDD");
LoadPriceProperties($(this));
flag = true;
}
} else {
$(this).css("background-color", "white");
$('.properties-panel').hide();
flag = false;
}
});
/*** Element editor ***/
var LoadPriceProperties = function (obj) {
$('.properties-panel').css('display', 'none');
$('#priceProps-edt').css('display', 'block');
var label = $('.priceLb', obj);
var price1 = $('.pricePh-1', obj);
var price2 = $('.pricePh-2', obj);
$('#SetPricePlaceholder-1').val(price1.attr('placeholder'));
$('#SetPricePlaceholder-2').val(price2.attr('placeholder'));
/*** Getting an answer, depending on what they click on. ***/
$('#fieldOptionsContainer_1 div').bind('click', function () {
if ($(this).hasClass('field-option-delete')) {
RemoveUnwantedPriceField1($(this));
} else {
/*** Function loacated on "line 98" ***/
HideUnwantedPriceField_1($(this));
}
});
_CurrentElement = obj;
};
function HideUnwantedPriceField_1() {
var input = $('.pricePh-1', _CurrentElement);
var comma = $('.priceComma-1', _CurrentElement);
if($(input).is(":hidden")){
} else {
input.hide();
comma.hide();
}
}
Do you mean something like this: http://jsfiddle.net/Zaf8M/
var items=$('.m>li'), set= $('.set input'), num=0, item=$('.item'), list=$('.list');
item.hide();
items.click(function(){
$(this).addClass('sel').siblings().removeClass('sel');
num=$(this).index()+1;
set.prop( "disabled", false );
});
$('.close').click(function(){alert(3);});
$(window).click(function(e){
if( e.target.className=='sel' || e.target.type=='text'){return;}
else {
items.removeClass('sel'); set.prop( "disabled", true );
}
if(set.val()!='') {
item.clone().show()
.appendTo(list).children('.n').text(num)
.siblings('.p').text(set.val());
set.val('');
}
if( e.target.className=='close' ){$(e.target).parent().remove();};
});