How to add auto-increment in the DOM - javascript

I have a problem to add auto-increment function in the javascript. For example if Kod Terakhir is 100-1/5, when showing the input field is 100-1/6, that mean every time will detect from the Kod Terakhir number and add 1 behind the number.
Below is my javascript code:
var id_selected = selectObject.value;
var cate_id_selected = selectObject.selectedOptions[0].getAttribute("data-cat_id");
var root_selected = selectObject.selectedOptions[0].getAttribute("data-root");
var action = 'find_max_code';
$.ajax({
url:'?f=kod_perfailan',
type:'POST',
data:{id_selected: id_selected,
cate_id_selected: cate_id_selected,
root_selected: root_selected,
action: action
},
success:function(data) {
if(data.trim() !== ""){
// document.getElementById("function_code_last").innerHTML = "*Kod Terakhir: " + data;
document.getElementById("activity_code_last").innerHTML = "*Kod Terakhir: " + data;
document.getElementById("sub_activity_code_last").innerHTML = "*Kod Terakhir: " + data;
document.getElementById("transaction_code_last").innerHTML = "*Kod Terakhir: " + data;
document.getElementById("activity_code").value = data + 1;
document.getElementById("sub_activity_code").value = data + 1;
document.getElementById("transaction_code").value = data + 1;
}else{
// document.getElementById("function_code_last").innerHTML = "*Tiada Data Disimpan";
document.getElementById("activity_code_last").innerHTML = "*Tiada Data Disimpan";
document.getElementById("sub_activity_code_last").innerHTML = "*Tiada Data Disimpan";
document.getElementById("transaction_code_last").innerHTML = "*Tiada Data Disimpan";
}
}
Below is my output, but it is wrong, because the input field should be 100-1/6, not 100-1/51. I think my code data + 1; here is got problem.
Actually I want the success output is below the picture:
So that, below is the input field may show the number format (example):
100-1/xxxx
100-1/5/xxxx
100-1/5/10/xxxx
256-1/10/xxxx
That means, xxxx number need to add 1 every time to do the auto-increment. My number is store in the data.
Hope someone can guide me how to solve this problem. Thanks.

You need to tokenize the string, remove and increment the part that you are interested in. It seems that you are simply performing a string concatenation operation.
function incrementSubActivityCode(sac) {
var p = sac.lastIndexOf("/") + 1;
return (p === 0) ? sac :
sac.substr(0, p) + (parseInt(sac.substr(p)) + 1);
}
// Example value
var data = "100-1/5/10/5";
// Incorrect - performs concatenation
document.getElementById("sub_activity_code").value = data + 1;
// Corrected - now performs increment
document.getElementById("sub_activity_code").value = incrementSubActivityCode(data);

Related

How to get bitcoin price from bitstamp

i want to show bitcoin price but there are several exchangers. i want to get from bitstamp only but positions of exchangers are changing and can't get only one
i wrote some code on jquery but i can't finish it
$.getJSON('https://chain.so/api/v2/get_price/BTC/USD', function(data) {
var text = ` ${data.data.prices[1].price} `
var integer = parseFloat(text, 10)
var percent = 3
var display = (integer - (integer/100 * percent)).valueOf()
$(".mypanel").html(display.toPrecision(7) + '$');
});
if you want to get request with jquery you should use $.get() and I write you code again (jquery version 3.3.1) get more detail
$(document).ready(function() {
var url= "https://chain.so/api/v2/get_price/BTC/USD";
$.get(url,function(data){
var text = ` ${data.data.prices[1].price} `
var integer = parseFloat(text, 10)
var percent = 3
var display = (integer - (integer/100 * percent)).valueOf()
$(".mypanel").html(display.toPrecision(7) + '$');
console.log(data);
})
});
https://jsfiddle.net/unqL14gs/4/

Nesting a function returning NaN

I am running into an error when I try nesting a simple counter function inside an existing function. I know some people frown upon this, so if there is any other way of doing this, it would be greatly appreciated. Basically, I am calling a function to parse a JSON string to get 3 numbers. I would like to animate those 3 numbers with a counter every time a new calculation is made. My instinct is to place this counter function inside of the same for loop that runs to get the numbers themselves. Doing so returns NaN. I'm sure there is something very little that I am missing here that I am hoping someone can pick up on.
Code:
var text = '{JSON data}'
var obj = JSON.parse(text);
function calculate() {
var e = document.getElementById("ltSpecialtyList");
var selectedSpec = e.options[e.selectedIndex].text;
console.log(selectedSpec);
var x = document.getElementById("ltLocationList");
var selectedState = x.options[x.selectedIndex].text;
console.log(selectedState);
for (i = 0; i < obj.values.length; i++)
{
if (obj.values[i].State == selectedState && obj.values[i].Specialty == selectedSpec)
{
// DISPLAY RESULTS DIV (JQUERY)
var $resultsDiv = $("#ROI-results");
$resultsDiv.fadeIn();
// CAPTURE HEADER SPAN NAMES
var headerState = document.getElementById("header-state-name");
var headerSpec = document.getElementById("header-specialty-name");
// CLEAR STATE AND SPECIALTY FROM SPAN
headerState.innerHTML = "";
headerSpec.innerHTML = "";
// ADD SELECTED STATE AND SPECIALTY
headerState.innerHTML += selectedState;
headerSpec.innerHTML += selectedSpec;
// CAPTURE RESULT DATA DIVS
var permResults = document.getElementById("ROI-results-perm-data");
var locumResults = document.getElementById("ROI-results-locums-data");
var uncollectedResults = document.getElementById("ROI-results-uncollected-data");
// CLEAR DATA DIVS
permResults.innerHTML = "";
locumResults.innerHTML = "";
uncollectedResults.innerHTML = "";
//POPULATE DIV WITH DATA
permResults.innerHTML += "<p class='ROI-results-data-number univers-bold'>" + obj.values[i].Permanent + "</p>";
locumResults.innerHTML += "<p class='ROI-results-data-number univers-bold'>" + obj.values[i].Locums + "</p>";
uncollectedResults.innerHTML += "<p class='ROI-results-data-number univers-bold'>" + obj.values[i].Gross + "</p>";
}
// COUNTER
$('.ROI-results-data-number').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
}
}

Need some help on logic (Xpages : Javascript) To get update Candidate No by Add on 1 if found item

View itself is sorted by decending order!(First column is "New_Exam_No")
currentExamNo = doc.getItemValueString("New_Exam_No");
var Candvw:NotesView = database.getView("(Exam Application Subject Sort by ExamNo)");
var CandEntry:NotesViewEntry=Candvw.getEntryByKey(doc.getItemValueString("New_Exam_No"),true);
if (CandEntry!=null) //If have exam no, use this condition
{
var CandDoc = CandEntry.getDocument()
if (Canddoc.hasItem("Candidate_No")==true) // assign Candidate No yet?Yes!
{
var CandNo = Canddoc.getItemValueString("Candidate_No");
LCandNo = "LSBS"
MidCandNo = #Left(CandNo,7)
MCandNo = #TextToNumber(#Right(MidCandNo,2)) + 1;
CNo = #Right("00"+#Text(MCandNo),2);
RExamNo = currentExamNo;
CandidateNo = LCandNo + "/" + CNo + "/" +RExamNo ;
}
else
{
CandidateNo = "LSBS/01/" + currentExamNo;
}
}
else
{
CandidateNo = "LSBS/01/" + currentExamNo;
}
Why i always get the LSBS/01/examno as it doesn't add on 1.
getEntryByKey() takes a Vector rather than a String. Try:
var key:java.util.Vector = new java.util.Vector();
key.add(doc.getItemValueString("New_Exam_No"));
var CandEntry:NotesViewEntry=Candvw.getEntryByKey(key,true);
It's been a while since I used SSJS, but I think that should work.

How to Increase the numurical value of 3rd column in a particular row when some one click on the link which is in the 2nd column of same row

How to increase the numerical value of 3rd column in a particular row when some one click on the link which is in the 2nd column of same row? Data loads from firebase in tabular form.
Fiddle here, so you can understand it much better.
The script which loads (callback) data from firebase is given bellow
var LEADERBOARD_SIZE = 10;
var get_title = $('title').html();
var get_id = $('id').find('textarea').html();
// Create our Firebase reference
var scoreListRef = new Firebase('https://androidappania.firebaseio.com//AlternateLinksDirectory//' + get_id);
// Keep a mapping of firebase locations to HTML elements, so we can move / remove elements as necessary.
var htmlForPath = {};
// Helper function that takes a new score snapshot and adds an appropriate row to our leaderboard table.
function handleScoreAdded(scoreSnapshot, prevScoreName) {
var newScoreRow = $("");
newScoreRow.append($("").append($("").text(scoreSnapshot.val().name)));
newScoreRow.append($("").text(scoreSnapshot.val().url));
newScoreRow.append($("").text(scoreSnapshot.val().score));
// Store a reference to the table row so we can get it again later.
htmlForPath[scoreSnapshot.name()] = newScoreRow;
// Insert the new score in the appropriate place in the table.
if (prevScoreName === null) {
$("#leaderboardTable").append(newScoreRow);
} else {
var lowerScoreRow = htmlForPath[prevScoreName];
lowerScoreRow.before(newScoreRow);
}
}
// Helper function to handle a score object being removed; just removes the corresponding table row.
function handleScoreRemoved(scoreSnapshot) {
var removedScoreRow = htmlForPath[scoreSnapshot.name()];
removedScoreRow.remove();
delete htmlForPath[scoreSnapshot.name()];
}
// Create a view to only receive callbacks for the last LEADERBOARD_SIZE scores
var scoreListView = scoreListRef.limit(LEADERBOARD_SIZE);
// Add a callback to handle when a new score is added.
scoreListView.on('child_added', function (newScoreSnapshot, prevScoreName) {
handleScoreAdded(newScoreSnapshot, prevScoreName);
});
// Add a callback to handle when a score is removed
scoreListView.on('child_removed', function (oldScoreSnapshot) {
handleScoreRemoved(oldScoreSnapshot);
});
// Add a callback to handle when a score changes or moves positions.
var changedCallback = function (scoreSnapshot, prevScoreName) {
handleScoreRemoved(scoreSnapshot);
handleScoreAdded(scoreSnapshot, prevScoreName);
};
scoreListView.on('child_moved', changedCallback);
scoreListView.on('child_changed', changedCallback);
// When the user presses enter on scoreInput, add the score, and update the highest score.
$("#scoreInput").keypress(function (e) {
if (e.keyCode == 13) {
var newScore = ($("#scoreInput").val());
var url1 = $("#urlInput").val();
var name = $("#nameInput").val();
$("#scoreInput").val("");
if (url1.length === 0)
if (name.length === 0) return;
var userScoreRef = scoreListRef.child(name);
// Use setWithPriority to put the name / score in Firebase, and set the priority to be the score.
userScoreRef.setWithPriority({
name: name,
url: url1,
score: newScore
}, newScore);
alert('Alternate Link for this App has been Succesfully submitted by you. By using this service you agree that you will Not Spam or Submit Links which refers to illegal or Copyrighted content.');
}
});
// delay function to make link clickable after 4 sec and also add onclick='HitCounter()' into links
var delay = 4000 //4 seconds
setTimeout(function () {
function replaceURLWithHTMLLinks(text) {
var re = /(\(.*?)?\b((?:https?|ftp|file):\/\/[-a-z0-9+&##\/%?=~_()|!:,.;]*[-a-z0-9+&##\/%=~_()|])/ig;
return text.replace(re, function (match, lParens, url) {
var rParens = '';
lParens = lParens || '';
var lParenCounter = /\(/g;
while (lParenCounter.exec(lParens)) {
var m;
if (m = /(.*)(\.\).*)/.exec(url) || /(.*)(\).*)/.exec(url)) {
url = m[1];
rParens = m[2] + rParens;
}
}
return lParens + "" + url + "" + rParens;
});
}
var elm = document.getElementById('leaderboardTable');
elm.innerHTML = replaceURLWithHTMLLinks(elm.innerHTML);
$(document).ready(function () {
$("a[href^='http://']").filter(function () {
return this.hostname && this.hostname !== location.hostname;
}).attr('target', '_blank');
});
}, delay)
and the script which take care of URL Hit Counts is given bellow
function HitCounter() {
var get_id = $('id').find('textarea').html();
var HitCounterRef = new Firebase('https://androidappania.firebaseio.com//AlternateLinksDirectory//' + get_id);
var hits = $(tbody).find('tr').children('td').html();
if (hits == null) {
hits = 1;
} else {
hits++;
}
HitCounterRef.setWithPriority({
score: hits
}, hits);
};
I need some modification or improvement in this code so that when some one click on a link then correct corresponding 3rd column of same row should get a increment/increase in it's numerical value.
I also need something which could create connection b/w HitCounter and urls given in 2nd column of every row or initiate the HitCounter function when some one click on any of the link given in 2nd column of every row.

Jquery- Dynamic added fields - prevent the last Item to be removed

I have a form field that is being duplicated / removed dynamically
See the fiddle here : http://jsfiddle.net/obmerk99/y2d4c/6/
In this feature, I also need to increment the NAME of the field ( and ID etc.. ) like so :
o99_brsa_settings[brsa_dash_wdgt_content][0]
o99_brsa_settings[brsa_dash_wdgt_content][1]
o99_brsa_settings[brsa_dash_wdgt_content][2] ...
It is working, but the problem is that when I add / remove fields , when it gets to the last ( actually first one ) , it will give me "undefined" and will not add anymore fields .
To see the problem you will need to "play" a bit with add/remove .
I believe the main problem is how to keep all of those on the same array level if we have [0] and [0][2]
I am far from a JS guru, and this code was somehow assembled from various sources. But I am kind of stuck right now, So any help will be appreciated .
Try this way:
$(function () {
$(".addScnt").on("click", function () {
var i = checkNumberOfElements();
var scntDiv = $("div[id^='widget_dup']:last");
var prevDiv = scntDiv.clone();
var newname = $(prevDiv).find("textarea").attr("name").substring(0, $(prevDiv).find("textarea").attr('name').indexOf(']'));
prevDiv.find('textarea').attr('name', newname + "][" + i + "]");
prevDiv.find('textarea').attr('id', newname + "][" + i + "]");
prevDiv.find('label').attr('for', newname + "][" + i + "]");
prevDiv.attr('id', $(prevDiv).attr('id') + "_" + i);
$(scntDiv).after(prevDiv);
});
$(document).on("click", ".remScnt", function (event) {
var i = checkNumberOfElements();
if (i <= 1) {
return false;
} else {
var target = $(event.currentTarget);
target.parent("div").remove();
}
});
});
function checkNumberOfElements() {
// Number of textareas
var i = $("textarea[name^='o99_brsa_settings[brsa_dash_wdgt_content]']").length;
// Number of divs
// var i = $("div[id^='widget_dup']").length;
if (typeof i === undefined) {
return 0;
} else {
return i;
}
}
Demo: http://jsfiddle.net/y2d4c/7/

Categories

Resources