.clone doesn't not appear to be incrementing - javascript

this script is suppose to clone a new row of a HTML table. It does not seem to be incrementing the name, id, attributes. What am I doing wrong? The only other thing that is not working is get the value from the previous input id of #endtime_* and putting it in the cloned input id of #starttime_* although I think that is because it does seem to be incrementing as it clones a row.
<script type="text/javascript">
function MaskTime(){
var index = $("#TimeCard tbody>tr").length-1;
$('#endtime_'+index).mask("99:99 aa");
$('#starttime_'+index).mask("99:99 aa");
}
function update_rows(){
$("#TimeCard tbody>tr:odd").css("background-color", "#FFF");
$("#TimeCard tbody>tr:even").css("background-color", "#999");
}
$(document).ready(function() {
$("#addrow").click(function() {
var row = $('#TimeCard tbody>tr:last').clone(true).insertAfter('#TimeCard tbody>tr:last');
var index = $("#TimeCard tbody>tr").length-1;
var endvalue = $('#endtime_'+index-1).val();
$("td:eq(0) select").attr("name", 'type_'+index).attr("id", 'type_'+index).addClass("validate[required]").val('')
$("td:eq(1)").html(" ")
$("td:eq(2) select").attr("name", 'propid_'+index).attr("id", 'propid_'+index).addClass("validate[required]").val('')
$("td:eq(3)").html(" ")
$("td:eq(4) input").attr("name", 'starttime_'+index).attr("id", 'starttime_'+index).addClass("validate[required,custom[timeclock]]").val(endvalue)
$("td:eq(5) input").attr("name", 'endtime_'+index).attr("id", 'endtime_'+index).addClass("validate[required,custom[timeclock]]").val('')
$("td:eq(6)").html(" ")
update_rows();
MaskTime();
return false;
});
});
</script>

For the first part of your question:
It does not seem to be incrementing the name, id, attributes.
Your script isn't giving the proper context for where the tds are for which you want to modify the attribues, etc.
Here's a modification that corrects that, adding a new variable "newrow" (to reduce DOM calls) and modifying the lines of code related to td:eq(#)...
$(document).ready(function() {
$("#addrow").click(function() {
var row = $('#TimeCard tbody>tr:last').clone(true).insertAfter('#TimeCard tbody>tr:last');
var index = $("#TimeCard tbody>tr").length-1;
var endvalue = $('#endtime_'+index-1).val();
var newrow = $("#TimeCard tbody>tr:last");
newrow.children("td:eq(0)").children("select").attr("name", 'type_'+index).attr("id", 'type_'+index).addClass("validate[required]").val('')
newrow.children("td:eq(1)").html(" ")
newrow.children("td:eq(2)").children("select").attr("name", 'propid_'+index).attr("id", 'propid_'+index).addClass("validate[required]").val('')
newrow.children("td:eq(3)").html(" ")
newrow.children("td:eq(4)").children("input").attr("name", 'starttime_'+index).attr("id", 'starttime_'+index).addClass("validate[required,custom[timeclock]]").val(endvalue)
newrow.children("td:eq(5)").children("input").attr("name", 'endtime_'+index).attr("id", 'endtime_'+index).addClass("validate[required,custom[timeclock]]").val('')
newrow.children("td:eq(6)").html(" ")
update_rows();
MaskTime();
return false;
});
});
Also, I'd made a jsfiddle with the above: http://jsfiddle.net/m78UN/2/
I'm not following what you're wanting when you describe your second problem:
The only other thing that is not working is get the value from the previous input id of #endtime_* and putting it in the cloned input id of #starttime_*
...so I've not attempted to address that.

