Printing PHP string using JQuery - javascript

I got a script which uses an array that was created in PHP and was encoded to JSON. It then take the string and use it to set a value for an element I created:
var val ="";
if(arr != null)
{
if((arr[i] != undefined) && (arr[i]["value"] != undefined))
{
var val = JSON.stringify(arr[i]["value"]);
val.replace(/"/g , "");
}
}
cell.innerHTML = "<input type='text' value='"+val+"' style='padding-right: 0px;'/>";
The problem is that every string on the screen appears with the "" around the string itself. for example "5". I want it to be just 5 and not "5". I thought the replace I did to the val was supposed to do it but it didn't work. why is that?

OK the problem is just something I keep forgetting all the time.
The line val.replace(/"/g , ""); is missing its magic and should be:
val = val.replace(/"/g , "");
I'm leaving the question so other people might be able to see how to decode a JSON string and how to use an array which was created in PHP.

Related

Compare two variable string in JavaScript

i am trying to compare two strings in javascript. below is my code
var statuss = document.getElementById("status").innerHTML;
//alert(statuss);
var s =statuss.toString();
var ss= "Active";
if (s === "Active"){
alert ('match');
}
else {
alert ('do not match');
}
why am i getting the output " do not match" when it should have been 'match' since when i did
alert ('document.getElementById("status").innerHTML');
i got the output: Active.
So basically both variable should have matched.. why am getting the opposite?
You might want to try the following
var s = statuss.toString().trim();
The most likely explanation is that your HTML also contains whitespace at the beginning and/or end.

Split last word value in JavaScript string [duplicate]

This question already has answers here:
How to retrieve GET parameters from JavaScript [duplicate]
(17 answers)
Closed 7 years ago.
I have a URL string in JavaScript below ex-
URL-"/MyProject/Information/EmpDetails.aspx?userId=79874&countryId=875567"
Now, I need to do below 2 things
Check whether the country exists in above url or not and there will be only one countryId in above url
Get the countryId value means 875567.
Thanks Guys for such good response quickly .I got the solution most of the answers are correct.
One More Question Guys I have hyperlink so i am generating some activities when onmousedown event .but the issue is it fires even when i do right click only..but i want the event which fires only on clicking the hyperlink double click or right click and then click
Fetch URL using
window.location.href
And
Split with '?' first, '&' next and '=' so that you can get countryId
OR
directly split with '=' and get last value from array that we get after split
You need to use a combination of indexOf() and substring()
var ind = url.indexOf("countryId");
if (ind != -1){
// value is index of countryid plus length (10)
var countryId = url.substring(ind+10);
}else{
//no countryid
}
How about something like this:
var TheString = "/MyProject/Information/EmpDetails.aspx?userId=79874&countryId=875567";
var TheCountry = parseInt(TheString.split('=').pop(), 10);
And then you just need to test if TheCountry is something with if (TheCountry) { ...}
This of course assumes that the URL query string will always have the country ID at the end.
var url ='/MyProject/Information/EmpDetails.aspx?userId=79874& countryId=875567';
alert((url.match(/countryId/g) || []).length);
alert(url.substring(url.lastIndexOf('=')+1));
you can get the count of the occurrence of any string in first alert and get the countryid value by substring.
This will convert your url query into an object
var data = url.split('?')[url.split('?').length - 1].split('&').reduce(function(prev, curr){
var fieldName = curr.split('=')[0];
var value = curr.split('=').length > 1 ? curr.split('=')[1] : '';
prev[fieldName] = value;
return prev
}, {});
then you can just check the value of data.country to get the value
You may also split the string and see if the countryId exists, as below.
var myString = "/MyProject/Information/EmpDetails.aspx?userId=79874&countryId=875567";
myString = myString.split("countryId="); //["/MyProject/Information/EmpDetails.aspx?userId=79874&", "875567"]
if (myString.length === 2) {
alert (myString.pop());
}

Set two values for span jquery

I want to put two values or data into my span. I am putting value into span like this:
$('#spanid').text(data[i].phonenumber);
the code above will put the phone number to the span now I want to make it in a way that if the data has another number like mobile number i will add it to the text if available. I put it like this:
$('#spanid').text(data[i].phonenumber|| data[i].mobilenumber);
But only the first value is set even if there is a value for mobile number.
Any idea is appreciated
Do you want something like this
$('#spanid').text((data[i].phonenumber ? data[i].phonenumber +" , " :"") + " " +(data[i].mobilenumber? data[i].mobilenumber :"" ))
and you can also shorthand the second condition
$('#spanid').text((data[i].phonenumber ? data[i].phonenumber +" , " : "") + " " +(data[i].mobilenumber || "" ))
|| condition for both object will return only first object if it has value to it. If you wish to use it as separator, you need to concatenate it in both data and then set it to span:
$('#spanid').text(data[i].phonenumber +"||"+ data[i].mobilenumber);
The further answers are MAYBE working, but concatinating strings like that is very slow, better don't do so.
Concatinating a strings is fastest like this:
[string1, string2].join('')
You don't need any operator like || to add in text. Just add-
$('#spanid').text(data[i].phonenumber +""+ data[i].mobilenumber);
So, if any one is present, it will be available in text. Or if both are present it will be in appended form
Fiddle : http://jsfiddle.net/1oo4noed/
With your code the mobile number would only be displayed if there is no phone number. Try it with
$('#spanid').text((data[i].phonenumber || '') + (data[i].phonenumber && data[i].mobilenumber ? ", " : "") + (data[i].mobilenumber || ''));
You can do this by adding a the + operator in the text(); function to concatenate the strings:
$('#spanid').text(data[i].phonenumber + data[i].mobilenumber);
For putting both of the values within the text() function, with checking if they exist, i'd do something like this:
$('#spanid').text((data[i].phonenumber == "" ? "" : data[i].phonenumber) + (data[i].mobilenumber == "" ? "" : data[i].mobilenumber));
In your data object
var data={
phonenumber:222222222,
mobilenumber:''
};
If phonenumber or mobilenumber is missing it should have empty string, null or undefined to identify value exist or not.
Assuming if phonenumber or mobilenumber is missing it will have empty string
var data={
phonenumber:222222222,
mobilenumber:''
};
var text = '';
if(data.phonenumber !='' && data.mobilenumber !='' ){
text = data.phonenumber +','+ data.mobilenumber;
}
else if(data.phonenumber == ''){
text = data.mobilenumber;
}
else{
text = data.phonenumber;
}
$('#spanid').text(text);
Demo

variable string appearing as undefined, new string not appearing in array, javascript

I'm attempting to write some code that puts a single string of emails into an array of emails. Splitting the string wherever there's a comma(,). The initial problem i'm having is the string that is being passed as a variable is not being recognized. I'm getting the error message "Cannot read property 'length' of undefined" of the conditional part of the for loop. Odd, as I'm definitely passing a string or trying to ?
When I pass in a string directly to the function parameter(to avoid the above problem for testing the rest of the function) only the first 2 email addresses appear the final email address is lost ?
I'm learning programming and this is an exercise as such I'm trying to avoid using the split() method or regEx. Daft i know.
Any help in overcoming these 2 issues greatly appreciated.
function separateCommaValues(text)
{
var input = [];
var val = '';
for(var i = 0; i < text.length; i++) {
if(text[i] == ',') {
if(val.length == 0){
continue;
}
input.push(val);
val = '';
} else {
val += text[i];
}
}
document.write( input );
}
separateCommaValues(str);
var str = "john#google.com, jake#yahoo.com, andrew#hotmail.com";
var str = "john#google.com, jake#yahoo.com, andrew#hotmail.com";
separateCommaValues(str);
This is the correct order. Your variable can be declared before it is used via hoisting, but you can't define it before it is used (undefined error).
And the last email address isn't pushed into the array because it doesn't have a comma after it. So after the loop, before document.write( input );, add something like this:
if(val.length > 0){
input.push(val);
val = '';
}

Unable to compare two Strings in javascript

I am trying two compare two strings in JavaScript. But I guess there is some problem while comparing. It doesn't show the results.
if(ajaxRequest.readyState == 4){
var msg = ajaxRequest.responseText;
var fld = document.getElementById("prtCnt");
if(msg == "false") {
var msg = "This User Name is already taken !!!!";
fld.className = "bp_invalid";
// fld.style.color=green;
fld.innerHTML=msg;
}
Can any body tell me where the problem is? Thanks.
You might want to check if there's any space before or after the "false" string that you return from the server. You can do it easily with this:
alert('"' + msg + '"');
If there is extra space, you can just do:
msg = msg.trim();
and then do your if statement
Ensure that there is no white space around the word "false" with something like:
if( msg.match(/\s*false\s*/i) )

Categories