jQuery - Disable href based on checkbox - Location of script? - javascript

Not sure what I am doing wrong, but I am very much a novice with javascript and html so probably a lot. I am trying to enable / disable an href link based on the selection of the check box. Here is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Page Title</title>
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;"/>
<meta http-equiv="keywords" content="keyword1, keyword2" />
<meta http-equiv="description" content="Description of Page" />
<link href="css/style.css"rel="stylesheet" type="text/css" />
<style type="text/css">
.auto-style1 {
font-size: 12px;
color: #4d4d4d;
line-height: 2em;
margin: 5px;
padding: 0;
text-align: center;
}
.auto-style2 {
text-align: center;
}
.auto-style3 {
font-family: Neogrey;
}
</style>
<script type="jQuery">
$('#link').click(function(){return false; });
$('#check').click(function() {
if(!$(this).is(':checked')){
$('#link').bind('click', function(){ return false; });
}else{
$('#link').unbind('click');
}
});</script>
</head>
<body>
<div class="auto-style2">
<form id="form1" runat="server">
<div class="logo"><h1 class="auto-style3">
</h1></div>
<h2 class="head">Header Text</h2>
<div class="auto-style1">
Welcome Text.<br />
<input type="checkbox" id="check"/><label for="check">I accept the Terms of Service.</label>
<br />
<a href="http://www.google.com" id="link">
<img alt="" height="30" src="images/download.png" width="100" /></a><br />
</div>
<div class="footer">
<div class="menu">
iOS
Android
Blackberry
Support
</div>
</div>
</form>
</div>
</body>
</html>
Any help is greatly appreciated!

Once you've included jQuery, I'd suggest making use of the DOM to make the script a little more efficient:
// bind the click-handler:
$('#link').click(function(e){
// prevent the default action of clicking on a link:
e.preventDefault();
// if the element with id 'check' is checked:
if (document.getElementById('check').checked){
// change the window.location to the 'href' of the clicked-link:
window.location = this.href;
}
});
JS Fiddle demo.
This would lead to the following HTML of your <head> element:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Page Title</title>
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;"/>
<meta http-equiv="keywords" content="keyword1, keyword2" />
<meta http-equiv="description" content="Description of Page" />
<link href="css/style.css"rel="stylesheet" type="text/css" />
<style type="text/css">
/* CSS removed for brevity */
</style>
<!-- note that this must come before the script containing the jQuery code
which in this case follows immediately -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="jQuery">
$('#link').click(function(e){
e.preventDefault();
if (document.getElementById('check').checked){
window.location = this.href;
}
});
</script>
</head>
Alternatively (though you still need to include jQuery), you could use the following approach:
// binds a change-handler function to the check-box:
$('#check').change(function () {
/* adds the 'disabled' class to the '#link' element if
the '#check' element is _not_ checked, and removes the
class if the '#check' element _is_ checked: */
$('#link').toggleClass('disabled', !this.checked);
/* triggers the change event-handler (so the class-name is toggled
appropriately on page-load: */
}).change();
/* attaches a delegated click-handler to the 'body' element,
if the click occurs on an 'a' element with the 'disabled'
class the function is executed:
*/
$('body').on('click', 'a.disabled', function(e){
// the default behaviour is prevented
e.preventDefault();
});
JS Fiddle demo.
References:
change().
click().
document.getElementById().
event.preventDefault().
on().
toggleClass().
window.location.

Put the following line in between your and tags to be able to use jquery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
Change your line that says:
<script type="jQuery">
To:
<script type="text/javascript">

