Create Dynamic tab in jquery-ui tab - javascript

I was doing a project on HTML and jQuery recently. Thing I want to achieve now is to create dynamic tab with particular data on a button click.
My code for JQuery-UI tab is
$(document).ready(function() {
var $tabs = $("#container-1").tabs();
var tabTemplate = "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>",
tabCounter = 2;
$('#add_tab').click( function(){
var label = 'New',
id = "tabs-" + tabCounter,
li = $( tabTemplate.replace( /#\{href\}/g, "#" + id ).replace( /#\{label\}/g, label ) ),
tabContentHtml = 'hi';
tabs.find( ".ui-tabs-nav" ).append( li );
tabs.append( "<div id='" + id + "'><p>" + tabContentHtml + "</p></div>" );
tabs.tabs( "refresh" );
tabCounter++;
});
$('#new').click( function(){
$tabs.tabs('select', 2);
});
});
My HTML file
<div id="container-1">
<ul>
<li>List</li>
</ul>
<div id="fragment-1">
</div>
</div>
<button id="add_tab">Add Tab</button>
When i click 'add' button in the console of firebug I'm get error:
ReferenceError: tabs is not defined
http://localhost:3000/
Line 38
I'm not so good with jquery-ui. How do I fix this problem?

The problem is with your script.So try this
$(document).ready(function() {
var tabs = $("#container-1").tabs();
var tabCounter = 1;
$('#add_tab').click( function(){
var ul = tabs.find( "ul" );
$( "<li><a href='#newtab'>New Tab</a></li>" ).appendTo( ul );
$( "<div id='newtab'>Name :<input type='text'></input></div>" ).appendTo( tabs );
tabs.tabs( "refresh" );
tabs.tabs('select', 1);
});
});

the only problem in your code was that you defined in the beginning $tabs and later called for tabs without the dollar sine. I just removed the dollar sine and it works the way you expected (note the var tabs definition on second line) ... I aswel added code to the jsfiddle.
$(document).ready(function() {
var tabs = $("#container-1").tabs();
var tabTemplate = "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>",
tabCounter = 2;
$('#add_tab').click( function(){
var label = 'New',
id = "tabs-" + tabCounter,
li = $( tabTemplate.replace( /#\{href\}/g, "#" + id ).replace( /#\{label\}/g, label ) ),
tabContentHtml = 'hi';
tabs.find( ".ui-tabs-nav" ).append( li );
tabs.append( "<div id='" + id + "'><p>" + tabContentHtml + "</p></div>" );
tabs.tabs( "refresh" );
tabCounter++;
});
$('#new').click( function(){
$tabs.tabs('select', 2);
});
});

Related

How to retrieve old text and subtract from total - JS

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>

Include same jsp page in all jQuery tabs

I want to include same JSP page in all jQuery tabs with unique tab ids, i.e. same Comment.jsp file in all jQuery tabs of CommentTab.html.
When I run the following code I am able to create new tabs but JSP page contents are not shown in any tab.
<script>
$(function() {
var tabTitle = $( "#tab_title" ),
tabContent = $( "#tab_content" ),
tabTemplate = "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close'>Remove Tab</span></li>",
tabCounter = 2;
var tabs = $( "#tabs" ).tabs();
// modal dialog init: custom buttons and a "close" callback reseting the form inside
var dialog = $( "#dialog" ).dialog({
autoOpen: false,
modal: true,
buttons: {
Add: function() {
addTab();
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
form[ 0 ].reset();
}
});
// addTab form: calls addTab function on submit and closes the dialog
var form = dialog.find( "form" ).submit(function( event ) {
addTab();
dialog.dialog( "close" );
event.preventDefault();
});
// actual addTab function: adds new tab using the input from the form above
function addTab() {
var label = tabTitle.val() || "Tab " + tabCounter,
id = "tabs-" + tabCounter,
li = $( tabTemplate.replace( /#\{href\}/g, "#" + id ).replace( /#\{label\}/g, label ) ),
//tabContentHtml = tabContent.val() || "Tab " + tabCounter + " content.";
tabContentHtml = getComments();
tabs.find( ".ui-tabs-nav" ).append( li );
tabs.append( "<div id='" + id + "'><p>" + tabContentHtml + "</p></div>" );
tabs.tabs( "refresh" );
tabCounter++;
}
function getComments(){
$( "#success" ).load( "Comment.jsp", function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
}
// addTab button: just opens the dialog
$( "#add_tab" )
.button()
.click(function() {
dialog.dialog( "open" );
});
// close icon: removing the tab on click
$( "#tabs span.ui-icon-close" ).live( "click", function() {
var panelId = $( this ).closest( "li" ).remove().attr( "aria-controls" );
$( "#" + panelId ).remove();
tabs.tabs( "refresh" );
});
});
</script>
<body>
<div id="dialog" title="Tab data">
<form>
<fieldset class="ui-helper-reset">
<label for="tab_title">Title</label> <input type="text"
name="tab_title" id="tab_title" value=""
class="ui-widget-content ui-corner-all" />
<div id="tab_content" class="ui-widget-content ui-corner-all"></div>
</fieldset>
</form>
</div>
<button id="add_tab">Add Tab</button>
<div id="tabs">
<ul>
<div id="success"></div>
</ul>
The problem was solved using iframe. The modified part of the code is as follows:
The script part:
<script>
$(function() {
var tabTitle = $( "#tab_title" ),
tabContent = $( "#tab_content" ),
tabTemplate = "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close'>Remove Tab</span></li>",
tabCounter = 2;
var websiteframe = '<iframe src="Comment.jsp" width="100%" height="100%" allowtransparency="true" frameBorder="0">Your browser does not support IFRAME</iframe>';
var tabs = $( "#tabs" ).tabs();
Then include websiteframe in addTab() function:
function addTab() {
var label = tabTitle.val() || "Tab " + tabCounter,
id = "tabs-" + tabCounter,
li = $( tabTemplate.replace( /#\{href\}/g, "#" + id ).replace( /#\{label\}/g, label ) ),
websiteframe = '<iframe src="Comment.jsp" width="100%" height="100%" allowtransparency="true" frameBorder="0">Your browser does not support IFRAME</iframe>';
tabs.find( ".ui-tabs-nav" ).append( li );
tabs.append( "<div id='" + id + "'>" + websiteframe + "</div>" );
tabs.tabs( "refresh" );
tabCounter++;
}
The html part:
<button id="add_tab">Add Tab</button>
<div id="tabs">
<ul>
</ul>
</div>

replace sub string in javascript string

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`

Jquery trying to remove dynamically made elements

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).

Js/jQuery - How to hide/show an input created on the fly?

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();};
});

Categories

Resources