Javascript is not running in HTML file [duplicate] - javascript

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed last year.
can someone be happy to help me, in my code below I'm trying to display a div with a dropdown select, but why is the existing javascript not working.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#business {
display: none;
}
#local {
display: none;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script>
$('#purpose').on('change', function () {
if (this.value === "1") {
$("#business").show();
$("#local").hide();
} else if (this.value === "2") {
$("#business").hide();
$("#local").show();
} else {
$("#business").hide();
$("#local").hide();
}
});
</script>
</head>
<body>
<select id='purpose'>
<option value="0">Personal use</option>
<option value="1">Business use</option>
<option value="2">Passing on to a client</option>
</select>
<div id="business">
<label for="business">Business Name</label>
<input type='text' class='text' name='business' value size='20' />
</div>
<div id="local">
<label for="local">Local Name</label>
<input type='text' class='text' name='local' value size='20' />
</div>
</body>
</html>
the above code works fine if i run it in fiddle, but not when i run it on my local computer, can someone help me, what should i do for the above problem, any kind of help i thank you.

The <select id='purpose'> doesn't exist yet when you try to run $('#purpose').on('change', ...). Either move your <script> tag to the end of the <body> tag, or add a defer attribute to the tag (which follows best practices anyways).

Related

Ways to wait for elements to load when adding eventlisteners