jsFiddle example
As Tom Gerken was the first to point out, you must include the jQuery library as he demonstrated in his answer. This is really the key point in solving your problem and Tom should receive credit for the correct solution.
However, here is another approach for enabling/disabling the link:
Begin with your href set to "#", as in:
<a href="#" id="link">
Your jQuery code block would do this:
$('#check').click(function() {
if( $(this).is(':checked') ){
$('#link').attr('href','http://www.google.com');
}else{
$('#link').attr('href','#');
}
});
Full Code Example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Page Title</title>
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;"/>
<meta http-equiv="keywords" content="keyword1, keyword2" />
<meta http-equiv="description" content="Description of Page" />
<link href="css/style.css"rel="stylesheet" type="text/css" />
<style type="text/css">
.auto-style1 {
font-size: 12px;
color: #4d4d4d;
line-height: 2em;
margin: 5px;
padding: 0;
text-align: center;
}
.auto-style2 {
text-align: center;
}
.auto-style3 {
font-family: Neogrey;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<style>
</style>
<script type="text/javascript">
$(document).ready(function() {
$('#link').click(function(){return false; });
$('#check').click(function() {
if( $(this).is(':checked') ){
$('#link').attr('href','http://www.google.com');
}else{
$('#link').attr('href','#');
}
});
}); //END $(document).ready()
</script>
</head>
<body>
<div class="auto-style2">
<form id="form1" runat="server">
<div class="logo"><h1 class="auto-style3">
</h1></div>
<h2 class="head">Header Text</h2>
<div class="auto-style1">
Welcome Text.<br />
<input type="checkbox" id="check"/><label for="check">I accept the Terms of Service.</label>
<br />
<a href="#" id="link">
<img alt="" height="30" src="images/download.png" width="100" /></a><br />
</div>
<div class="footer">
<div class="menu">
iOS
Android
Blackberry
Support
</div>
</div>
</form>
</div>
</body>
</html>

Related

Changing h1 element based on input element content Vanilla JS

Why the h1 tag does not change?
Is there anything wrong?
I tried it with alert and it worked perfectly. I mean whenever I typed into input box the alert message showed me the characters. but how about h1 tag?
what did I do wrong?
Here is my snippet:
html {
box-sizing: border-box;
font-size: 2rem;
font-family: 'Georama', sans-serif;
}
body {
background-color: #555;
color: #fff;
display: flex;
justify-content: center;
flex-direction: column;
height: 100vh;
align-items: center;
}
button {
cursor: pointer;
}
.container {
width: auto;
height: 100px;
}
.te {
display: block;
color: white;
}
const text = document.getElementById('pps');
pass.addEventListener('input', (e) => {
const val = e.target.value;
text.innerHTML(val);
});
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
<script src="main.js" defer></script>
</head>
<body>
<form class="container">
<label>Type here:</label>
<input
type="text"
placeholder="insert here.,.."
/>
</form>
<h1 class="te" id="pps">PP</h1>
</body>
</html>
</html>
I see two mistakes here:
As it was mentioned in comments innerHTML is property, not a method, so should be called text.innerHTML = e.target.value;
You didn't assign anything to the 'pass' variable.
Also, there's no sense to create the variable if you are going to use the value only once, so we can remove const val = e.target.value; and just use e.target.value directly.
I've attached the working snippet below.
const text = document.getElementById('pps')
document.getElementById('textInput').addEventListener('input', (e) => {
text.innerHTML = e.target.value;
});
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
<script src="main.js" defer></script>
</head>
<body>
<form class="container">
<label>Type here:</label>
<input type="text" id="textInput" placeholder="insert here..." />
</form>
<h1 class="te" id="pps">PP</h1>
</body>
</html>
</html>

Make JavaScript choose image and display it from an array (randomly)

With my code, I made an array for JavaScript to randomly choose an image and display it. But its not showing. Please help.
This is my code currently:
HTML & JS
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="https://images-na.ssl-images-amazon.com/images/I/41I+vcnXn-L._AC_UL600_SR600,600_.png" />
<title>Noice Game</title>
</head>
<body>
<img id="img1" src="" alt="" />
<button class="foodbtn" onclick="GetImage();" id="imagebtn">
Begin!
</button>
<body>
<html>
<script>
function GetImage()
{
var imagearray= new Array("https://cdn.madeinturkeytours.com/wp-content/uploads/2020/02/vegan-cig-kofte.jpg","https://deih43ym53wif.cloudfront.net/large_spanakopita-greek-food_dd3bda740c.jpeg","https://static.toiimg.com/thumb/53099699.cms?width=1200&height=900","https://www.travelbuddies.info/wp-content/uploads/2020/02/tsuivan.jpg");
var randomimagesrc = imagearray[Math.floor(Math.random() * imagearray.length)];
}
$("#img1").attr("src", imagearray[randomimagesrc]);
</script>
<style>
#img1 {
size: 400px;
z-index: 1000;
}
</style>
You need to move $("#img1").attr(...) inside the GetImage() function. Also, since you are accessing a random element in randomimagesrc, there is no need to do imagearray[randomimagesrc] while setting the src.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="https://images-na.ssl-images-amazon.com/images/I/41I+vcnXn-L._AC_UL600_SR600,600_.png" />
<title>Noice Game</title>
</head>
<body>
<img id="img1" src="" alt="" />
<button class="foodbtn" onclick="GetImage()" id="imagebtn">
Begin!
</button>
<body>
<html>
<script>
function GetImage() {
var imagearray = new Array("https://cdn.madeinturkeytours.com/wp-content/uploads/2020/02/vegan-cig-kofte.jpg", "https://deih43ym53wif.cloudfront.net/large_spanakopita-greek-food_dd3bda740c.jpeg", "https://static.toiimg.com/thumb/53099699.cms?width=1200&height=900", "https://www.travelbuddies.info/wp-content/uploads/2020/02/tsuivan.jpg");
var randomimagesrc = imagearray[Math.floor(Math.random() * imagearray.length)];
$("#img1").attr("src", randomimagesrc);
}
</script>
<style>
#img1 {
size: 400px;
z-index: 1000;
}
</style>
You have provided change src sript outside the GetImage() function and when you already have created new variable which is random, then you can use it directly in randomimagesrc
function GetImage()
{
var imagearray= new Array(
"https://cdn.madeinturkeytours.com/wp-content/uploads/2020/02/vegan-cig-kofte.jpg",
"https://deih43ym53wif.cloudfront.net/large_spanakopita-greek-food_dd3bda740c.jpeg",
"https://static.toiimg.com/thumb/53099699.cms?width=1200&height=900",
"https://www.travelbuddies.info/wp-content/uploads/2020/02/tsuivan.jpg"
);
var randomimagesrc = imagearray[Math.floor(Math.random() * imagearray.length)];
$("#img1").attr("src", randomimagesrc);
}
#img1 {
size: 400px;
z-index: 1000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img id="img1" src="" alt="" />
<button class="foodbtn" onclick="GetImage();" id="imagebtn">
Begin!
</button>
The problems you had:
You had html lang="en">. You forgot to add an extra < before that code.
Secondly, I think it would be better if the script and style tag were inside the html tag.
I recommend using HTML DOM over jQuery.
Also put the HTML dom inside the function.
Now you're done!
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="https://images-na.ssl-images-amazon.com/images/I/41I+vcnXn-L._AC_UL600_SR600,600_.png" />
<title>Noice Game</title>
</head>
<body>
<img id="img1" src="" alt="" /> <br>
<button class="foodbtn" onclick="GetImage();" id="imagebtn">
Begin!
</button>
<body>
<script>
function GetImage()
{
var imagearray= new Array("https://cdn.madeinturkeytours.com/wp-content/uploads/2020/02/vegan-cig-kofte.jpg","https://deih43ym53wif.cloudfront.net/large_spanakopita-greek-food_dd3bda740c.jpeg","https://static.toiimg.com/thumb/53099699.cms?width=1200&height=900","https://www.travelbuddies.info/wp-content/uploads/2020/02/tsuivan.jpg");
var randomimagesrc = imagearray[Math.floor(Math.random() * imagearray.length)];
document.getElementById('img1').src = randomimagesrc;
}
$("#img1").attr("src", imagearray[randomimagesrc]);
</script>
<style>
#img1 {
size: 400px;
z-index: 1000;
}
</style>
<html>
Here's your new code.
Edit: Forgot to add that you can make the picture fixed size, so you don't need to chase the button.
<style>
img#img1 {
width: 100px;
height: 100px;
}
</style>

