I have a page with the following html that appears numerous times with different phone numbers:
<div class="crm-content crm-contact_phone primary">
<span>5555551212</span>
</div>
The phone number itself is displayed using a smarty variable in the form {$phone.i.phone}, where i is the array key in an array of phone numbers.
I want to be able to change the format of these phone numbers using js.
So for just one phone number, I was using the following in my smarty .tpl file:
{literal}
cj(function($){
var phoneNumber = {/literal}{$phone.1.phone}{literal};
var phoneNumberFormatted = '(' + phoneNumber.substr(0,3) + ') ' + phoneNumber.substr(3,3) + '-' + phoneNumber.substr(6);
$(".crm-contact_phone span").text(phoneNumberFormatted);
});
{/literal}
So I figure, I need to do something along the lines of:
$('.crm-contact_phone span').each(function(i, obj) {
var phoneNumber = '' + {/literal}{$phone.1.phone}{literal};
}
but I have no idea how to replace the 1 inside the smarty variable, with the javascript index i.
Any ideas? Thanks.
Try this
$('.crm-contact_phone span').each(function(i, obj) {
var phoneNumber = '' + {/literal}{$phone[i].phone}{literal};
}
Use the bracket Notation and replace it with i .
I took a different approach in the end, saving the entire smarty array to a js array using the following:
var phoneNumbers = {/literal}{$phone|#json_encode}{literal};
I could then just access the phone number by using pure js:
var phoneNumber = phoneNumbers[i]['phone'];
Related
i could not make it as function.Please help.When i modified as function and add button,it not work.
i'm newbie in javascript.i would like study by the simple script.But for the below script when i try to add "function xxx()" it not working with input button.
I try to solve by my own with google...failed.
<script>
var myStr = "xxx yyy zzz";
var strArray = myStr.split(" ");
// Display array values on page
for(var i = 0; i < strArray.length; i++){
document.write("<p>" + strArray[i] + "</p>");
}
</script>
Break your code into blocks if you ever are stuck on something. So first you are trying to break a string into an array so that's your first block. Then your second block would be to write it to the page. So we have our code basically written out in our heads.
---Break string
---Display broken string
So to make a function we need to write a function first
myFunction = function(){
};
But to get the function to be modular we need to be able to pass in variables
So we'll add two variables one being the string to pass through and one being the location to inject the looped broken text.
myFunction = function(str, location){
};
Now we have to do something with these variables.
myFunction = function(str, location){
///test if str is a string
if(typeof(str) == "string")
{
var l = str.split(" "); /// here we're spliting the string into an array by every space
if(l.length >= 1) ///test if there's atleast one item
for(i=0;i<l.length;i++) ///simple for loop
location.innerHTML += "This is a part of str " + l[i] + "<br>" ///you can do anything here you want to do.
}
};
Now as you can see it's modular at it's lowest point, this can be as complex as you want it. here is a test you can try out and mess around with. https://jsfiddle.net/s8pytzm3/1/
I'm trying to send an SQL query with javascript using a variable sourced from an input. In this input, characters like ' and " along with others may be entered.
Here's what my script function looks like:
function insertJobDesc (r) {
rowid=r;
var qty = document.getElementById('Qty' + r).value;
var desc = document.getElementById('Desc' + r).value;
desc = desc.replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, '"""').replace(/'/g, '"'"');
sendAsync("editDatabase.php?sql=UPDATE+jobdesc+SET+qty="+qty+",+description='"+desc+"',+rowID="+rowid+"+WHERE+id="+rowid+"+AND+jobID="+jobID);
}
An example of the value for 'desc' that I'd want to send is:
80-0234-1 6'5" GATE
So it's a combination of numbers, letters, and special characters.
I tried to replace each of them but it didn't work out.
Any ideas?
Use encodeURIComponent()
function insertJobDesc (r) {
rowid=r;
var qty = document.getElementById('Qty' + r).value;
var desc = encodeURIComponent(document.getElementById('Desc' + r).value);
sendAsync("editDatabase.php?sql=UPDATE+jobdesc+SET+qty="+qty+",+description='"+desc+"',+rowID="+rowid+"+WHERE+id="+rowid+"+AND+jobID="+jobID);
}
Disclaimer: Don't ever do anything like this...
I use stringify() method in JavaScript to convert a list of objects to a string, but I need to customize the output on the first level ONLY like the following:
[
/*T01*/ {"startX":55,"endX":109,"sartY":0,"endY":249},
/*T02*/ {"startX":110,"endX":164,"sartY":0,"endY":249},
/*T03*/ {"startX":165,"endX":219,"sartY":0,"endY":249},
/*T04*/ {"startX":220,"endX":274,"sartY":0,"endY":249},
/*T05*/ {"startX":275,"endX":329,"sartY":0,"endY":249},
/*T06*/ {"startX":330,"endX":384,"sartY":0,"endY":249},
/*T07*/ {"startX":385,"endX":439,"sartY":0,"endY":249},
/*T08*/ {"startX":440,"endX":494,"sartY":0,"endY":249},
/*T09*/ {"startX":495,"endX":549,"sartY":0,"endY":249},
/*T10*/ {"startX":550,"endX":604,"sartY":0,"endY":249}
]
Now there are other parameters in stringfy() method, replacer and space, can't I use them to format my output like the aforementioned format including:
tabs
spaces
comments
You are not going to get JSON.parse to make that output since it is not valid JSON. But if you want to have something rendered like that, it is a simple loop and string concatenation.
var details = [
{"startX":55,"endX":109,"sartY":0,"endY":249},
{"startX":110,"endX":164,"sartY":0,"endY":249},
{"startX":165,"endX":219,"sartY":0,"endY":249},
{"startX":220,"endX":274,"sartY":0,"endY":249},
{"startX":275,"endX":329,"sartY":0,"endY":249},
{"startX":330,"endX":384,"sartY":0,"endY":249},
{"startX":385,"endX":439,"sartY":0,"endY":249},
{"startX":440,"endX":494,"sartY":0,"endY":249},
{"startX":495,"endX":549,"sartY":0,"endY":249},
{"startX":550,"endX":604,"sartY":0,"endY":249}
];
var out = "[\n" + details.map(function(val, i) {
var id = "\t/*T" + ("0" + (i + 1)).substr(-2) + "*/\t";
return id + JSON.stringify(val);
}).join(",\n") + "\n]";
console.log(out);
I'm injecting text into page using jquery like this
$("#myDiv").text(someWebServiceResponse.Data);
this returned data is in most cases numbers divided with commas but in some cases can be
string as a title which is followed with numbers
Returned data case without title
1,2,3,4,89,11
Returned data case with title
MyTitle 1,2,3,4,89,11
Returned data case with title
MyTitle2 1,2,35,4,89,14
Those title and number values are dynamic ofcourse.
How can I recognize if returned data contains title (maybe using typeofstring) and
modify this returned string with title + and than numbers in next line
Given that the numbers are divided only by , and not by space, you can easily test if the string contains empty space.
Like this
function containsTitle(input) {
return input.indexOf(' ') > 0;
}
...
if (containsTitle(someWebServiceResponse.Data)) {
//TODO: split for 2 lines or whatever you need
}
With your quoted examples, just find the last space if any and insert the plus sign:
var lastSpace = yourString.lastIndexOf(' ');
if (lastSpace != -1) {
yourString = yourString.substring(0, lastSpace) + " +" + yourString.substring(lastSpace);
}
Live Example:
test("1,2,3,4,89,11");
test("MyTitle 1,2,3,4,89,11");
test("MyTitle2 1,2,35,4,89,14");
function test(yourString) {
var lastSpace = yourString.lastIndexOf(' ');
if (lastSpace != -1) {
yourString = yourString.substring(0, lastSpace) + " +" + yourString.substring(lastSpace);
}
snippet.log(yourString);
}
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
try this:-
var isTitle=function(txt){
var first=txt.substr(0,txt.indexOf(','));
return !$.isNumeric(first);
}
//here how to use
alert(isTitle('1,2,3,4,89,11'));
alert(isTitle('MyTitle 1,2,3,4,89,11'));
Demo
I'm trying to append a some HTML to a code in jquery, but chrome keeps throwing "unexpected string" at the append function, here's the code :
for (var i =0 ;i<resultArray.length;i++){
$.ajax({url:"getExpenseInfo.php",type:"POST",data : {
'expenseId' : resultArray[i]["expenseId"]
},success:function(expense){
expense = $.parseJSON(expense);
$("#mainDiv").append("<div class=\"row\">".expense["expenseName"]."</div>");
}});
}
I guess you're mixing up php and js syntax, string concatenation works with + in js and not ..
$("#mainDiv").append("<div class=\"row\">" + expense["expenseName"] + "</div>");
Your string concatenation in your append function is a little off. Try something like this:
for (var i =0 ;i<resultArray.length;i++){
$.ajax({url:"getExpenseInfo.php",type:"POST",data : {
'expenseId' : resultArray[i]["expenseId"]
},success:function(expense){
expense = $.parseJSON(expense);
$("#mainDiv").append("<div class=\"row\">"+expense[expenseName]+"</div>");
}});
}