I think you can do everything you're doing in a way simpler way. I don't have your original HTML, but check this out as a possible alternative. It mainly does 3 things:
Removed IDs used for finding things
Caches selectors
Adds classes to time inputs to make them easier to reference
Removed MaskTime() function
Here's the code:
$(document).ready(function() {
var $timecard = $("#TimeCard");
var $tbody = $timecard.find("tbody");
var $rows = $tbody.children("tr");
$("#addrow").click(function(e) {
e.preventDefault(); // clearer than return false
var $lastRow = $tbody.find("tr:last-of-type");
var lastEnd = $lastRow.find(".endTime").val();
var $newRow = $lastRow.clone(true).appendTo($tbody);
var $cols = $newRow.find("td");
var index = $rows.length - 1;
$cols.eq(0).find("select").attr("name", 'type_' + index).addClass("validate[required]").val('');
$cols.eq(1).empty();
$cols.eq(2).find("select").attr("name", 'propid_' + index).addClass("validate[required]").val('');
$cols.eq(3).empty();
$cols.eq(4).find("input").attr("name", 'starttime_' + index).addClass("time startTime validate[required,custom[timeclock]]").val(lastEnd);
$cols.eq(5).find("input").attr("name", 'endtime_' + index).addClass("time endTime validate[required,custom[timeclock]]").val('');
$cols.eq(6).empty();
update_rows(); // no idea what this is
$newRow.find(".time").mask("99:99 aa"); // MaskTime() just did this
});
});

Related

How to use different blogger post ID in Javascript variable?

I am trying to make every article views having comma separated every 3 digit number. I have found the code for that.
But I have problem to find specific blogger post ID to use for the code to work fine.
Here's the whole code that I am trying to work on.
<--Viewable area /-->
<span class='entry-time'><b:if cond='data:allBylineItems.author and data:allBylineItems.timestamp.label'><span class='on'><data:allBylineItems.timestamp.label/></span></b:if><time class='published' expr:datetime='data:post.date.iso8601'><data:post.date/></time></span><span class='postviews1' style='margin-left:5px; display:display;'><a expr:name='data:post.id'/> <i class='far fa-eye'/> <span id='bacani'><span id='postviews'/></span> Views</span>
<--comma separated every 3 digit /-->
<script>var angka = document.getElementById('bacani').textContent;var reverse = angka.toString().split('').reverse().join(''),ribuan = reverse.match(/\d{1,3}/g);ribuan = ribuan.join(',').split('').reverse().join('');document.getElementById('bacani').innerHTML= ribuan;</script>
<--code for views count /-->
<script src='https://cdn.firebase.com/v0/firebase.js' type='text/javascript'/> <script> $.each($("a[name]"), function(i, e) { var elem = $(e).parent().find("#postviews"); var blogStats = new Firebase("https://sh-v-3da10-default-rtdb.firebaseio.com/" + $(e).attr("name")); blogStats.once("value", function(snapshot) { var data = snapshot.val(); var isnew = false; if(data == null) { data= {}; data.value = 0; data.url = window.location.href; data.id = $(e).attr("name"); isnew = true; } elem.text(data.value); data.value++; if(window.location.pathname!="/") { if(isnew) blogStats.set(data); else blogStats.child("value").set(data.value); } }); });</script>
I want to change:
<span id='bacani'><span id='postviews'/></span>
and
document.getElementById('bacani').textContent;
to have a specific value id which is post id from blogger. The only thing that i found from internet is
<data:post.id>
Is there any other way that i can make it work other than what I am thinking right now? I think I need specific new id to make it work for every article to have comma separated every 3 digit.
I try to use the code but it only work for one time only. I believe to make it work as a whole I need to use different code to read specific unique id base on data:.post.id from blogger post id itself. But i do not sure how to make it work. I am expecting when I know how to use different method which is making new code that find unique id for different article it would work fine.
You can just replace elem.text(data.value) to
// original count
var count = data.value;
// count separated by comma
var separatedCount = count.toString()
.split('').reverse().join('')
.match(/\d{1,3}/g).join(',')
.split('').reverse().join('');
elem.text(separatedCount);
The full code would be
<!-- code for views count -->
<script src='https://cdn.firebase.com/v0/firebase.js' type='text/javascript'/>
<script>
/*<![CDATA[*/
$.each($("a[name]"), function (i, e) {
var elem = $(e).parent().find("#postviews");
var blogStats = new Firebase("https://sh-v-3da10-default-rtdb.firebaseio.com/" + $(e).attr("name"));
blogStats.once("value", function (snapshot) {
var data = snapshot.val();
var isnew = false;
if (data == null) {
data = {};
data.value = 0;
data.url = window.location.href;
data.id = $(e).attr("name");
isnew = true;
}
// original count
var count = data.value;
// count separated by comma
var separatedCount = count.toString()
.split('').reverse().join('')
.match(/\d{1,3}/g).join(',')
.split('').reverse().join('');
elem.text(separatedCount);
data.value++;
if (window.location.pathname !== "/") {
if (isnew) blogStats.set(data); else blogStats.child("value").set(data.value);
}
});
});
/*]]>*/
</script>