Why after first click, i need to click two times to reverse

So my problem is that when i click on a radiobutton to add the class "completed", it does what is suposed to do, but when i want to remove it, i need to click two times, i don't know why. Any help would be appreciated. Thank you
html
<!DOCTYPE html>
<html>
<head>
<title>Todo App</title>
<link rel="stylesheet" type="text/css" href="TodoApp.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- displays site properly based on user's device -->
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- ------ Meta Tags ------ -->
</head>
<body>
<div id="container">
<div id="topImage">
<h1 id="topImage-title">T O D O</h1>
<img onclick="test()" id="moon" src="images/icon-moon.svg">
<img src="images/bg-mobile-light.jpg" width="100%" height="100%">
</div>
<div class="newToDo">
<input onclick="addTask()" id="ready" type="radio" name="ready">
<input type="text" name="todoTask" id="todoTask" placeholder="Create a new todo...">
</div>
<div id="tasksBox">
<div class="newTasks">
<input onclick="completeTask()" type="radio" class="bttComplete" name="bttComplete">
<span>Complete Online Javascript Course</span>
<div onclick="deleteTask()" class="delete"></div>
</div>
</div>
</div>
<script src="jquery_library/jquery-3.5.1.min.js"></script>
<script src="TodoApp.js"></script>
</body>
</html>
css
.completed{
background-image: url(images/icon-check.svg);
background-position: center;
background-repeat: no-repeat;
}
javascript
function completeTask(){
$(".newTasks").click(function(){
if ($(this).children().hasClass('completed')){
$(this).children().removeClass('completed');
} else {
$(this).children().addClass('completed');
};
});
}

Internet Explorer 7+ returns the error "Object expected" although none of the other browsers do

