I am trying to call two functions when only the "add" button is clicked. the problem I am having is that the final four textboxes in the calculate_balances function are not outputting their variables.
var $ = function (id) {
return document.getElementById(id);
}
// Declare Arrays to store information from Inputs //
var transactions = [];
transactions[0] = []; // holds date
transactions[1] = []; // holds transaction type
transactions[2] = []; // holds amount
// Function to print results to text area //
var update_results = function () {
var list = ""; // string variable to build output //
// check to see if arrays are empty //
if (transactions[0].length == 0) {
$("results").value = "";
} else {
list = "";
// for loop to cycle through arrays and build string for textarea output //
for (var i = 0; i < transactions[0].length; i++) {
list += transactions[0][i] + " " + transactions[1][i] + " " + transactions[2][i] + "\n";
}
// display results //
$("results").value = list;
}
}
// function to gather inputs //
var add_transaction = function () {
$("add").blur();
transactions[0][transactions[0].length] = $("date").value;
transactions[1][transactions[1].length] = $("transType").value;
transactions[2][transactions[2].length] = parseFloat( $("amount").value);
update_results();
calculate_balances();
}
// function for Calculations //
var calculate_balances = function () {
var startBal = 2000.00;
var ttlDeposits = 0;
var ttlWithdrawals = 0;
var endBal = startBal;
if (transactions[1][transactions[1].length] == "deposit")
{
ttlDeposits += transactions[2][transactions[2].length];
endBal += ttlDeposits;
}
if (transactions[1][i] == "withdrawal")
{
ttlWithdrawals += transactions[2][transactions[i]];
endBal -= ttlWithdrawals;
}
$("balStart").value = parseFloat(startBal);
$("ttlDeposits").value = parseFloat(ttlDeposits);
$("ttlWithdrawals").value = parseFloat(ttlWithdrawals);
$("balEnd").value = parseFloat(endBal);
}
window.onload = function () {
$("add").onclick = add_transaction, calculate_balances;
update_results();
}
tHank you
Edit: Did not realize the OP was NOT using jQuery. Your onclick should look like this:
$("add").onclick = function(){
add_transaction();
calculate_balances();
};
The rest here is for jQuery which is not what the OP wanted.
For setting the value of a text box with jQuery use the val() method:
$("balStart").val(parseFloat(startBal));
To call the two methods when the button is clicked:
$("add").click(function(){
add_transaction();
calculate_balances();
});
Related
I am building an application that takes in grade and then gives the average. It also has a sort button that makes it so you can sort by the last name of the student entered and a clear button to clear the current values that are in the display array. Here is the code I have so far for the javascript file:
var $ = function (id) {return document.getElementById(id);}
"use strict";
var scoreArray = [];
var dispArray = [];
var displayScores = function () {
var totalScore = 0;
var numberOfScores = 0;
var averageScore = 0;
numberOfScores = scoreArray.length;
//loop to find the total score
for (var i=0;i<numberOfScores;i++)
{
totalScore = totalScore + scoreArray[i];
}
//find the average
averageScore = totalScore/numberOfScores;
var st="";
//put the string in the display array
for(var i=0; i<numberOfScores;i++)
{
st += (dispArray[i]+"\n");
}
//display the average score
$("#average_score").val(averageScore.toString());
$("#scores").val(st);
};
$("#add_button").click(function(){
var scoreNumber = parseInt( $("#score").val());
var scoreString = $("#last_name").val() + ", " + $("first_name").val() + ": " + $("#score").val();
scoreArray.push(scoreNumber);
dispArray.push(scoreString);
displayScores();
//reset the values
$("#first_name").val("");
$("#last_name").val("");
$("#score").val("");
$("#first_name").focus();
});
//function to clear the contents of the form
$("#clear_button").click(function(){
//empty the arrays
scoreArray=[];
dispArray=[];
//reset the values in the form
$("#scores").val("");
$("#first_name").val("");
$("#last_name").val("");
$("average_score").val("");
$("#score").val("");
});
//function to sort the scores based on the last name that was entered
$("#sort_button").click(function(){
var mylen = scoreArray.length;
//sorting
for(var kk=0;kk<mylen;kk++)
{
for(var aa = 1; aa<(mylen-kk);aa++)
{
var xp1 = dispArray[aa-1].split(" ");
var lname1 = xp1[0];
lname1 = lname1.slice(0, -1);
var xp2 = dispArray[aa].split(" ");
var lname2 = xp2[0];
lname2 = lname2.slice(0, -1);
if (lname1 > lname2){
var tp1 = scoreArray[aa];
scoreArray[aa]=scoreArray[aa-1];
scoreArray[aa-1] = tp1;
var tp2 = dispArray[aa];
dispArray[aa]=dispArray[aa-1];
dispArray[aa-1] = tp2;
}
}
}
//display the scores
$("#scores").val("");
var st=" ";
for(var i=0;i<dispArray.length;i++)
{
st += (dispArray[i]+"\n");
}
//display the sorted scores
$("scores").val(st);
});
$("#first_name").focus();
It is giving the error: Uncaught TypeError: Cannot read property 'click' of null
at scores.js:38
Line 38 is the click function for the add button to add the score to the display array: $("#add_button").click(function(){
Any thoughts on this?
This is happening because you've defined $ as a function which returns the result of document.getElementById().
What you've not accounted for is what happens if this operation finds no element, in which case it returns null, and there is no .click() method of null.
In short: your selector #add_button seems not to be finding the intended element. So check your DOM, and the presence of the element, before running that line. Always suspect your selectors. Either that or build in a check that only goes to .click() on finding an element successfully.
let el = $('#add_button');
if (el) el.click(...);
Here is my issue:
I have RadListBox and I'm trying to get the values and append them so the result would be displayed like that: '1,2,3,4' but I'm getting back : 1,2,3,4,
Does anyone know how can I achieve that?
Problem starts here:
var sbLocationsIDS = new StringBuilder();
for (i = 0; i < LocationIDS.get_items().get_count(); i++) {
sbLocationsIDS.append(LocationIDS.getItem(i).get_value()+ ",");
}
The result: sbLocationsIDS =1,2,3,4, instead of '1,2,3,4'
The Rest of the Code:
function openNewTab(url) {
var captureURL = url;
var win = window.open(captureURL, '_blank');
win.focus();
}
function GetComparisonsReport(sender, args) {
var isValid = Page_ClientValidate('validateComparisons');
if (isValid) { // If its true is going to fire the rest of the code
var SessionID = getUrlVars()["SessionID"];
var companyCodeVal = document.getElementById("<%=hfC.ClientID%>").value;
var LocationIDS = $find("<%=rlbSelectedLocation.ClientID %>");
var CategoriesIDS = $find("<%=rlbSelectedCategory.ClientID %>");
var fileType = $find("<%=rcbFileType.ClientID %>");
var fromFirstPeriod = $find("<%=rdpFromFirstPeriod.ClientID %>");
var toFirstPeriod = $find("<%=rdpToFirstPeriod.ClientID %>");
var fromSecondPeriod = $find("<%=rdpFromSecondPeriod.ClientID %>");
var toSecondPeriod = $find("<%=rdpToSecondPeriod.ClientID %>");;
if (LocationIDS.get_items().get_count() < 0) {
radalert("Please choose locations and select the Add button.<h3 style='color: #ff0000;'></h3>", 420, 170, "Case Global Alert");
return;
}
if (CategoriesIDS.get_items().get_count() < 0) {
radalert("Please choose categories and select the Add button.<h3 style='color: #ff0000;'></h3>", 420, 170, "Case Global Alert");
return;
}
var fromFirstPeriodDateValSelected = fromFirstPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
var toFirstPeriodDateValSelected = toFirstPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
var fromSecondPeriodDateValSelected = fromSecondPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
var toSecondPeriodDateValSelected = toSecondPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
var fileTypeValSelected = fileType.get_selectedItem().get_value();
var sbLocationsIDS = new StringBuilder();
for (i = 0; i < LocationIDS.get_items().get_count(); i++) {
sbLocationsIDS.append(LocationIDS.getItem(i).get_value()+ ","); // The problem is here!!!
}
var sbCategoriesIDS = new StringBuilder();
for (i = 0; i < CategoriesIDS.get_items().get_count(); i++) {
sbCategoriesIDS.append(CategoriesIDS.getItem(i).get_value() + ",");
}
var ComparisonsURL = (String.format("https://www.test.com/cgis/{0}/reports/ConnectTorptIncidentsCountByLocationInterval.asp?SessionID={1}&locString={2}&catString={3}&FromDate1={4}&&ToDate1={5}&FromDate2={6}&ToDate2={7}&ExportType={8}", companyCodeVal, SessionID, sbLocationsIDS, sbCategoriesIDS, fromFirstPeriodDateValSelected, toFirstPeriodDateValSelected, fromSecondPeriodDateValSelected, toSecondPeriodDateValSelected, fileTypeValSelected));
openNewTab(ComparisonsURL);
}
}
String.format = function () {
// The string containing the format items (e.g. "{0}")
// will and always has to be the first argument.
var theString = arguments[0];
// start with the second argument (i = 1)
for (var i = 1; i < arguments.length; i++) {
// "gm" = RegEx options for Global search (more than one instance)
// and for Multiline search
var regEx = new RegExp("\\{" + (i - 1) + "\\}", "gm");
theString = theString.replace(regEx, arguments[i]);
}
return theString;
}
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
vars[key] = value;
});
return vars;
}
// Initializes a new instance of the StringBuilder class
// and appends the given value if supplied
function StringBuilder(value) {
this.strings = new Array("");
this.append(value);
}
// Appends the given value to the end of this instance.
StringBuilder.prototype.append = function (value) {
if (value) {
this.strings.push(value);
}
}
// Clears the string buffer
StringBuilder.prototype.clear = function () {
this.strings.length = 1;
}
// Converts this instance to a String.
StringBuilder.prototype.toString = function () {
return this.strings.join("");
}
The problem is your loop is appending , always even for the last item in the loop.
You want to append only for all items other than the last. There are multiple ways to do that, simplest being: check if the current element is the last and if so, do not append ,
var sbLocationsIDS = new StringBuilder();
for (i = 0; i < LocationIDS.get_items().get_count(); i++) {
sbLocationsIDS.append(LocationIDS.getItem(i).get_value()); //append only value
if(i != (LocationIDS.get_items().get_count() -1)) { //if not last item in list
sbLocationsIDS.append(","); //append ,
}
}
There are other ways to do it, and depending on what you want to do with the values in the future, these may be pretty useful. (I see that the append in your code is actually a call to join, so this is actually a simpler version)
Add the values of the list to a array and use Array.join:
var select = document.getElementById("locationId");
var options = select.options;
var optionsArray = [];
if(options) {
for (var i=0; i<=options.length; i++) {
//text is the text displayed in the dropdown.
//You can also use value which is from the value attribute of >option>
optionsArray.push(options[i].text);
}
}
var sbLocationsIDS = optionsArray.join(",");
With JQuery, the above code becomes a bit more simple:
var optionsArray = [];
$("#locationId option").each(function(){
optionsArray.push(options[i].text);
});
var sbLocationsIDS = optionsArray.join(",");
Actually, if you decide yo use JQuery, you can use jquery.map:
(idea from Assigning select list values to array)
$(document).ready(function() {
$("#b").click(function() {
var sbLocationsIDS = jQuery.map($("#locationId option"), function(n, i) {
return (n.value);
}).join(",");
alert(sbLocationsIDS);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="locationId">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button id="b">Click</button>
I'm getting HTML from a forum url, and parsing the post count of the user from their profile page. I don't know how to write the parsed number into the Google spreadsheet.
It should go account by account in column B till last row and update the column A with count.
The script doesn't give me any errors, but it doesn't set the retrieved value into the spreadsheet.
function msg(message){
Browser.msgBox(message);
}
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu("Update")
.addItem('Update Table', 'updatePosts')
.addToUi();
}
function getPostCount(profileUrl){
var html = UrlFetchApp.fetch(profileUrl).getContentText();
var sliced = html.slice(0,html.search('Posts Per Day'));
sliced = sliced.slice(sliced.search('<dt>Total Posts</dt>'),sliced.length);
postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
return postCount;
}
function updatePosts(){
if(arguments[0]===false){
showAlert = false;
} else {
showAlert=true;
}
var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var accountSheet = spreadSheet.getSheetByName("account-stats");
var statsLastCol = statsSheet.getLastColumn();
var accountCount = accountSheet.getLastRow();
var newValue = 0;
var oldValue = 0;
var totalNewPosts = 0;
for (var i=2; i<=accountCount; i++){
newValue = parseInt(getPostCount(accountSheet.getRange(i, 9).getValue()));
oldValue = parseInt(accountSheet.getRange(i, 7).getValue());
totalNewPosts = totalNewPosts + newValue - oldValue;
accountSheet.getRange(i, 7).setValue(newValue);
statsSheet.getRange(i,statsLastCol).setValue(newValue-todaysValue);
}
if(showAlert==false){
return 0;
}
msg(totalNewPosts+" new post found!");
}
function valinar(needle, haystack){
haystack = haystack[0];
for (var i in haystack){
if(haystack[i]==needle){
return true;
}
}
return false;
}
The is the first time I'm doing something like this and working from an example from other site.
I have one more question. In function getPostCount I send the function profileurl. Where do I declare that ?
Here is how you get the URL out of the spreadsheet:
function getPostCount(profileUrl){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var thisSheet = ss.getSheetByName("List1");
var getNumberOfRows = thisSheet.getLastRow();
var urlProfile = "";
var sliced = "";
var A_Column = "";
var arrayIndex = 0;
var rngA2Bx = thisSheet.getRange(2, 2, getNumberOfRows, 1).getValues();
for (var i = 2; i < getNumberOfRows + 1; i++) { //Start getting urls from row 2
//Logger.log('count i: ' + i);
arrayIndex = i-2;
urlProfile = rngA2Bx[arrayIndex][0];
//Logger.log('urlProfile: ' + urlProfile);
var html = UrlFetchApp.fetch(urlProfile).getContentText();
sliced = html.slice(0,html.search('Posts Per Day'));
var postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
sliced = sliced.slice(sliced.search('<dt>Total Posts</dt>'),sliced.length);
postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
Logger.log('postCount: ' + postCount);
A_Column = thisSheet.getRange(i, 1);
A_Column.setValue(postCount);
};
}
You're missing var in front of one of your variables:
postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
That won't work. Need to put var in front. var postCount = ....
In this function:
function updatePosts(){
if(arguments[0]===false){
showAlert = false;
} else {
showAlert=true;
}
There is no array named arguments anywhere in your code. Where is arguments defined and how is it getting any values put into it?
I have a main function generatePersonDatasheet(theses) and I have a handler function submit(e) (the handler is in other function called showList()).
In the main function, I can call the handler function this way:
if (theses == 1){
Logger.log("going to showList() ");
return showList();
If I drop de return in the line return showList(); the UI of showList() opens and closes at a fraction of second, not allowing the user choose the items. If I put this return, after the handler function submit(e) is closed, the code in my main function doesn't run the next line after the if block:
if (theses == 1){
Logger.log("going to showList() ");
return showList();
}
showURL(docName, link); // Shows document name and link in UI
How could I fix that? How could I got the main function to runs its lines after the if (theses == 1) block? I didn't want to repeat the code in the handler function because it's bigger than the line showURL(docName, link); in the above sample.
This is the called functions:
var fact_list = [ ["Kennedy Inauguration", "politics", "tZwnNdFNkNklYc3pVUzZINUV4eUtWVWFSVEf"], ["Pericles’ Funeral Oration", "politics", "sdgrewaNkNklYc3pVUzZINUV4eUtW345ufaZ"], ["The Pleasure of Books", "culture", "1234rFszdgrfYc3pVUzZINUV4eU43usacd"], ["I Am The First Accused (Nelson Mandela)", "law", "34rsgadOsidjSZIswjadi95uydnfklsdks"] ];
function showList() {
Logger.log("running showList ");
var mydoc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication();
var panel = app.createVerticalPanel().setId('panel');
// Store the number of items in the array (fact_list)
Logger.log("fact_list.length " + fact_list.length);
panel.add(app.createHidden('checkbox_total', fact_list.length));
// add 1 checkbox + 1 hidden field per item
for(var i = 0; i < fact_list.length; i++){
Logger.log("checkbox_isChecked_"+i + " = " + fact_list[i][0]);
Logger.log("checkbox_value_"+i + " = " + fact_list[i]);
var checkbox = app.createCheckBox().setName('checkbox_isChecked_'+i).setText(fact_list[i][0]);
var hidden = app.createHidden('checkbox_value_'+i, fact_list[i]);
panel.add(checkbox).add(hidden);
}
var handler = app.createServerHandler('submit').addCallbackElement(panel);
panel.add(app.createButton('Submit', handler));
app.add(panel);
mydoc.show(app);
}
function submit(e){
Logger.log("running submit(e)");
var numberOfItems = e.parameter.checkbox_total;
var itemsSelected = [];
// for each item, if it is checked / selected, add it to itemsSelected
for(var i = 0; i < numberOfItems; i++){
if(e.parameter['checkbox_isChecked_'+i] == 'true'){
itemsSelected.push(e.parameter['checkbox_value_'+i]);
}
}
var app = UiApp.getActiveApplication();
Logger.log("itemsSelected = " + itemsSelected);
ScriptProperties.setProperties({'theses': itemsSelected}, true);
var thesesArrays = ScriptProperties.getProperty('theses');
Logger.log("thesesArrays = " + thesesArrays);// to see targetDoc's content
for (var i = 0; i < thesesArrays.lenght; i++){
var thesesId = ScriptProperties.getProperty('theses')[i][2];
var thesesType = ScriptProperties.getProperty('theses')[i][1];
importTheses(target, thesesId, thesesType);
}
app.close();
return app;
}
function importTheses(targetDocId, thesesId, thesesType) { // adapted from Serge insas
Logger.log("running importTheses() ");
var targetDoc = DocumentApp.openById(targetDocId);
var targetDocParagraphs = targetDoc.getParagraphs();
var targetDocElements = targetDocParagraphs.getNumChildren();
var thesesDoc = DocumentApp.openById(thesesId);
var thesesParagraphs = thesesDoc.getParagraphs();
var thesesElements = thesesDoc.getNumChildren();
var eltargetDoc=[];
var elTheses=[];
for( var j = 0; j < targetDocElements; ++j ) {
var targetDocElement = targetDoc.getChild(j);
// Logger.log(j + " : " + type);// to see targetDoc's content
eltargetDoc[j]=targetDocElement.getText();
if(el[j]== thesesType){
for( var k = 0; k < thesesParagraphs-1; ++k ) {
var thesesElement = thesesDoc.getChild(k);
elTheses[k] = thesesDoc.getText();
targetDoc.insertParagraph(j, elTheses[k]);
}
}
}
}
Please have a look at this worflow, wouldn't it be more easy ?
(check the log to confirm the last function was called)
note : I didn't use scriptProperties as it was not necessary anymore since factList is a global variable in your example... and I simplified the importTheses function for this test since I had no docs to use ;-)
var fact_list = [["Kennedy Inauguration", "politics", "tZwnNdFNkNklYc3pVUzZINUV4eUtWVWFSVEf"], ["Pericles Funeral Oration", "politics", "sdgrewaNkNklYc3pVUzZINUV4eUtW345ufaZ"], ["The Pleasure of Books", "culture", "1234rFszdgrfYc3pVUzZINUV4eU43usacd"], ["I Am The First Accused (Nelson Mandela)", "law", "34rsgadOsidjSZIswjadi95uydnfklsdks"]];
function showList() {
var mydoc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication();
var panel = app.createVerticalPanel().setId('panel');
// Store the number of items in the array (fact_list)
panel.add(app.createHidden('checkbox_total', fact_list.length));
// add 1 checkbox + 1 hidden field per item
for(var i = 0; i < fact_list.length; i++){
var checkbox = app.createCheckBox().setName('checkbox_isChecked_'+i).setText(fact_list[i][0]);
panel.add(checkbox);
}
var handler = app.createServerHandler('submit').addCallbackElement(panel);
panel.add(app.createButton('Submit', handler));
app.add(panel);
mydoc.show(app);
}
function submit(e){
var numberOfItems = Number(e.parameter.checkbox_total);
var thesesArrays = [];
for(var i = 0; i < numberOfItems; i++){
if(e.parameter['checkbox_isChecked_'+i] == 'true'){
thesesArrays.push(fact_list[i]);
}
}
Logger.log(thesesArrays);
var target = 'target doc';
for (var i = 0; i < thesesArrays.length; i++){
var thesesId = thesesArrays[i][2];
var thesesType = thesesArrays[i][1];
importTheses(target, thesesId, thesesType);
}
// showURL(docName, link); /
return UiApp.getActiveApplication().close();
}
function importTheses(targetDocId, thesesId, thesesType) { // adapted from Serge insas
Logger.log(targetDocId+' '+thesesId+' '+thesesType);
}
When I try var a = ar_url2.concat(ar_desc2); to join my arrays into one it returns null. I'm sure it's trivial but I spent a few hours stuck on this now and an explanation as why this is happening would be great. In my code bellow I tried while(ar_url2.length)a.push(ar_url2.shift()); and it returns same null...
function agregar() {
var i = 0,
textarea;
var ar_desc = [];
while (textarea = document.getElementsByTagName('textarea')[i++]) {
if (textarea.id.match(/^desc_([0-9]+)$/)) {
ar_desc.push(textarea.id);
}
}
var desc_count_demo = document.getElementById('desc_count').value;
var desc_count = desc_count_demo - 1;
i = 0;
var ar_desc2 = [];
var campo = null;
while (i <= desc_count) {
campo = document.getElementById(ar_desc[i]).value;
ar_desc2[ar_desc[i]] = campo;
i++;
}
i = 0;
var input;
var ar_url = [];
while (input = document.getElementsByTagName('input')[i++]) {
if (input.id.match(/^url_([0-9]+)$/)) {
ar_url.push(input.id);
}
}
var url_count_demo2 = document.getElementById('url_count').value;
var url_count2 = url_count_demo2 - 1;
i = 0;
var ar_url2 = [];
while (i <= url_count2) {
campo = document.getElementById(ar_url[i]).value;
ar_url2[ar_url[i]] = campo;
i++;
}
// var a = Array.prototype.concat.call(ar_url2, ar_desc2);
while (ar_url2.length) a.push(ar_url2.shift());
function url(data) {
var ret = [];
for (var d in data)
ret.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
return ret.join("&");
}
window.open('alta1.php?'+url(a));
}
EDIT: If I pass to function url(ar_url2) or url(ar_desc2) the returned values in the URL are
http://localhost/proj1/alta1.php?url_0=inpit&url_1=input
and
http://localhost/proj1/alta1.php?desc_0=input&desc_1=input
But still cannot merge both into one...
One thing I see is your ar_url Array is filled by:
while(input=document.getElementsByTagName('input')[i++]){
if(input.id.match(/^url_([0-9]+)$/)){
ar_url.push(input.id);
}
}
Since you the putting the whole id in the array, it will be filled with things like: 'url_0', 'url_1', 'url_2', etc...
Later you do:
ar_url2[ar_url[i]] = campo;
When you index into ar_url, you get out the 'url_XXX' strings. That means you are setting the 'url_XXX' properties on ar_url2 instead of filling in the elements of the array.
Try changing your second loop to:
while(input=document.getElementsByTagName('input')[i++]){
var result;
if(result = input.id.match(/^url_([0-9]+)$/)){
ar_url.push(+result[1]);
}
}
To use the value captured in the ([0-9]+) portion of the RegExp instead of the entire 'url_XXX' string.