Trying to conditionally disable link depending on link text via javascript/jquery - javascript

I have a link whose text content is determined by some backend software. Depending on what the text content is, that link should be clickable or not clickable. I am trying to make the link not clickable if the link text is "No New Messages". I am trying to use the following code:
if ($('a#full_notifications_link').text() == "No New Messages"){
$('a#full_notifications_link').click(function(){
return false;
});
}
This is not working. The link works just like normal. How do I get the link to not work if the link text is "No New Messages"?
To be clear, I CANNOT change any of the html because it will be different every time depending on the backend. Also, I've determined the problem is with line 1, because if i place an alert right after it the alert does not appear.
Also, here is the html when the text says "No New Messages":
<a data-remote="true" href="/usernotificationslist" id="full_notifications_link">
No New Messages
</a>

Please see this Fiddle: http://jsfiddle.net/jFIT/J8eEL/
$('a#full_notifications_link').click(function(event){
if ($.trim($('a#full_notifications_link').text()) == "No New Messages"){
event.preventDefault();
return false;
}
});
returning return false from a function doesnt usually do it.. event.preventDefault();

HTML
text
JAVASCRIPT
function myfunction(){
var text_of_link = $('a #full_notifications_link').text();
if(text_of_link == "No New Messages"){
//do nothing
}else{
window.location.replace($('#full_notifications_link').attr("href"));
}
}

Make sure you have no spaces to meet the condition right..
To be sure, dont line break them
<a data-remote="true" href="/usernotificationslist" id="full_notifications_link">No New Messages</a>
also, have you already placed these inside?
$(document).ready(function(){
//enter code here
});

You can use preventDefault to do this, by catching the click event
BTW this is not working to me i don't know why the onclick does not find the function to be binded hehe
Even though this the best approach I think http://jsfiddle.net/A2wns/1/
// HTML
No New Messages
// js
function checkMessage(evt){
if ( $(evt.target).text() === "No New Messages"){
evt.preventDefault();
}
}

Related

JavaScript - Calling the click function more than once would not work

I am making a text adventure game, which would require user input in the form of a element in html, which would send the user input to JavaScript using the click function:
<!-- HTML CODE -->
<div class="game">
<div id="gamebox">
<a name="game"></a>
<!-- Javascript writes to here (if it works :( ) -->
</div>
<div id="inputbox">
<input type="text" id="userinput" placeholder="Input" value="" />
Go!
</div>
</div>
As you can see above, I have a element and a "Go!" button, which sends it to my JavaScript code. In JavaScript, first I define 3 variables where I would output my text.
//JavaScript Code
var txt_input = $("#userinput");
var btn_quest = $("#btn-quest");
I would than define 2 other functions, which allows me to write into the . I would than have other functions, which are for the storyline of the text adventure game. However, the root of the problem is that I can't seem to progress past the second event. Here are my events:
function wakeUp() {
displayGame("You wake up, at stackoverflow. West or east? [Choose 'west' or 'east']");
btn_quest.on({
"click": function() {
// Begin input preproccessing
var input = txt_input.val().toLowerCase();
// If/else block for choice here
if (input === "west") {
//Paste btn_quest here for new event
goWest();
} else if (input === "east") {
//Paste btn_quest here for new event
goEast();
} else {
//Error handler - do not modify
txt_input.val("Error - enter a valid choice");
}
//End of if else block body
}
});
The first event function would work perfectly, and write to my html, and accept the first user choice. However, at the next event, no matter what it is, (goEast() or goWest()), my program aways displays "Error - enter a valid choice"). Right now, my hypothesis is that the "switch" function isn't working correctly. However, I honestly don't know. What is the issue here, and how can I fix it? The other event functions (etc goEast) are exactly the same as the wakeUp function, except with different displayGame() strings and link to other event functions.
I have not included the full code, in order to keep my code short - but here is the full html/css/javascript if needed: http://plnkr.co/edit/55heHh4k5QEIVYdBrWGB?p=preview
Edit: I tried to implement the suggestion, like this: But It seems that JavaScript doesn't even get the userinput anymore. When I try to submit the user's response, nothing happens. What went wrong? I did the same thing here with all of my functions in the game:
function wakeUp() {
displayGame("You wake up at stackoverflow again, but it didn't work. Go West or east again?");
// btn_quest.off("click").on("click",function()){
btn_quest.off("click").on;
"click", function() {
// Begin input preproccessing
var input = txt_input.val().toLowerCase();
// If/else block for choice here
if (input === "walk") {
//Paste btn_quest here for new event
walkToWork();
} else if (input === "bus") {
//Paste btn_quest here for new event
busToWork();
} else {
//Error handler - do not modify
txt_input.val("Error - enter a valid choice");
}
//End of if else block body
};
//End of function. Copy until line under this comment V
}
What did I do wrong? Can you please show a example using this function?
You need to look at all the code to see the problem. The reason is because you keep binding to the element so multiple click events are being triggered. You need to remove the last click
btn_quest.off("click").on("click",function(){});

Check for empty href atribute in JQuery

I have an idea I'd like to implement to a site I'm working on. I've got an idea of how it would work but I'm not entirely sure how to piece the bits together.
So!! I'd like to check the domain and generate an alert box if it's necessary to do so.
Say we have 2 domains:
test.domain.com & domain.com
IF we're on test.domain.com and there's no content inside the href (Missing Link), I'd like an alert box to pop up saying "MISSING LINK". And if there is content inside the href, just ignore it (Not Missing Link).
Missing Link
Not Missing Link
Then, if we were on domain.com I'd like the jQuery to still be present in the code, but it to do nothing if a Missing Link was clicked. As it will just redirect to the home page - Not the best journey, but much better than an intrusive popup box.
This way I could use a tiny bit of code to check missing links at the test stage, but not have to remove it every time it gets sent to the actual domain.
If any of this doesn't make sense, please ask!
Thanks a million, really appreciate the help!
$(document).on("click", 'a[href=""]', function(evt) {
if(window.location.hostname.indexOf("test")!==-1) {
alert("broken");
} else {
window.location.href = "foo.html";
}
evt.preventDefault();
});
Personally if I were making a page on test to determine if a link is broken, I would do something so they would stand out when the page is open. Instead of clicking to find out.
if(window.location.hostname.indexOf("test")!==-1) {
$('a[href=""]').css("background-color", "red");
}
Here is some code to get you started. It feels to me as though whatever it is you’re trying, we’re taking completely the wrong approach.
if (location.host === 'test.domain.com' && !$('a[href=""]').length) {
alert('MISSING LINK');
}
Hows this?
$(document).ready(function() {
$('a').click(function(e) {
var a = $(this);
e.preventDefault();
if($.trim(a.prop('href')) == "")
{
alert("No link")
}
else
{
window.location = $.trim(a.prop('href'));
}
});
});

jQuery show function flashing briefly

I am very new to web development and jQuery. I'm trying to add my first jQuery method to my code in Ruby on Rails. I have a css class
.list-group-item{
display: none;
}
and a JS function
$(document).ready(function(){
$(".list-group").click(function(){
$(".list-group-item").show();
});
});
I tested it with an alert, the alert appeared. When I try to run this, the list group briefly flashed then goes away immediately. I am sure it is a simple mistake. I have tried adding return false before the document function, no change. Thanks for acknowledging my noob question :)
Is .list-group-item a link? If so, it sounds like the page is reloading as you don't have return false. Need something like:
$(document).ready(function(){
$(".list-group").click(function(){
$(".list-group-item").show();
return false;
});
});
What this does is stop the link from doing anything else after it shows the links with list-group-item class.
You need to put the return false; after the show() function...assuming the list item is a link. return false; prevents the default behaviour of the selector. So if it's a link, it'll prevent the link from functioning - or being fired.
$(document).ready(function(){
$(".list-group").click(function(){
$(".list-group-item").show();
return false; // add this here
});
});