Each time I load a page in Internet Explorer 7 or greater I get the error Object Expected when calling the function below. The script appears right at the bottom of the page before the closing </body> tag. There are no elements with the same name or id.
<script type="text/javascript">
window.onload = show();
</script>
The Javascript function it is attempting to call is
function show() {
obj1
= document.getElementById("container").innerHTML
= '<div style="width: 960px; height: 2000px;"><p>Hello World.<br>Here I am.</p>'
+ '<p>test</p></div>';
}
Why does this error not appear in any of the other browsers?
What do I need to change to resolve the issue?
EDIT 0
If I move the function show into the same block at window.onload, hide() now no longer works.
Javascript code
function show() {
obj1
= document.getElementById("container").innerHTML
= '<div style="width: 960px; height: 2000px;"><p>Hello World.<br>Here I am.</p>'
+ '<p>test</p></div>';
}
function hide() {
obj1 = document.getElementById("container");
if(obj1){
alert("Hi");
obj1.style.display = "none";
obj1.style.visibility = "hidden";
}else{
alert("Cannot find the element with id container.");
}
}
HTML code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict/EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtm1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset="UTF-8" />
<meta http-equiv="content-language" content="en-us" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<meta name="author" content="" />
<meta name="copyright" content="© 2012" />
<title>takeover</title>
<base href="" />
<link rel="stylesheet" href="" />
<style type="text/css" media="all" />
#container {
position:absolute;
text-align:center;
background-color:#fff;
z-index:9999;
}
</style>
<script type="text/javascript" src="takeover.js"></script>
</head>
<body>
<div>
<div id="container"></div>
<p>qwe</p>
</div>
<script type="text/javascript">
window.onload = show;
</script>
</body>
</html>
EDIT 1
Message that appears when using non-Internet Explorer browsers when placing alert(show) before window.onload
EDIT 2
The message displayed after removing all the white spaces. Again this only works in non-Internet Explorer browsers.
EDIT 3
Tried window.show = function show() and window.hide = function hide() however still get an error in Internet Explorer. The error is show as below.
EDIT 4
Here is the updated code with all the functions in a single file. This does not work in any other browser and I get the error show is undefined.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict/EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtm1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset="UTF-8" />
<meta http-equiv="content-language" content="en-us" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<meta name="author" content="" />
<meta name="copyright" content="© 2012" />
<title>takeover</title>
<base href="" />
<link rel="stylesheet" href="" />
<style type="text/css" media="all" />
#container {
position:absolute;
text-align:center;
background-color:#fff;
z-index:9999;
}
</style>
</head>
<body>
<div>
<div id="container"></div>
<p>qwe</p>
</div>
<script type="text/javascript">
alert(show)
window.show = function show() {
obj1 = document.getElementById("container").innerHTML = '<div style="width: 960px; height: 2000px;"><p>Hello World.<br>Here I am.</p><p>test</p></div>';
}
window.hide = function hide() {
obj1 = document.getElementById("container");
if(obj1)
{
alert("Hi");
obj1.style.display = "none";
obj1.style.visibility = "hidden";
}
else
{
alert("Cannot find the element with id container.");
}
}
window.onload = window.show;
</script>
</body>
</html>
This line...
window.onload = show();
Should be this...
window.onload = show;
...because you need to assign the show function itself to window.onload, not its return value from calling it.
Move the <script> block that references container to a point after container is defined:
<!DOCTYPE HTML>
<HTML>
<HEAD>
</HEAD>
<BODY>
<DIV id="container"></DIV>
<script type="text/javascript">
window.onload = show;
function show() {
obj1 = document.getElementById("container").innerHTML = '<div style="width: 960px; height: 2000px;"><p>Hello World.<br>Here I am.</p>' +
'<p>test</p></div>';
}
</script>
</BODY>
</HTML>
If the <script> block is, for example, inside the <head> then Internet Explorer gives the error:
SCRIPT5007: Unable to set value of the property 'innerHTML': object is null or undefined
on page load.

jquery mobile changePage() not working correctly

I am creating a webapp using phonegap and jquerymobile. When i am using changePage to go to other page then it is not working.Here is my code
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width; user-scalable=no" />
<script type="text/javascript" charset="utf-8" src="phonegap-1.4.1.js"></script>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<link rel="stylesheet" href="jquery.mobile-1.0.1.min.css" />
<script type="text/javascript" src="jquery.mobile-1.0.1.min.js"></script>
</head>
<script type="text/javascript">
function clickEvent()
{
$.mobile.changePage("account_page.html", null, true, true);
}
</script>
<body>
<div style="top: 0; left: 0; position: absolute; z-index: 1;">
<img src="images/login_screen.JPG" alt="login_screen" width="320" onclick="clickEvent()"/>
</div>
</body>
</html>
But when i use
window.location.href = 'file:///android_asset/www/account_page.html';
Then it is working...Why is it so?
$.mobile.changePage doesnt load another html into view. it scans the html in the html whose link u gave, gets the first jqm 'page' on it and adds that into the dom(not the entire html) If this is not what you intended to do and wanted to load the full account_page.html into the dom then u'll have to use either
window.location.href or navigator.app.loadUrl

Categories

Resources