I am trying to wrap my head around if statements. I am new to this.
I have a pretty simple script pulling data(text) from a html5 data attribute.
var $datatext = $(this).data('explain');
Now I want an if statement when html5 attribute data-explain is missing or empty.
var $success = if ($datatext < 0) {
// show some other text, maybe? =
$(this).text('Fail');
} else {
// show original, maybe? =
$(this).text($datatext);
}
Again, hard time wrapping my head around it. Ohhh these ifs.
That should work:
if (typeof $datatext !== 'undefined' && $datatext.length > 0) {
$(this).text($datatext);
} else {
$(this).text('Fail');
}
check for the length not for the data in $datatext rewrite your code like this
if ($datatext.length > 0) {
// show original, maybe? =
$(this).text($datatext);
} else {
// show some other text, maybe? =
$(this).text('Fail');
}
You can do it this way,
Live Demo
$('.someclass').each(function() {
if(typeof this.attributes['data-explain'] != 'undefined')
{
alert(this.id + ": explain exists");
explain = $.trim(this.getAttribute('data-explain'))
if(explain.length > 0)
alert(explain);
else
alert("no value for explain");
}
else
alert(this.id + ": explain does not exists");
});
Related
I have written this scrip to take out ads on a website. Was working on it the whole day.
This is the JS code:
var timer = setInterval(deletor, 1);
function deletor() {
timer;
var slider = document.querySelector("#slider-con");
var bannerTop = document.querySelector("#MainContent > div:nth-child(2)")
var bannerMiddle = document.querySelector("#MainContent > iframe");
var bannerRandom = document.querySelector("#MainContent > div:nth-child(7)");
var bannerRandom2 = document.querySelector("#MainContent > div:nth-child(6)");
if (slider == undefined) {
return false;
} else {
slider.parentNode.removeChild(slider);
};
if (bannerTop == undefined) {
return false;
} else {
bannerTop.parentNode.removeChild(bannerTop);
};
if (bannerMiddle == undefined) {
return false;
} else {
bannerMiddle.parentNode.removeChild(bannerMiddle);
};
if (bannerRandom == undefined) {
return false;
} else {
bannerRandom.parentNode.removeChild(bannerRandom);
};
if (bannerRandom2 == undefined) {
return false;
} else {
bannerRandom2.parentNode.removeChild(bannerRandom2);
};
};
Now, as you can see, it gets the values first and then goes through if statements. Idea behind this is: On first try, it deletes the elements and on the second one, it stops the function.
But when I inserted this last element, it won't delete it. The ID is correct, everything is correct but it won't delete the element, so I keep getting the same alert over and over.
Also, I found out that, I get this banner ad on two places. When I have "var bannerRandom = document.querySelector("#MainContent > div:nth-child(7)");" this, it appears as "document.querySelector("#MainContent > div:nth-child(6)")" this, and when I have both, it appears as "document.querySelector("#MainContent > div:nth-child(6)")" this. And it's not deleted.
Console shows no errors.
Your various statements in the form:
if (slider == undefined) {
return false;
} else {
slider.parentNode.removeChild(slider);
};
mean this: "If slider wasn't found in the DOM, exit the function. Otherwise, remove the slider and continue the function."
So that means your function will terminate the first time one of the elements you're looking for doesn't exist. Since it terminates then, none of the other elements after it is checked. That seems unlikely to be what you want to do.
You probably just wanted:
if (slider) {
slider.parentNode.removeChild(slider);
}
...and so on.
Note that you don't put ; at the end of a block attached to a flow-control statement like if or else, which is why I've removed it above. (Doing so is harmless, because JavaScript ignores them; but it's pointless.)
I am trying to cycle through a list of custom autocomplete options using the arrow keys in JavaScript. I am attempting to do this by iterating through the options and adding a "selected" ID to the option currently selected. I've run in to a problem where, although the "selected" ID of the option currently selected is visible (if you log it out, you can see the ID), the ID is inaccessible (trying to log out element.id returns an empty string).
Here is the code:
SearchBox.prototype.handleOptionNavigation = function() {
_this.inputElement.addEventListener("keyup", function(event) {
var options = _this.getOptions();
if (event.key === "ArrowUp") _this.moveSelectedUp();
if (event.key === "ArrowDown") _this.moveSelectedDown();
});
}
SearchBox.prototype.getOptions = function() {
return Array.from(document.getElementsByClassName("result-item"));
}
SearchBox.prototype.getSelectedIndex = function() { //here is the problem
var options = _this.getOptions();
if (options.length === 0) return;
console.log(options[2]);
//this returns <li class="result-item" id="selected">...</li>
console.log(options[2].id);
//this returns an empty string
return 1;
//this function is supposed to return the index of the element currently selected;
//I am returning 1 just to see a selected element on the screen.
}
SearchBox.prototype.moveSelectedDown = function() {
var options = _this.getOptions();
if (options.length === 0) return;
var selectedIndex = _this.getSelectedIndex();
if (selectedIndex === -1) {
options[0].id = "selected"
} else if (selectedIndex === (_this.maxResults - 1)) {
options[0].id = "selected"
options[options.length - 1].removeAttribute("id");
} else {
console.log("we are moving down");
options[selectedIndex + 1].id = "selected";
options[selectedIndex].removeAttribute("id");
}
}
SearchBox.prototype.moveSelectedUp = function() {
var options = _this.getOptions();
if (options.length === 0) return;
var selectedIndex = _this.getSelectedIndex();
console.log(selectedIndex);
if (selectedIndex === -1) {
options[options.length - 1].id = "selected";
} else if (selectedIndex === 0) {
options[0].removeAttribute("id");
} else {
options[selectedIndex - 1].id = "selected";
options[selectedIndex].removeAttribute("id");
}
}
The idea is that, with each press of the up or down arrows, a different element in the list of complete options will become highlighted. However, because I can't seem to access the id of the selected element, it gets stuck and the moveSelectedUp/moveSelectedDown functions don't work.
Does anyone know what is going on here?
Thank you!
Not quite sure what you are trying to achieve in your method SearchBox.prototype.getSelectedIndex, but it is always returning 1, how is that supposed to help ?
I've updated your method so that it returns the real index and it seems to work fine, see the fiddle below :
https://jsfiddle.net/c2p1aayh/
i used skype sdk Here and here is my code snippet after
config.conversation.historyService.activityItems.added(function(newMsg) {
if(typeof newMsg.direction != 'function') {} else {
if(newMsg.direction() == 'Incoming') {
direction = "black";
} else if(newMsg.direction() == 'Outgoing' && newMsg.status() === "Succeeded") {
direction = "green";
} else {}
$("#conversationText").append('<br/><div class="chat-user-info"><h1 class="chat-user-name">' + newMsg.sender.displayName() + '</h1><h2 class="chat-user-time">' + new Date() + '</h2></div><div class="chat-user-message"><h3 style="color:' + direction + ';">' + newMsg.text() + '</h3></div><br/>');
}
});
But, the message appears when it is on state pending or even if fails , after this i try to put the message inside but it appears only on the other side not mine.
Github related issue Here
Why did you add the typeof newMsg.direction != 'function' condition, does it correct something ?
The behaviour of your code seems correct here because the message appends only if the message is "Outgoing" and not "Succeeded".
Did you have any bugs or logs with the original solution wich is
conversation.historyService.activityItems.added(function(message) {
if (message.type() == 'TextMessage') {
if (message.direction() == 'Incoming' ) {
historyAppend(XMessage(message));
} else if (message.direction() == 'Outgoing' && message.status() === "Succeeded") {
historyAppend(XMessage(message));
}
}
});
I did solve this by workaround appending the message first regardless message.direction() value
I have a long if statement that I'm wanting to refactor. The statement listens for a click and then updates one of five text boxes depending on if those text boxes have anything in them or not. How could I change my code to be more efficient.
$('#img1').click(function() {
if ($('#card1').val().length === 0) {
$('#card1').val('A feeling of warmth');
} else if ($('#card2').val().length === 0) {
$('#card2').val('A feeling of warmth');
} else if ($('#card3').val().length === 0){
$('#card3').val('A feeling of warmth');
} else if ($('#card4').val().length === 0){
$('#card4').val('A feeling of warmth');
} else if ($('#card5').val().length === 0){
$('#card5').val('A feeling of warmth');
}
});
you could use a loop
$('#img1').click(function() {
var items = ["#card1", "#card2", "etc"];
for(var i=0;i<items.length;i++){
if ($(items[i]).val().length === 0) {
$(items[i]).val('A feeling of warmth');
}
}
});
it's at least easier to read. Also if your buttons are always card + a number you could make it even simplier (not easier to read, just less lines & maintenance)
$('#img1').click(function() {
for(var i=0;i<=5;i++){
if ($("#card" + i).val().length === 0) {
$("#card" + i).val('A feeling of warmth');
}
}
});
It seems like you're using JQuery. You can use a selector and a filter to isolate the first empty item:
$('#img1').click(function() {
$('input:text[id^=card]')
.filter(function() { return $(this).val() == ""; })
.first()
.val('A feeling of warmth');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="img1">CLICK ME</button><br>
<input id="card1"><br>
<input id="card2"><br>
<input id="card3"><br>
<input id="card4"><br>
<input id="card5">
$('input:text[id^=card]') selects all text inputs whose IDs begin with 'card'. But the same principle would apply to other element types.
$('#img1').click(function() {
// num can be total count of the element like $(.card).children.count
var num = 5, // preferably dont make it hardcoded.
str = 'A feeling of warmth',
preIdStr = '#card',
id;
for (var i = 1; i <= num; i += 1) {
id = preIdStr + i;
if ($(id).val().length === 0) {
$(id).val(str);
}
}
});
Give all cards the same class.
Then use the selector $('.yourclass')
Now use the jQuery for-each (.each) function to iterate all elements. Within the loop you check the value, set it to whatever you want and return false when the value was set, since this exit's the loop.
$('.yourclass').each(
function () {
if (this.val().length === 0) {
this.val('your value');
return false; // exit loop
}
});
I want to create a system that displays certain content based on the number for this innerhtml content...
Here's the actual element itself, 17 is just the number for mine it is different for each user:
<span id="your_div_id_diamonds"><dd><div class="field_uneditable">17</div></dd></span>
I want it to display if their number is say between 10 and 20... Here's a code I've been trying to work with, but it only does one number at a time and currently isn't working...
$(function() {
if(document.getElementById('your_div_id_diamonds').innerHTML = "17") {
document.getElementById('elitecontent').className="gotelite";
}
else {
document.getElementById('elitecontent').style.display="none";
}
}
});
Here's a version that works, but again only works for one number at a time... It'd be a huge pain if I had it go up to say 150 or 200, I'd have to make like 200 else if statements.
$( "#lev1" ).load('/u' + _userdata.user_id + ' #field_id-14 dd', function() {
var divs= document.getElementsByClassName('field_uneditable');
for (var i = 0, len = divs.length; i < len; ++i) {
if(divs[i].innerHTML.indexOf("7") != 1) {
document.getElementById('elitecontent').innerHTML="Elite";
}
else if(divs[i].innerHTML.indexOf("16") != -1) {
document.getElementById('elitecontent').innerHTML="Elite";
}
else if(divs[i].innerHTML.indexOf("17") != -1) {
document.getElementById('elitecontent').innerHTML="Elite";
}
else {
document.getElementById('elitecontent').innerHTML="Starter";
}
}
});
I basically want a code that works similar to with values, where I can just put something like >=10 and =<20
The problem you are facing with your current code is that you aren't using the correct comparison statements = is declarative, not used for comparison. In its place you should be using ==(matches regardless of data type) or === (must match data type as well) for instance
$(function() {
if(document.getElementById('your_div_id_diamonds').innerHTML = "17") {
document.getElementById('elitecontent').className="gotelite";
}else {
document.getElementById('elitecontent').style.display="none";
}
}
});
should be
$(function() {
if(document.getElementById('your_div_id_diamonds').innerHTML == "17") {
document.getElementById('elitecontent').className="gotelite";
}else {
document.getElementById('elitecontent').style.display="none";
}
}
});
However, for your needs something along the lines of:
$(function() {
if(document.getElementById('your_div_id_diamonds').innerHTML <=20 && document.getElementById('your_div_id_diamonds').innerHTML >=10) {
document.getElementById('elitecontent').className="gotelite";
}else {
document.getElementById('elitecontent').style.display="none";
}
}
});
should work.