I have a problem with following code:
var status = null;
var action = 1;
function test() {
if(status != null || action == 3) {
alert('Why am i her?');
}else {
alert('I should be here');
}
}
test();
I get expected results in Firefox and IE alert('I should be here'). But in Chrome i get alert('Why am i here?').
I'm not able to reproduce this for you, but I might just have the answer:
if(status !== null || action === 3) {
Compare the variable not just by value but also by type, by using an extra =
status and action var names seem too good to not be system reserved. maybe your chrome has something running with a status var allocated. try changing them to something else and see if it makes a difference.
var myStatus = null;
var myAction = 1;
function test() {
if(myStatus != null || myAction == 3) {
alert('Why am i her?');
}else {
alert('I should be here');
}
}
test();
Related
I am trying to call startsWith() string function on a JSON property value:
{"message":"xyzabc"}
var jsonResponse = JSON.parse(httpResponse.text);
var stringMessage = jsonResponse.message.toString();
if(stringMessage.startsWith('xyz')) {
...
}
but I get the error:
Object xyzabc has no method 'startsWith'
How can I do that?
The code is running on server side, Express on Node.js
It may be happen that your browser does not support the startsWith() function so you can use use the RegExp to overcame this problem like this...
var jsonObject={message:"xyzHELLO"};
var regex=new RegExp("^xyz");
if(regex.test(jsonObject["message"])){
alert("hello");
}
Live Demo HERE
[EDIT]
If you want to add the function startsWith() in your each and every string than you can add like this
if (String.prototype.startsWith !== "function") {
String.prototype.startsWith = function (searching) {
var regex = new RegExp("^" + searching);
if (regex.test(this.toString())) {
return true;
}
else {
return false;
}
}
}
and after that you can use like this:
var jsonObject = { message: "xyzHELLO" };
if (jsonObject["message"].toString().startsWith("xyz")) {
alert("start with");
}
else {
alert("not start with");
}
[EDIT]
if (String.prototype.startsWith !== "function") {
String.prototype.startsWith = function (searching) {
if (this.toString().indexOf(searching) == 0) {
return true;
}
else {
return false;
}
}
}
As per the comment by #nnnnnn and I also think it is good practice if we use the native function of the JavaScript, Thanks #nnnnnn.
Please double check your input JSON. Your code works like a charm with a correct JSON input in httpResponse.text.
var json = '{"message": "xyztest"}';
var jsonResponse = JSON.parse(json);
var stringMessage = jsonResponse.message.toString();
if(stringMessage.startsWith('xyz')) {
alert('It works!');
}
Also please make sure the browser you are working in supports startsWith method. Here you can find a list with all supported browsers.
If you need to work around the browser compatibility issues, you can use the widely supported indexOf method.
if(stringMessage.indexOf('xyz') === 0) {
alert('It works!');
}
HERE is a Fiddle for both cases.
Apparently, Js has startsWith function for the strings. However, using your own function to see if the string starts with the value should cause no error.
function StartsWith(s1, s2) {
return (s1.length >= s2.length && s1.substr(0, s2.length) == s2);
}
var jsonResponse = JSON.parse(httpResponse.text);
var stringMessage = jsonResponse.message.toString();
if(StartsWith(stringMessage,'xyz')) {
//Doing Stuff!
}
I'm running this code:
jQuery.get("http://email.hackmailer.com/checkuser.php?email=".concat(document.getElementById('name').value).concat(document.getElementById('domain').value), function(data) {
if(data == "true") {
document.getElementById('containerThree').style = "background-color:#20bb47;";
}else{
document.getElementById('containerThree').style = "background-color:#b33535;";
}
document.getElementById('avail').style = "color:#272727;";
document.getElementById('emt').style = "color:#272727;";
});
It works fine in FireFox, but in chrome not at all. I've tried using .style.background = "#mycolorcode" but it still doesn't work in chrome(and in that case, firefox too).
Try this:
if (data === 'true') {
document.getElementById('containerThree').style.backgroundColor = '#20bb47';
} else {
document.getElementById('containerThree').style.backgroundColor = '#b33535';
}
http://devdocs.io/html/element/style
http://youmightnotneedjquery.com/
NOTE: 'true' is a string. You would most likely would rather use the Boolean true.
Based on the latest edit to your question, does this cleanup of your surrounding code help?
jQuery.get('http://email.hackmailer.com/checkuser.php?email='
.concat(document.getElementById('name').value)
.concat(document.getElementById('domain').value),
function (data) {
if (data === true) {
document.getElementById('containerThree').style.backgroundColor = '#20bb47';
} else {
document.getElementById('containerThree').style.backgroundColor = '#b33535';
}
document.getElementById('avail').style.color = '#272727';
document.getElementById('emt').style.color = '#272727';
});
You don't need to send a string as 'true' to check a condition. Use it like:
var data = true; //use boolean but not 'true' as string.
Then you can simple use it as follows:
jQuery.get("http://email.hackmailer.com/checkuser.php?email=" + document.getElementById('name').value + document.getElementById('domain').value, function(data) {
var colorValue = "#272727";
document.getElementById('containerThree').style.backgroundColor = data == "true"?"#20bb47":"#b33535";
document.getElementById('avail').style.color = colorValue;
document.getElementById('emt').style.color = colorValue;
});
BTW, I am not sure how .style = "background-color:#20bb47;"; is working for you.
$(function(){
var a=document.getElementById('text_editor_textarea'),regEx=/^\s*$/,
updateOrig = function() {
var sc = $(a).data('sceditor');
if(sc){
sc.bind('keypress', sc.updateOriginal);
sc.blur(sc.updateOriginal);
}else {
setTimeout(updateOrig , 200);
}
};
updateOrig();
if(a.value !== "" && regEx.test(a.value) ){
window.onbeforeunload = function(){
return "You have a post waiting to be submitted";
};
}
});
This code should check if there is data in a and if there is onbeforeunload the alert should be prompted. It works except that even if there is no data in the textarea it still is prompted. Am I doing something wrong here?
Just do a.value !== "" instead of a.value !== null || a.value !== "" inside of this if block:
if (a.value !== null || a.value !== "") {
window.onbeforeunload = function () {
return "You have a post waiting to be submitted";
};
}
Also, flip the if and the event function assignment to this:
window.onbeforeunload = function () {
if (a.value !== "") {
return "You have a post waiting to be submitted";
}
};
I didn't realize this before, but only on page load would your message get called since otherwise the assignment wouldn't occur since the textarea would be empty when you first opened the page.
jsFiddle
var act = false;
var newprod = prompt("tell me somthing", "");
if (newprod != '' && newprod != null) {
$.ajax({
//posting code here
});
}
if (act != false) { document.location.href = window.location; }
The page is refresh in every condition even act false or not.
It is fired on an event.
Can anyone tell me why it page is refreshed in all condition?
var act = false;
var newprod = prompt("tell me somthing", "");
if (newprod) { // not null, undefined or 0
$.ajax({
//posting code here
});
}
if (act) { window.location.reload(1); }
assuming that is what the code was supposed to do. document.location is deprecated and in theory read-only.
This should work
if( newprod != null && newproda.length != 0) {
//Execute the code
}
To the reason why it was always working was that newprod was not the same as ''.
As the question is what is wrong with that JavaScript code i will advise.
if(act) {
document.location.href = window.location;
}
You may want to learn more about false-y values in JavaScript. My guess is that your if statement is giving you some problems because it does not compare the way you think it should compare.
OMG, I am in need of a way to set up arrays of XML Requests based on the idShout - 1.
So it would be something like this...
var req = new Array();
req[idShout - 1] = ALL XML Data...
Here's what I got so far but it's not working at all :(
var idShout;
var req = new Array();
function htmlRequest(url, params, method)
{
req[req.push] = ajax_function();
for (i=0;i<req.length;i++)
{
(function (i) {
if (req[i])
{
if (method == "GET")
{
req[i].onreadystatechange = function()
{
if (req[i].readyState != 4)
return;
if (req[i].responseText !== null && req[i].status == 200)
{
document.getElementById("shoutbox_area" + idShout).innerHTML = req[i].responseText;
}
}
}
req[i].open(method,url,true);
if (method == "POST")
req[i].setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
if (params == "")
req[i].send(null);
else
req[i].send(params);
return req[i];
}
else
return null;
})(i);
}
}
function ajax_function()
{
var ajax_request = null;
try
{
// Opera 8.0+, Firefox, Safari
ajax_request = new XMLHttpRequest();
}
catch (e)
{
// IE Browsers
try
{
ajax_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
ajax_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
//No browser support, rare case
return null;
}
}
}
return ajax_request;
}
function send(which)
{
var send_data = "shoutmessage=" + document.getElementById("shout_message" + which).value;
var url = smf_prepareScriptUrl(smf_scripturl) + "action=dreamaction;sa=shoutbox;xml;send_shout="+ which;
htmlRequest(url, send_data, "POST");
document.getElementById("shout_message" + which).value = "";
document.getElementById("shout_message" + which).focus();
return true;
}
function startShouts(refreshRate, shoutCount)
{
clearInterval(Timer[shoutCount-1]);
idShout = shoutCount;
show_shouts();
Timer[shoutCount - 1] = setInterval("show_shouts()", refreshRate);
return;
}
function show_shouts()
{
var url = smf_prepareScriptUrl(smf_scripturl) + "action=dreamaction;sa=shoutbox;xml;get_shouts=" + idShout;
htmlRequest(url, "", "GET");
}
Any help at all on this would be greatly appreciated...
Basically, I'm setting the Timer Arrays in a different function before this, and I call startShouts which is supposed to show all of the information, but startShouts gets called more than once, which is why I have idShout set to equal shoutCount. So it will go something like this: shoutCount = 1, shoutCount = 2, shoutCount = 3, everytime it is being called. So I set the req[idShout - 1] array and it should return the result right??
Well, I get no errors in Firefox in the error console with this code above, but it doesn't work... Any ideas anyone?? As it needs to output into more than 1 area... argg.
Thanks for any help you can offer here :)
Thanks guys :)
Also, a little more info on this...
Basically there is 1 or more Shoutboxes on any given page (Don't ask why?), I need to be able to grab the info of this and put it into the document.getElementById("shoutbox_area" + idShout), since the idShout for each element changes incrementing by 1 for each Shoutbox that is on that page. The values for the Shoutbox can be different, example the refreshRate can be different. 1 Shoutbox can have a refresh rate of like 2000 milliseconds, while the other can have a rate of 250 milliseconds, they need to be different and refresh at the times that are defined for them, so this is why I decided to make a Timer array, though not sure I have setup the Timer array the way it is meant to be setup for the setInterval function. Here is the way it get's done in a different javascript function that runs just before startShouts gets called...
This part is outside of the function and within the document itself:
var Timer = new Array();
And this part is in the function...
Timer[shoutCount - 1] = "";
So not sure if this is correctly setup for Timers...?
Since XHRs are asynchronous, by the time the readystatechange callback function fires the value of i has changed. You need to create a separate closure for the i variable during your loop. The easiest way to do this is wrap an anonymous function around the code block and call it with i passed as the first argument:
for (i=0;i<req.length;i++)
{
(function (i) {
if (req[i])
{
if (HttpMethod == "GET")
{
req[i].onreadystatechange = function()
{
if (req[i].readyState != 4)
return;
if (req[i].responseText !== null && req[i].status == 200)
{
document.getElementById("shoutbox_area" + idShout).innerHTML = req[i].responseText;
}
}
}
req[i].open(HttpMethod,url,true);
if (HttpMethod == "POST")
req[i].setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
if (params == "")
req[i].send(null);
else
req[i].send(params);
return req[i];
}
else
return null;
})(i);
}