replace sub string in javascript string - javascript

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`

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>

Display a post under the form after submitting it

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 >

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>

JavaScript Recursion to format lists from XML to HTML

I have an exercise where it calls upon me to use recursion to output XML data into HTML list tags. Shamefully admitting my shortcomings in mathematics, I would like someone to show me how to implement recursive logic to XML's 'node structure' using JavaScript.
Here is the outcome: JSFiddle
EDIT
Added sample XML to round off this topic and deleted unneeded code. The XML used to create the recursive function:
<ddm>
<menu0 submenu="true"><name>Welcome</name>
<menu1>Home Page</menu1>
<menu1>Bulletin</menu1>
</menu0>
<menu0 submenu="true"><name>Members\' Area</name>
<menu1>Constitution & Bylaws</menu1>
<menu1 submenu="true"><name>AGM Minutes</name>
<menu2>2012</menu2>
<menu2>2011</menu2>
</menu1>
</menu0>
<menu0>About</menu0>
</ddm>
<ddm>
You call your recursive function once with your top level element. Every child element will simply call the same function. When you get to the bottom, you stop, and everything gets passed back up.
This should get your started (a sample of your xml).
Demo:
Output:
Script:
document.getElementById( 'parse' ).addEventListener( 'click', function () {
var xml = '<ddm>'
+ '<menu0 submenu="true"><name>Welcome</name>'
+ '<menu1>Home Page</menu1>'
+ '<menu1>Bulletin</menu1>'
+ '</menu0>'
+ '<menu0 submenu="true"><name>Members\' Area</name>'
+ '<menu1>Constitution & Bylaws</menu1>'
+ '<menu1 submenu="true"><name>AGM Minutes</name>'
+ '<menu2>2012</menu2>'
+ '<menu2>2011</menu2>'
+ '</menu1>'
+ '</menu0>'
+ '<menu0>About</menu0>'
+ '</ddm>',
xmlDoc = new DOMParser().parseFromString( xml, 'text/xml' ),
html = nodeMarkup( xmlDoc.documentElement );
document.getElementById( 'result' ).innerHTML = html;
} );
function nodeMarkup( node ){
if( node.childNodes.length ) {
var list = '', header = '';
for( var index = 0; index < node.childNodes.length; index++ ) {
if( node.childNodes[index].tagName == 'name' ) {
header = node.childNodes[index].textContent;
} else {
list += nodeMarkup( node.childNodes[index] );
};
};
return node.hasAttribute( 'submenu' )
? '<li>' + header + '<ul>' + list + '</ul></li>'
: list;
} else {
return '<li>' + node.textContent + '</li>';
};
};
HTML:
<input type="button" id="parse" value="Parse" />
<ul id="result"></ul>
CSS:
#result {
list-style-type: none;
margin: 0;
padding: 0;
}

Create Dynamic tab in jquery-ui tab

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

Categories

Resources