casperjs: how do I click a remote div and then update it's class name?

As a way of learning CasperJS, I am trying to initiate a click event on a div on a remote page, and then change the class name of the div after I have clicked it. The idea is to find the first clickable div, click it, and then mark it as clicked so I can skip over it to other clickable divs. The markup for the div tag on the remote page looks like:
<div class='clickable_div'></div>
I have tried the following casperjs code:
...
casper.then(function() {
if( this.exists( 'div.clickable_div' ) ) {
this.evaluate(function() {
this.click(document.querySelector('div.clickable_div'));
return document.querySelector('div.clickable_div').setAttribute("className","clicked");
});
}
});
...
It doesn't seem to work. First, I don't think I am initiating the mouse click event on the div correctly. What am I missing? Second, when I fetch the updated html, I don't see any changes in the div's class name. Am I going about this step in the wrong way?
You're calling this.click within evaluate(), it just can't work as evaluate() executes code within the page DOM context where there's probably no window.click method.
Here's a possibly working script:
var linkSelector = 'div.clickable_div';
casper.then(function() {
if (!this.exists(linkSelector)) return;
this.click(linkSelector);
this.evaluate(function(linkSelector) {
__utils__.findOne(linkSelector).setAttribute("className", "clicked");
}, linkSelector);
});
You may want to have better handling of errors and edge cases, but you get the idea.

jQuery AJAX is not showing output after first PHP conditional

I am having trouble using the jQuery AJAX call. The query runs properly and debug output also shows the correct data, but anything apart from the first PHP conditional in the document being called is not being shown.
First, there are two buttons, one linked to "core" the other "email":
Here's the relevant JavaScript:
$("#core").click(function(){
loaddetails ("core");
});
$("#email").click(function(){
loaddetails ("email");
});
function loaddetails(type) { var query = "details=" + type;
$.post("details.php", query , function( data ) {
$("#d-features").html(data); alert (data);});
return false;
};
And the contents of details.php:
<? if($_POST['details']=='core'){ ?> blah1 <? }
if($_POST['details']=='email') { ?> blah2 <? } ?>
Both "blah1" and "blah2" appear in the alert box debug output. But, only "blah1" ever gets posted on the page div (#d-features), as "blah2" never appears on the page.
I have checked Firebug and there are absolutely no errors. But I suspect the second conditional request may have gone in a loop, as the alert window showing up when "email" button is clicked shows "Prevent page from creating additional dialogs", though no additional dialogs show up even when unchecked.
What is causing this problem and how to fix it?
.html() replaces the content instead of appending.
Try changing that line to see if all the data is returned from both calls:
$("#d-features").html(data); ==> $("#d-features").append(data);
A small modification on your code, you could try to see if this works:
function loaddetails(type) {
$.post(
"details.php",
{
details: type
},
function( data ) {
$("#d-features").html(data);
alert (data);
}
);
return false;
}
Ok, it seems to be a conflict with the tabs effect I loaded for a div that encompassed these links. So once I removed that effect, it works now. But I'm not sure what is wrong with the effect yet, I'll post another question to figure it out.
Thanks to those that offered assistance!

Categories

Resources