Error handling in a Javascript search function - javascript

this is actually a follow up question to this question
that was solved thanks to Rory McCrossan.
I now have this functioning script; a search function that shows a div depending on a searchword.
JS
$('#search').click(function() {
var txt = $('#search-criteria').val();
if (txt)
$('.fruit').hide().filter('#' + txt.toLowerCase()).show();
});
CSS
.fruit {
display: none;
}
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script
<input type="text" id="search-criteria" />
<input type="button" id="search" value="search" />
<div class="fruit" id="apple">
<h3>Some text about apples</h3>
</div>
<div class="fruit" id="orange">
<h3>Some text about oranges</h3>
</div>
What I now wonder is if someone could help me with some kind of error handling to add to this script, preferably that can be smoothly added without rewriting the logic of the script. I.e. I'd like to display another div with a message when the search comes up with no result and/or when the user makes an empty string search.
Since I'm actually an UX designer my technical skills are somewhat limited and I'm therefore very grateful if someone could help me with this...
Thanks in advance!

simple javascipt error handing using try and catch:--
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
function adddlert2($a){
alert($a);
}
try {
adddlert("Welcome guest!");
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
</script>
</body>
</html>

You can use try and catch in this case, but If you want to be informed about all irregularities in your application I prefer to use dedicated services for this job.
I use Sentry.io, this is nice service to handle exceptions and errors in backend and frontend. Is simple to use, you only need to add one additional JS script without modifying existing code. More about installation process here

I guess what you're looking for is this :) I know changing to .keyup() had nothing to do with your question, so change it back if you like
<input type="text" id="search-criteria" />
<input type="button" id="search" value="search" />
<div id="default" class="fruit">
no fruit found
</div>
<div class="fruit" id="apple">
<h3>Some text about apples</h3>
</div>
<div class="fruit" id="orange">
<h3>Some text about oranges</h3>
</div>
and
<script>
$(document).ready(function(){
$('#search-criteria').keyup(function() {
var txt = $('#search-criteria').val();
if (txt){
var elements = $('.fruit').hide().filter('#' + txt.toLowerCase());
if(elements.length > 0){
elements.show();
}
else{
$("#default").html("No result found for "+txt);
$("#default").show();
setTimeout(function(){
$("#default").hide();
}, 1000);
}
}
});
});
</script>

Another error handing(javascript example) using javascript SEARCH function:--
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
try {
var str_wrong = "Visit";
var n = str.search("Visit");
document.getElementById("demo").innerHTML = n;
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
</script>
</body>
</html>

Related

Is there a way to stop html from making line breaks when a tag is in another tag?

So I would like to make a calculator with some formatting to make it look nice. It keeps making a new line for my p tag and I don't want it to, is there any fix for this?
var n1 = document.getElementById("n1");
var n2 = document.getElementById("n2");
var display = document.getElementById("disp");
function addAndDisplay() {
display.innerHTML = (Number(n1.value)+Number(n2.value)).toString();
}
<!DOCTYPE html>
<html>
<head>
<title>Addition</title>
</head>
<body>
<h1>Addition</h1>
<h3>Value one:</h3>
<input type="number" id="n1">
<h3>Value two:</h3>
<input type="number" id="n2">
<br>
<button onclick="addAndDisplay()">Add</button>
<h3>The output: <p id="disp">You have not calculated anything yet</p>.</h3>
</body>
</html>
EDIT: Thanks #Pipe and #Pointy I appreciate your help a lot!
Per default, a paragraph is a block level element. This means that it starts on a new line and takes up the full width. Maybe you should consider using something else.
For this kind of usecase, you would want to use <span></span>. Span is using display: inline which allows multiple inline-elements to appear next to each other.
It might be useful to read this article about the CSS display property - it will help you understand the suggested solution much better.
you shuld use span instead of p. p is paragraph element and span can be used to group elements for styling purposes
var n1 = document.getElementById("n1");
var n2 = document.getElementById("n2");
var display = document.getElementById("disp");
function addAndDisplay() {
display.innerHTML = (Number(n1.value)+Number(n2.value)).toString();
}
p{
display:inline-block;}
<!DOCTYPE html>
<html>
<head>
<title>Addition</title>
</head>
<body>
<h1>Addition</h1>
<h3>Value one:</h3>
<input type="number" id="n1">
<h3>Value two:</h3>
<input type="number" id="n2">
<br>
<button onclick="addAndDisplay()">Add</button>
<h3>The output: <p id="disp">You have not calculated anything yet</p>.</h3>
</body>
</html>

Uncaught TypeError: Cannot Read Property 'checked' of null - html checkbox toggle

I am getting an error when attempting to run a function once a checkbox is being checked. The above error appears consistently each time I am attempting to run it. Heres the code:
HTML:
<body>
<header>
<div class="header_container">
<h1>Trivia Quiz</h1>
<p>Welcome to the Trivia Quiz 2020!</p>
<p>The aim of the game is to get as many questions correct as possible!<br> The topics range from film to geography, so good luck!</p>
<div class="header_settings" id="header_settings">
<input type="checkbox" id="checkbox" onclick="TimeToggle()">
<label for="TimeToggle">Time Limit</label><br>
<input type="text" id="Timer" name="Timer" placeholder="Seconds" id="header_input">
</div>
<button>Start</button>
</div>
</header>
</body>
And Javascript (stored externally, linked in the head of the HTML document.):
var header_input = document.getElementById("header_input");
var header_settings = document.getElementById("header_settings");
var checkbox = document.getElementById("checkbox");
function TimeToggle() {
if (checkbox.checked) {
header_settings.style.height = "3%";
setTimeout(function () {
header_input.style.display = "none";
}, 500);
} else {
header_settings.style.height = "10%";
setTimeout(function () {
header_input.style.display = "block";
}, 500);
}
}
The code is intended to toggle the height of the div named "header_settings", and the display setting of the input named "header_input" depending on whether the checkbox is checked.
I would appreciate any pointers regarding how this is not working, I have tried a lot. Thanks :)
Is this what you are trying to do ? You can use an onchange function and pass this as an argument and check if in your toggle function if input is checked or unchecked.
Also, you have had two id selectors on your input which is not possible.
In addition, please ensure that your scripts.js is loading just added before the </body> end tag
Add this code as your HTML input
<input type="checkbox" id="checkbox" onchange="TimeToggle(this)">
Live Working Demo:
function TimeToggle(el) {
var header_input = document.getElementById("header_input");
var header_settings = document.getElementById("header_settings");
var checkbox = document.getElementById("checkbox");
if (el.checked) {
header_settings.style.height = '50px';
setTimeout(function() {
header_input.style.display = "none";
}, 500);
} else {
header_settings.style.height = '100px';
setTimeout(function() {
header_input.style.display = "block";
}, 500);
}
}
<body>
<header>
<div class="header_container">
<h1>Trivia Quiz</h1>
<p>Welcome to the Trivia Quiz 2020!</p>
<p>The aim of the game is to get as many questions correct as possible!<br> The topics range from film to geography, so good luck!</p>
<div class="header_settings" id="header_settings">
<input type="checkbox" id="checkbox" onchange="TimeToggle(this)">
<label for="TimeToggle">Time Limit</label><br>
<input type="text" name="Timer" placeholder="Seconds" id="header_input">
</div>
<button>Start</button>
</div>
</header>
</body>
Your problem is a very common one. You are trying to get the html elements using document.get... before the DOM has loaded. You need to wrap those document fetches in the onload listener for the window:
let checkbox;
window.onload = function() {
checkbox = document.getElementById();
};
function TimeToggle() {//...}
Place the external JS to at the end. Just before</body>. And your problem will be solved.
Somewhat like
<body>
<!--Your HTML content here-->
<script src = "External Js.js"></script>
</body>

content replace js script fails

The code below does not appear to function properly. newH2Text should replace para1. This does not happen. I used Sublime, then looked through the browser console, and even on SO's code snippet. I am almost certain I have the code verbatim.
The first paragraph, which has its own id attribute should be replaced by newH2Text which is created in my JS script. I can't find my mistake here. Please help.
PS the refresh button works properly. No issue there.
function replaceHeading(){
var newH2=document.createElement("h2");
var newH2Text=document.createTextNode("Welcome");
newH2.appendChild(newH2Text);
var myDiv=document.getElementById("id1");
var oldP=document.getElementById("para1");
myDiv.replaceChild(NewH2,oldP);
}
window.onload=function() {
document.getElementById("btn").onclick=replaceHeading;
}
<div id="id1">
<p id="para1">Welcome to my web page.</p>
<p id="para2">Take a look around.</p>
<input type="button" id="btn" value="Replace Element">
<br>
<input type="button" value="refresh" onclick="location.reload()">
</div>
NewH2 is capitalized but should be newH2 with a lowercase.
myDiv.replaceChild(newH2,oldP);
See this fiddle for an example
Update
To catch these errors earlier you can use "strict mode". An example of this would be:
;(function(){
"use strict";
function replaceHeading(){
var newH2=document.createElement("h2");
var newH2Text=document.createTextNode("Welcome");
newH2.appendChild(newH2Text);
var myDiv=document.getElementById("id1");
var oldP=document.getElementById("para1");
myDiv.replaceChild(NewH2,oldP);
}
}());
Which would give you the error Uncaught ReferenceError: NewH2 is not defined.
There are at least two different ways todo what you are trying:
function replaceHeading(){
/***** CORRECTED AND WORKING
var newH2=document.createElement("h2");
var newH2Text=document.createTextNode("Welcome");
newH2.appendChild(newH2Text);
var oldP=document.getElementById("para1");
document.getElementById("id1").replaceChild(newH2,oldP);
*////
// OR a more simpler way
document.getElementById("para1").innerHTML = "<h2>Welcome</h2>";
}
window.onload=function() {
document.getElementById("btn").onclick=replaceHeading;
}
<div id="id1">
<p id="para1">Welcome to my web page.</p>
<p id="para2">Take a look around.</p>
<input type="button" id="btn" value="Replace Element">
<br>
<input type="button" value="refresh" onclick="location.reload()">
</div>

use html5 output tag to display javascript variables?

Sorry if this is a silly question, but I've been trying to use AJAX to display my javascript variables in 'real time' with little luck. I'm definitely a beginner though so this could be the problem haha- When I see the AJAX code, it always seems to require an additional url that it refreshes, but I just want to refresh the javascript variables on click.
http://jsfiddle.net/bagelpirate/m9Pm2/
<script>
var one = 0;
var two = 0;
var three = 0;
</script>
<body>
<div id="div_1">
One: <script>document.write(one)</script> |
Two: <script>document.write(two)</script> |
Three: <script>document.write(three)</script>
</div>
<div id="div_2">
<img id="mine" src="https://si0.twimg.com/profile_images/3170725828/ac1d6621fc3c3ecaa541d8073d4421cc.jpeg" onclick="one++;" />
<img id="forest" src="http://blogs.dallasobserver.com/sportatorium/No.%202.png" onclick="two++;" />
<img id="farm" src="https://si0.twimg.com/profile_images/3732261215/bd041d1f0948b6ea0493f90507d67ef2.png" onclick="three++;" />
</div>
</body>
As you can see in the above code, when a user clicks one of the images, I want to increment the count and display it at the top of the page. I found the HTML5 output tag, and was wondering if it's possible to use this to display the javascript variable in real time? Everything I've read seems to imply it can't be done because the output tag only works on forms? Anyway, I figured it couldn't hurt to ask!
Thanks for your time!
You shouldn't use document.write to write to the DOM after it's finished loading. You have tagged your question with jQuery, so I'll assume you can use that to update things. Instead, update the DOM from within your script block. Here is an example that might help you get started.
http://jsfiddle.net/prxBb/
<script type="text/javascript">
$(function() {
var one = 0;
var two = 0;
var three = 0;
$('img#mine').click(function() {
one++;
$('span#one').html(one);
});
$('img#forest').click(function() {
two++;
$('span#two').html(two);
});
$('img#farm').click(function() {
three++;
$('span#three').html(three);
});
});
</script>
<body>
<div id="div_1">
One: <span id="one"></span> |
Two: <span id="two"></span> |
Three: <span id="three"></span>
</div>
<div id="div_2">
<img id="mine" src="https://si0.twimg.com/profile_images/3170725828/ac1d6621fc3c3ecaa541d8073d4421cc.jpeg" />
<img id="forest" src="http://blogs.dallasobserver.com/sportatorium/No.%202.png" />
<img id="farm" src="https://si0.twimg.com/profile_images/3732261215/bd041d1f0948b6ea0493f90507d67ef2.png" />
</div>
</body>
Maybe you should try putting all your variables inside a named object, iterating through it at predefined interval and displaying the values.
var varContainer = {
one:0,
two:0,
three:0
};
jQuery("#div_2 img").on('click',function(){
jQuery.each(varContainer,function(key,value){
//Add key + value to the DOM
if(jQuery("."+key+value).length<1)
jQuery("#div_2").append("<div class='"+key+value+"'></div>");
var newHtmlVal= "<p><span>Var name: "+key+"</span><br><span>Value: "+value+"</span>";
jQuery("."+key+value).html();
});
});
HTML
<div id="div_2">
</div>
Of course the script could be upgraded to look through each variable recursivley in case of nested objects/arrays...
Hope this helps!

Chrome Extension/Javascript Problems

I have been working on Chrome extension and am having problems. What I'm trying to do: when you click on the icon to the right of the search bar, a search bar comes up which you type your query in and hit enter. It will then go to http://dev.bukkit.org/search/?search=(whatever was entered). This is what I have but it is not working.
<scriptLANGUAGE="JavaScript">
function whatURL() {
window.location= 'http://dev.bukkit.org/search/?search=' + document.form1.url.value;
}
</SCRIPT>
<FORM name=form1>
<inputtype="text"id="url">
<inputtype="button"id="btnSearch"value="Search"onClick="return whatURL()"/>
</FORM>
Thank you:) Note: I have the manifest and everything, its just the javascript part thats not working.
EDIT: Rewrote it now it works!!!
<html>
<head>
<script>
function onLoad() {
document.getElementById("mytextfield").focus();
}
function onKeyPress(e) {
if (e.keyCode == 13) {
openResults();
}
}
function openHomePage() {
window.open("http://dev.bukkit.org/");
}
function openResults() {
window.open("http://dev.bukkit.org/search/?search=" + encodeURIComponent(document.getElementById("mytextfield").value));
}
</script>
</head>
<body onload="onLoad();">
<img src="png-3.png" onclick="openHomePage();" style="border-width: 0px; cursor: pointer" /><br>
<div name="myFormDiv" style="center: 6px;">
<br>
<input type="search" id="mytextfield" name="mytextfield" value="Search..." onkeypress="onKeyPress(event);" />
</div>
</div>
</body>
</html>
Try changing...
<inputtype="button"id="btnSearch"value="Search"onClick="return whatURL()"/>
to..
<inputtype="button"id="btnSearch"value="Search"onClick="whatURL()"/>
window.location doesn't need to be returned to anything. You're already making the window point to your given url when you execute window.location = "http://myurl.com"

Categories

Resources