Set two values for span jquery - javascript

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

Related

can i make this into 1 switch case instead of many if else statements

const ticket = {
movie : document.getElementById("movie").value,
amount : document.getElementById("amount").value,
};
This is my object and I want to validate input. But I'm not sure how to change if-else statements to one switch case, since it has different statements.
PS: for learning purpose I need to use javaScript and not jQuery.
if(ticket.movie ===""){
document.getElementById("warningMovie").innerHTML = "need to choose a movie"
}else{
document.getElementById("warningMovie").innerHTML = "";
}
if(ticket.amount === ""){
document.getElementById("warningAmount").innerHTML = "need to choose amount"
}else{
document.getElementById("warningAmount").innerHTML = "";
}
Something like this?
I am using Object.entries and
a Conditional operator (ternary) twice :)
and add the key of the object to the ID of the span - I could use warningAmount but then I would have to capitalise the key
Note the object could have been created by looping over input elements
Also ignore ("aeiou".indexOf(item[0].toLowerCase())>=0?"n ":" ") if you do not like it
const ticket = {
movie: "",
amount: 0,
snack: "Chips",
};
for (let [key, value] of Object.entries(ticket)) {
document.getElementById("warning_" + key).innerHTML =
value ? "" :
"need to choose a"+ ("aeiou".indexOf(key[0].toLowerCase())>=0?"n ":" ") + key
}
<span id="warning_movie"></span><br/>
<span id="warning_amount"></span><br/>
<span id="warning_snack"></span><br/>
I would use ternary operator in this case. Eg.:
document.getElementById("warningMovie")
.innerHTML = ticket.movie ? "" : "need to choose a movie"

In javascript, spliting a string with order preserving

hosts=".uk.com:hostname:#10.10.10.10/10:#[2001:db8:1/64]:#11.11.11.11/11:#[::2/24]"
In javascript, how do i split the above string("hosts") string like the following :
newhosts=.uk.com,hostname,#10.10.10.10/10,#[2001:db8:1/64],#11.11.11.11/11,#[::2/24]"
tried this :
var hosts, newhosts;
var ip6_hosts = [];
var ip6_re = /#\[(.*?)\]/g;
hosts=".uk.com:hostname:#10.10.10.10/10:#[2001:db8:1/64]:#11.11.11.11/11:#[::2/24]";
while ((match=ip6_re.exec(hosts)) != null)
ip6_hosts.push(match[0]);
non_ip6_hosts=hosts.replace(ip6_re, '').replace(/:+/g, ':');
newhosts=ip6_hosts.concat(non_ip6_hosts.split(':'));
actual output :
newhosts=#[2001:db8:1/64],#[::2/24],.uk.com,hostname,#10.10.10.10/10,#11.11.11.11/11
expected output :
newhosts=.uk.com,hostname,#10.10.10.10/10,#[2001:db8:1/64],#11.11.11.11/11,#[::2/24]
but not sure how to preserve the order. is there any way to achieve an expected output ?
You could try:
var openbracket=0;
for (i=0; i<hosts.length; i++)
{
if (hosts.substr(i,1) == '[') openbracket=openbracket+1;
if (hosts.substr(i,1) == ']') openbracket=openbracket-1;
if ((hosts.substr(i,1) == ':') && openbracket==0)
{
hosts = hosts.substr(0,i) + ',' + hosts.substr(i+1,hosts.length-i-1);
}
}
seems to work for me, though I'm not sure if there's a better method for changing the value of hosts. All it needs to do is insert the ',' at the location i. The above code adds everything to the left of the ':', a ',', and everything to the right of the ':'.
note: this assumes you don't want any ':' inside of brackets changed to a comma.
hope this helps.
Can't You just say:
host = host.replace(/:+/, ',');
whenever you want to change it?
I feel like this is too simple of an answer, comment if I'm not getting it.
The following should work:
hosts.replace(/([^:]{1})\:{1}([^:]{1})/g, '$1,$2')
Try this.
var hosts='.uk.com:hostname:#10.10.10.10/10:#[2001:db8:1/64]:#11.11.11.11/11:#[::2/24]';
hosts = hosts.replace(/:#/g, ':##');
hosts = hosts.split(':#');
var hostDetails = hosts[0].split(':');
var newHost = hostDetails.concat(hosts.splice(1, hosts.length));
console.log(newHost);
Can you try this...
String.prototype.replaceAt=function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
}
hosts=".uk.com:hostname:#10.10.10.10/10:#[2001:db8:1/64]:#11.11.11.11/11:#[::2/24]"
hosts = hosts.split(':#').join(',#');
var re = /:\w/g;
var found = hosts.match(re);
hosts.replaceAt(found.index,',');

Printing PHP string using JQuery

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.

Join syntax in javascript

Please suggest me how to play with Join in javascript.
My Code
var multiTokenQuery = value.join(',');
submitted.set('multiTokenQuery', multiTokenQuery);
alert(multiTokenQuery);
the above code shows (abc,bcd) but I want it in ('abc','bcd') I mean I need single qoutes on the values ...
Please Help
Change the glue in the bits:
var multiTokenQuery = value != null && value.length > 0 ? "'" + value.join("','") + "'" : value;
You'd like to use the following instead to get your quotes.
var value = ['test','sample','example'];
var multiTokenQuery = "'" + value.join("','") + "'";
alert(multiTokenQuery);
JSFiddle: http://jsfiddle.net/FJUJ9/1/

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