Reputation:
<script>
function test() {
var name=prompt ("Some question / text")
if (name.toLowerCase()=="TextToBlock") {
alert ("text");
name.preventDefault();
}
else {
}
}
</script>
<body>
< a id="link" onclick="test()" href="http://www.example.com">Text</a>
</body>
I'd like it to be so that if someone typed in "TextToBlock" in the prompt box it would prevent the user from going to the link location.
Thanks.
Upvotes: 1
Views: 182
Reputation: 10560
All you need in just one line:
<script>
function test() {
return "texttoblock" === prompt("Some question / text").toLowerCase() ? (window.event.preventDefault(), alert("text"), !1) : !0
};
</script>
<body>
<a id="link" onclick="test()" href="http://www.example.com">Text</a>
</body>
Demo: JSFiddle
.toLowerCase()
.
Upvotes: 0
Reputation: 7466
You just need to pick up the event
object from the click handler. (See fiddle http://jsfiddle.net/amyamy86/pJvZd/)
function test(event) {
event = event || window.event;
var name = prompt("Some question / text")
if (name.toLowerCase() === "texttoblock") {
alert("text");
event.preventDefault(); // block link from working
} else {
}
};
<body>
<a id="link" onclick="test()" href="http://www.example.com">Text</a>
</body>
Read more about Javascript event objects: http://javascript.info/tutorial/obtaining-event-object
Also, use ===
for strict comparisons. And also since you converted name .toLowerCase()
you should be comparing it to texttoblock
in lowercase.
Upvotes: 1