I'm playing around with parcel before I used liveserver in vscode and I rarely ran into this problem. I'm trying to add a eventlistener to a inputform. DOM isn't finding the element no matter what I do. I've tried to put a if statement checking if the element exist before putting a listener but it doesn't change anything. I never had this problem using liveserver, do i have to write a asynchronous function and wait for the page to load? I tried putting defer inside the script tag aswell. Is parcel slower than liveserver somehow?
const input1 = document.getElementById("input1");
if(input1)
{
console.log("The input exists");
input1.addEventListener('click', () =>{
console.log("heey");
});
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./assets/scss/main.scss">
</head>
<body>
<form>
<div class="form-group">
<label for="inputlg">input</label>
<input class="form-control input-lg" id="inputlg" type="text" id="input1">
<label for="inputlg">output</label>
<input class="form-control input-lg" id="inputlg" type="text">
</div>
</form>
<script type="module" src="./assets/js/main.js" ></script>
</body>
</html>
Your input has two ids. That's invalid, and getElementById doesn't see the second one.
const input1 = document.getElementById('input1');
console.log(input1); // null
const inputlg = document.getElementById('inputlg');
console.log(inputlg); // input#inputlg.form-control.input-lg
<input class="form-control input-lg" id="inputlg" type="text" id="input1">
There are a few ways.
(best) document.addEventListener('DOMContentLoaded', () => { // code here })
document.onreadystatechange = () => { if (document.readystate == "complete") { // code here } }
Also, it is a requirement that there is only 1 element assigned to each ID. In your code, you have 2 elements with ID "inputlg", which is not allowed. Get rid of those and it should work. You also have an element which you are trying to have 2 IDs on, which also does not work.
The code above is just to make sure that the document is fully loaded, and prevents errors.

Cannot set property innerHTML error

I am trying to automate the process of opening an external site from a button of an internal site that I created, but I can not reference the document I created, follow the code below, tried several times and could not, any help is valid, thank you so much.
<!DOCTYPE html>
<head>
<title>Principal</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="\\fswcorp\ceic\ssoa\gaacc\System\JQuery\jquery-3.2.1.min.js"></script>
<script src="\\fswcorp\ceic\ssoa\gaacc\System\jQueryMask\dist\jquery.mask.min.js"></script>
<script src="\\fswcorp\ceic\ssoa\gaacc\System\jQueryUI\jquery-ui.js"></script>
<script>
$(document).ready(function() {
$("#dateBegin").mask('00/00/0000');
$("#dateEnd").mask('00/00/0000');
$("#buttonDownloadBRScan").click(function() {
$windowopen = window.open();
$windowopen.location.href = "https://www.fdibr.com.br/autenticacao/autenticacao/login";
$test = $windowopen.document.getElementById("usuario").innerHTML = "7478704";
})
});
</script>
</head>
<body>
<div class="dataInput">
<label id="labelDateBegin">Data Inicial</label>
<input id="dateBegin" type="date" />
<label id="labelDateEnd">Data Final</label>
<input id="dateEnd" type="date" />
</div>
<br><br>
<button id="buttonDownload">Download</button>
<button id="buttonDownloadBRScan">Download BRScan</button>
</body>
Assuming you have access to that domain in the window you're opening (same origin policy), you have to wait for the window to finish opening first before accessing elements inside.
$("#buttonDownloadBRScan").click(function(){
const w = window.open('https://www.fdibr.com.br/autenticacao/autenticacao/login');
w.addEventListener('DOMContentLoaded', () => {
w.document.getElementById("usuario").innerHTML = "7478704";
});
})
Try something like this:
<input id="yourID" type="button" onclick="open_page()" value="Your Message Here"/>
<script>
function open_page () {
window.open('Your Webpage');
}
</script>
the external site and your internal site have different domain,you can't modify the external site content from your internal site directly.you can use window.postMessage,maybe it would resolve your problem

How to select an ID in Jquery for an if statement

I want to use a form selector as shown, and depending on the option selected, a different output. Simple, yet I am not getting it to work. Here is what I have.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
$(document).ready(function(){
if ("#1") {
$("#display").html("<table width="221"><tbody><tr class="su-even"><td width="64"><strong>Level</strong></td><td width="64"><strong>Damage</strong></td><td width="93"><strong>Crown Tower Damage</strong></td></tr><tr><td width="64">1</td><td width="64">80</td><td width="93">32</td></tr></tbody></table>");
}
if ("#2") {
$("#display").html("<table width="221"><tbody><tr class="su-even"><td width="64"><strong>Level</strong></td><td width="64"><strong>Damage</strong></td><td width="93"><strong>Crown Tower Damage</strong></td></tr><tr><td width="64">2</td><td width="64">88</td><td width="93">36</td></tr></tbody></table>");
}
});
</script>
</head>
<body>
<div>
<form id="option">
<label for="level">Level at a glance:</label>
<select name="level" id="level">
<option id="1">1</option>
<option id="2">2</option>
</select>
</form>
<div id="display">
</div>
</div>
</body>
</html>
There were a couple issues here.
First of all, "#1" and "#2" are always going to == true, since they are strings.
Second, the code that changes the text only happens once, on page load. There is nothing telling it to update after the menu is changed.
Third, on the lines starting with $("#display").html...., you had what should have been a very long string, but you broke it up by using double quotes every time. You need to switch between single and double quotes. If I say, "class="potato">", it sees "class=" as one string, and ">" as another, but it doesn't know what to do with potato. You need to use single quotes, like "class='potato'>" or 'class="potato">'.
This is the fixed code:
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
function changeText(){
if ($("#level option:selected").text() == "1") {
$("#display").html("<table width='221'><tbody><tr class='su-even'><td width='64'><strong>Level</strong></td><td width='64'><strong>Damage</strong></td><td width='93'><strong>Crown Tower Damage</strong></td></tr><tr><td width='64'>1</td><td width='64'>80</td><td width='93'>32</td></tr></tbody></table>");
}
if ($("#level option:selected").text() == "2") {
$("#display").html("<table width='221'><tbody><tr class='su-even'><td width='64'><strong>Level</strong></td><td width='64'><strong>Damage</strong></td><td width='93'><strong>Crown Tower Damage</strong></td></tr><tr><td width='64'>2</td><td width='64'>88</td><td width='93'>36</td></tr></tbody></table>");
}
}
$(document).ready(function(){
changeText();
});
</script>
</head>
<body>
<div>
<form id="option">
<label for="level">Level at a glance:</label>
<select name="level" id="level" onchange="changeText()">
<option id="1" >1</option>
<option id="2">2</option>
</select>
</form>
<div id="display">
</div>
</div>
</body>
Your javascript conditions are executed once, when the document is ready.
You have to add an event, when the select value change !
Add some values in your option elements ( <option value="1">1</option> )
$(document).ready(function(){
// Set event
$("#level").change(function(){
if ($(this).val() === "1") {
$("#display").html(...);
} else {
$("#display").html(...);
}
}
// Call event when document loaded
$("#level").change();
});

Dynamically Add and Remove HTML Elements not working

I need to dynamically add and remove HTML elements to my product form (attribute addition purpose) and was searching stack overflow.
I found this solution to be very close (except it does not has a remove option plus I sincerely do not know how to retrieve the data of each textbox, but all this later).
https://jsfiddle.net/nzYAW/
The code in the fiddle works fine. But as I tried it on my local machine it fails to produce any result.
Here is what I did
index.html
<!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>Untitled Document</title>
<style type="text/css">
.extraPersonTemplate {display:none;}
</style>
<script type="text/javascript">
$(document).ready(function () {
$('<div/>', {
'class': 'extraPerson',
html: GetHtml()
}).appendTo('#container');
$('#addRow').click(function () {
$('<div/>', {
'class': 'extraPerson',
html: GetHtml()
}).hide().appendTo('#container').slideDown('slow');
});
})
function GetHtml() {
var len = $('.extraPerson').length;
var $html = $('.extraPersonTemplate').clone();
$html.find('[name=firstname]')[0].name = "firstname" + len;
$html.find('[name=lastname]')[0].name = "lastname" + len;
$html.find('[name=gender]')[0].name = "gender" + len;
return $html.html();
}
</script>
</head>
<body>
<div class="extraPersonTemplate">
<div class="controls controls-row">
<input class="span3" placeholder="First Name" type="text" name="firstname">
<input class="span3" placeholder="Last Name" type="text" name="lastname">
<select class="span2" name="gender">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
</div>
<div id="container"></div>
<i class="icon-plus-sign icon-white"></i> Add another family member</p>
</body>
</html>
and this is the result
Where did I go wrong at copy paste?
You need to load jQuery library
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You need to include jQuery. If you check your javascript console (which you definetly should) you will probably find this error:
$ is not defined
That is because jQuery wasn't loaded before you try to use it. Add this to your page before your javascript code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can see in the JSFiddle that you include these libraries, but you don't include them when you just copy paste this.
Include these javascripts
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
Move the JavaScript to be right above the </body> tag.
I think if you're trying to access elements before the page has loaded them, then it won't work.
Also as other answers have pointed out, be sure you've included jQuery in the <head></head> section of your page.

onchange javascript to submit form breaks in jquerymobile

i was using a javascript like this...
<select onchange="document.langForm.submit();" ... >
but that broke when i started using jquerymobile.
i know this issue has come up 100 times before. but hyperlinks to prior cases wont help here because i have already read dozens and unfortunately i am just not smart enough to understand any of those other discussions. seriously. i am totally confused.
on the other hand, i have made time to make a REALLY, REALLY simple example to show the headache i have. so, if someone can tell me exactly how to fix these two pages, that would be very much appreciated.
http://activemetrics.ch/test/en.html
http://activemetrics.ch/test/de.html
notice that you can load either one of these in your browser and then switch to the other page by changing the selection in the select list. however, after you get to the second page, you can not use a similar action to get back to the first page.
yes, this has to with ajax. i know that much. but what is the very best way for me to fix the problem right here on these 2 pages to allow users to switch back and forth between the two pages easily?
all suggestions are welcome.
thanks very much to anyone who is spending some of their brain waves considering this for me!
-jd
Description :
To understand this situation you need to understand how jQuery Mobile works. It uses ajax to load other pages.
First page is loaded normally. Its HEAD and BODY is loaded into the DOM, and they are there to await other content. When second page is loaded, only its BODY content is loaded into the DOM.
From what I have so in your answer you understand this but you had make a mistake. There are 2 html files: en.html and de.html but their names are not slightly important. What is important is page id's or id's attribute of data-role="page" div. In your case you have 2 pages with a same div and with a same select id. Because both of them are loaded into the DOM event binding will always go to the first loaded page.
What you need to to is use unique id for your pages and your select boxes.
Working example :
en.html
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.1/jquery.mobile-1.2.1.min.css" />
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.1/jquery.mobile-1.2.1.min.js"></script>
</head>
<body>
<div data-role="page" id="sbePage1">
<h3>this is english</h3>
<form name="langForm" id="langForm" action="BookNow.asp?" method="get" style="margin-top:0px auto">
<select data-inline="true" name="lang" id="langId" data-native-menu="false" >
<option value="1972" SELECTED>Something Already Selected</option>
<option value="1973">Some Sort of Change</option>
</select>
</form>
<script>
$(document).on('pageinit', '#sbePage1' ,function () {
$(document).off('change', '#langId').on('change', '#langId',function (event) {
$.mobile.changePage('de.html', {
type: 'get',
data: ''
});
});
});
</script>
</div><!-- /page -->
</body>
</html>
de.html
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.1/jquery.mobile-1.2.1.min.css" />
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.1/jquery.mobile-1.2.1.min.js"></script>
</head>
<body>
<div data-role="page" id="sbePage2">
<h3>this is german</h3>
<form name="langForm2" id="langForm2" action="BookNow.asp?" method="get" style="margin-top:0px auto">
<select data-inline="true" name="lang" id="langId2" data-native-menu="false" >
<option value="1972" SELECTED>Something Already Selected</option>
<option value="1973">Something Else</option>
</select>
</form>
<script>
$(document).on('pageinit', '#sbePage2' ,function () {
$(document).off('change', '#langId2').on('change', '#langId2',function (event) {
$.mobile.changePage('en.html', {
type: 'get',
data: ''
});
});
});
</script>
</div><!-- /page -->
</body>
</html>
Edit :
While I understand your wish, I still must tell you that it is impossible. You can't have 2 pages with a same id with jQuery Mobile in your current example. Think about it, you will have 2 pages with an identical id loaded into the DOM. Each time you try to access the page DIV you will ALWAYS access the first page because it is first in line.
If you want to create a multilingual page you don't need several html pages. Just look for a good jQuery multilingual plugin.
On the other hand you can do what you want if you turn ajax off but you will loose animated transitions.
Example without ajax but where pages have same id
en.html:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.1/jquery.mobile-1.2.1.min.css" />
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script language="text/javascript">
$(document).bind("mobileinit", function () {
$.mobile.ajaxEnabled = false;
});
</script>
<script src="http://code.jquery.com/mobile/1.2.1/jquery.mobile-1.2.1.min.js"></script>
</head>
<body>
<div data-role="page" id="sbePage1en">
<h3>this is english</h3>
<form name="langFormEn" id="langFormEn" action="BookNow.asp?" method=get style="margin-top:0px auto">
<select data-inline="true" name="lang" id="langId" data-native-menu="false" >
<option value="1972" SELECTED>Something Already Selected</option>
<option value="1973">Some Sort of Change</option>
</select></form>
<script>
$("#sbePage1en").live('pageshow', function () {
$('#langFormEn').bind('change', function (event) {
$.mobile.changePage('de.html', {
type: 'get',
data: ''
});
});
});
</script>
</div><!-- /page -->
</body>
</html>
de.html
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.1/jquery.mobile-1.2.1.min.css" />
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script language="text/javascript">
$(document).bind("mobileinit", function () {
$.mobile.ajaxEnabled = false;
});
</script>
<script src="http://code.jquery.com/mobile/1.2.1/jquery.mobile-1.2.1.min.js"></script>
</head>
<body>
<div data-role="page" id="sbePage1de">
<h3>this is german</h3>
<form name="langFormDe" id="langFormDe" action="BookNow.asp?" method=get style="margin-top:0px auto">
<select data-inline="true" name="lang" id="langId" data-native-menu="false" >
<option value="1972" SELECTED>Something Already Selected</option>
<option value="1973">Something Else</option>
</select></form>
<script>
$("#sbePage1de").live('pageshow', function () {
$('#langFormDe').bind('change', function (event) {
$.mobile.changePage('en.html', {
type: 'get',
data: ''
});
});
});
</script>
</div><!-- /page -->
</body>
</html>

Categories

Resources