Find ID in String using match

I'm building a widget that will generate a graph for an element when it is double clicked on the page. Without remaking all widgets this is the only way for me to tackle the problem.
I want find the ID of a widget from the html of an element.
All widgets I want to work are inside a div element panel_content_id_#
I want to find the number found on the line of code
var io_id=32715;
How can I search the string for this pattern and get the number (32715).
$('div[id^="panel_content_id_"]').dblclick(function(e){
console.log($(this).attr('id'));
var code = $(this).html();
// Find ID
var id = -1;
var search = code.match("var io_id=");
if(search > -1){
}
console.log($(this).html());
});
The line of code im looking for will look like so
var io_id=xxxxx;
Where xxxxx = some random number I dont know
I want to find xxxxx
Split it in two parts - All the code before the var io_id= and the other part is after that.
And then you know that the line ends with ;, so from that second part you cut of the stuff that is before the semicolon.
CODE
$('div[id^="panel_content_id_"]').dblclick(function(e){
console.log($(this).attr('id'));
var code = $(this).html();
// Find ID
var id = -1;
if (code.indexOf("var io_id")>-1) {
id = parseInt(code.split("var io_id=")[1].split(";")[0]);
}
if(search > -1){
console.log("The code betrayed me");
}
console.log("The id is: " +id);
});
Maybe you could try this regex pattern:
\d+(?! var io_id=)
Used like this:
$('div[id^="panel_content_id_"]').dblclick(function(e) {
console.log($(this).attr('id'));
var code = $(this).html();
// Find ID
var id = -1;
var search = code.match("var io_id=");
if (search) { // Edited
// New code
alert(code.match(/\d+(?! var io_id=)/gim));
}
console.log($(this).html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="panel_content_id_32715">
Div content
<br><br>
var io_id=32715;
</div>

Format number with commas in .each function

So I have some js which is converting a div class's number through a daily exchange rate engine. It outputs correctly as it should and I am now trying to separate this number it outputs using jQuery and a function I found whilst doing some research. I am trying to feed the number to the function using a .innerHTML method. I have got the function to alert a converted number but I have multiple elements which this function should run for, so have used an .each function - this is where something isn't working. I get no alert so I think there is something wrong with the .each code.
Can anyone see anything that might be causing it?
The complete code is here:
<script src="https://raw.githubusercontent.com/openexchangerates/money.js/master/money.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<div class="hello">
2300
</div>
<div class="hello">
52400
</div>
<script>
function ReplaceNumberWithCommas(yourNumber) {
//Seperates the components of the number
var n= yourNumber.toString().split(".");
//Comma-fies the first part
n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//Combines the two sections
return n.join(".");
}
$(".hello").each(function() {
var currentDiv = $(this);
var currentPrice = currentDiv.text();
var demo = function(data) {
fx.rates = data.rates
var rate = fx(currentPrice).from("GBP").to("USD");
currentDiv.html("<div>"+currentPrice +"</div><div id='converted'> " +rate.toFixed(0)+"</div>");
//alert("Product Costs" + rate.toFixed(4))
}
$.getJSON("http://api.fixer.io/latest", demo);
});
$("#converted").each(function() {
var convertedPrice = $(this.innerHTML);
function runThis() { alert( ReplaceNumberWithCommas(convertedPrice)) }
setTimeout (runThis, 100);
});
</script>
I think the reason is
$("#converted").each(function() {
var convertedPrice = $(this.innerHTML);
function runThis() { alert( ReplaceNumberWithCommas(convertedPrice)) }
setTimeout (runThis, 100);
});
happends before you created the converted elements. Because you put the creation inside a get call.
I suggest you put this inside the callback of your get call.
Something like this
function ReplaceNumberWithCommas(yourNumber) {
//Seperates the components of the number
var n = yourNumber.toString().split(".");
//Comma-fies the first part
n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//Combines the two sections
return n.join(".");
}
var currentDiv = $(this);
var currentPrice = currentDiv.text();
var demo = function(data) {
fx.rates = data.rates
$(".hello").each(function() {
var currentDiv = $(this);
var currentPrice = currentDiv.text();
var rate = fx(currentPrice).from("GBP").to("USD");
currentDiv.html("<div>" + currentPrice + "</div><div class='converted'> " + rate.toFixed(0) + "</div>");
//alert("Product Costs" + rate.toFixed(4))
});
$(".converted").each(function() {
var convertedPrice = $(this).html();
console.log(ReplaceNumberWithCommas(convertedPrice));
});
}
$.getJSON("https://api.fixer.io/latest", demo);

Need text in input to not display user input once sent

Here is my jQuery, I have it working properly but once my row is added the user input in the inputs are still there and not cleared. How do I fix this?
// Removing menu rows
$('.menu-items').on('click', '.delete', function(){
$(this).closest('.menu-row').remove();
});
// HTML
var MENU_ROW_TEMPLATE = '<div class="menu-row"><span class="item-description">$description</span><div class="control-items"><span class="item-price">$price</span><span class="delete">X</span></div></div>'
// Adding menu rows
$('.menu-category').on('click', 'button', function(){
var $row = $(this).closest('.add-item');
var name = $row.find('input').first().val();
var price = $row.find('input').last().val();
var newRowHtml = MENU_ROW_TEMPLATE.replace('$description', name).replace('$price', price);
var $newRow = $(newRowHtml);
var $lastMenuRow = $row.closest('.menu-category').find('.menu-row').last();
$newRow.insertAfter($lastMenuRow);
});
Sorry for my poor explaining skills.
Clear the name and price after you get the values...
...
var name = $row.find('input').first().val();
var price = $row.find('input').last().val();
$row.find('input').first().val('');
$row.find('input').last().val('');
...

can't get the dynamic textfield value using Jquery

I can't get the dynamic textfield value. Please see the below my jquery code.
I added onclick event while creating the textfield for LandMark. Please see the below code.
I am always getting undefined. Please help me.
function dynamicEvent() {
alert("dynamic event");
$(document).ready(function(){
alert("inside ajax --> dynamic");
var table = document.getElementById("dataTable");
alert("table-->"+table);
var rowCount = table.rows.length;
alert("rowCount-->"+rowCount);
alert("value of rowCount"+rowCount);
var uniqueId;
for (var i=rowCount;rowCount>7;i++){
uniqueId = i;
alert("inside for loop");
alert("uniqueId-->"+uniqueId);
var element = document.createElement("input");
uniqueId=uniqueId-1;
element.id = "t02Travelfrom" +uniqueId;
var tfrom=element.id;
alert("tfrom id-->"+tfrom);
var t02Travelfrom=$("tfrom").val();
alert(tfrom+"--value-->" +t02Travelfrom);
}
});
}
You have incorrect selector:
var t02Travelfrom=$("tfrom").val();
change to:
var t02Travelfrom=$("#" + tfrom).val();
$("tfrom") returning elements with tag tfrom
You need $(tfrom). You don't need double quotas.

Categories

Resources