Code below.
I'm complete balls at JS, and I have no idea what I did wrong. I /had/ it working, so that when the user input a name, it would display 'Name: {outputn}' on the next page after clicking submit. Afterwards, I put in a form html field below it, not displayed here because it was removed, and now it no longer works, even though it's the same code I had previously.
PS: In addition, if someone happens to know, is there a way I could add additional fields, ex gender, and have them be applied with the same submit button?
<div class="content active">Username: <input type="text" id="userName"></input>
<script>
var didClickIt = false;
document.getElementById("submitter").addEventListener("click",function(){
didClickIt = true;
});
setInterval(function(){
if( didClickIt ) {
didClickIt = false;
var o=document.getElementById("outputn"),v=document.getElementById("userName").value;
if(o.textContent!==undefined){
o.textContent=v;
}else{
o.innerText=v;
}
}
},05);
</script>
<button id="submitter" style="background:#ffffff;">Submit</button><br>
</div>
<div class="content"><p>Name: <div id="outputn"></div></p></div>
It seems to work for me here http://jsfiddle.net/NA9BM/2/
I added another element so you can see how you could do it with the same logic.
<div class="content active">
Username: <input type="text" id="userName"></input><br>
Email: <input type="text" id="email"></input>
<button id="submitter" style="background:#ffffff;">Submit</button>
</div>
<div class="content">
<p>Name:
<div id="outputn"></div>
</p>
<p>Email:
<div id="outpute"></div>
</p>
</div>
And the js
var didClickIt = false;
document.getElementById("submitter").addEventListener("click",function(){
didClickIt = true;
});
setInterval(function(){
if( didClickIt ) {
didClickIt = false;
var o=document.getElementById("outputn"), v=document.getElementById("userName").value;
var eo = document.getElementById("outpute"), e = document.getElementById("email").value;
if(o.textContent!==undefined && eo.textContent!==undefined){
o.textContent=v;
eo.textContent=e;
}else{
o.innerText=v;
eo.innerText=e;
}
}
},05);
You can try putting the script tag on the bottom to let the DOM load correctly before actually loading the script.
Place your <script> block after you have already declared your #submitter element - addEventListener() can't listen to events on nodes that haven't already appeared in the page.
Additionally, your code is overly complicated. Instead of checking to see if the button has been checked, just have the event fire your code directly when the listener is triggered:
document.getElementById("submitter").addEventListener("click", function () {
var o = document.getElementById("outputn"),
v = document.getElementById("userName").value;
if (o.textContent !== undefined) {
o.textContent = v;
} else {
o.innerText = v;
}
});
Your JavaScript code in the <script> block is executed as the page loads, so it will encounter and execute getElementById("submitter") before the <button id="submitter"> is encountered by the browser.
Move your code inside a DOMContentLoaded event-handler, then the submitter element will be available:
document.addEventListener('DOMContentLoaded', function () {
var didClickIt = false;
document.getElementById("submitter").addEventListener("click",function(){
didClickIt = true;
});
});
Another option is to move the <script> block to the bottom of the page.
If you need to support older browsers, use window.onload instead of DOMContentLoaded.
Move your script part at the end of document.
When executing the line:
document.getElementById("submitter")
DOM was not ready (not all elements created) so your search for "submitter" produced NULL.
In fact, the proper way is to wait DOM to create all elements - see documentation for JavaScript or use jQuery.
<script type="text/javascript">
function init(){
//Your code
}
window.onload = init;
</script>
Related
inside my index.ejs i inserted an Iframe Tag to embed another document within the current document. Inside this Iframe i have a Form.
<iframe
src="purchase/form.html" scrolling="yes" id="purchase"
style="min-width:280px;width:100%;height:400px;border:none;"
frameborder="none"
allowTransparency="true" >
</iframe>
Inside this Form i want to target a Button with the class of stripe_button and the code looks like this
<button type="submit" class="btn btn-primary btn-lg stripe_button" style="z-index: 1;">
<span class="fa fa-credit-card-alt" aria-hidden="true"></span>
Pay
</button>
Doing this with the following Javascript code
// target iframe inside index.ejs
var iframe = document.getElementById('purchase')
// get iframe content
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
// targeting class and awaiting click event to run function
var stripe = innerDoc.getElementsByClassName('stripe_button')
for (var i = 0; i < stripe.length; i++) {
var stripe_button = stripe[i]
stripe_button.addEventListener('click', purchaseClicked)
}
the whole code is inside my ready function
if (document.readyState == 'loading') {
document.addEventListener('DOMContentLoaded', ready)
} else {
ready()
If i try to run this i get Failed to load resource: the server responded with a status of 404 (Not Found)
and i assume it's because im trying to submit a form on localhost and that makes sense so far also tells me that the click event is working.
But if i delete type="submit" from the button and refresh nothing happens although the
purchaseClicked function should get into work.
The purchaseClicked function looks like this
function purchaseClicked() {
var priceElement = document.getElementsByClassName('zahl')[0]
var price = parseFloat(priceElement.innerText.replace('$', '')) * 100
updateCartTotal()
stripeHandler.open({
amount: price
})
}
basically it calls stripe popup payment.
And i know that this works if i would assign the button from within my index.ejs file
for example: document.getElementsByClassName('checkout_button')[0].addEventListener('click', purchaseClicked)
I assume it has something to do with the click event.
Same Domain. Im aware of CROSS.
wrapping this function into a entire new function
function stripe() {
// target iframe inside index.ejs
var iframe = document.getElementById('purchase')
// get iframe content
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
// targeting class and awaiting click event to run function
var stripe = innerDoc.getElementsByClassName('stripe_button')
for (var i = 0; i < stripe.length; i++) {
var stripe_button = stripe[i]
stripe_button.addEventListener('click', purchaseClicked)
}
}
and calling it inside iframe
parent.function()
solved it.
I have a .cshtml file with the following in the head tag:
<script type="text/javascript">
getPlatform = function() {
if (Platform.Android) {
return "androidlink";
}
else if (Platform.IOS) {
return "IOSLink";
}
else {
return "other";
}
}
</script>
The reason I've inserted this is because this logic was already taken care of in another javascript file which I've imported in. Essentially what I need to do is change the link of a button depending on which platform the user is using. I've tried the following but this does not work (and even if it did, looks messy and I'm sure incorrect) but I can't seem to find a solution. Can anyone help please?
</div>
getPlatform()</script> id="mobilelink" class="btn"
</div>
One cannot write this:
getPlatform()</script> id="mobilelink" class="btn"
This is how it can be done:
</div>
<a href="" id="mobilelink" class="btn" </a>
</div>
<!-- Later in the page (ideally just before the end </body> tag) -->
<script>
document.getElementById('mobileLink).href = getPlatform()
function getPlatform () {
if (Platform.Android) {
return "androidlink";
}
else if (Platform.IOS) {
return "IOSLink";
}
else {
return "other";
}
}
</script>
why don't you check it when the page is loaded and change the href of the a tag accordingly? Like:
<a id = "mobileLink" href="">some text</a>
And
var getPlatform = function() {
if (Platform.Android) {
return "androidlink";
}
else if (Platform.IOS) {
return "IOSLink";
}
else {
return "other";
}
}
document.getElemenyById("mobileLink").href = getPlatform
//Or innerHTML, I don't really understand what you want to do
<script type="text/javascript">
function getPlatform() {
if (Platform.Android) {
document.getElementById('mobileLink').innerhtml = "androidlink";
}
else if (Platform.IOS) {
document.getElementById('mobileLink').innerhtml = "IOSLink";
}
else {
document.getElementById('mobileLink').innerhtml = "other";
}
}
</script>
the html,
</div id="mobilelink" class="btn" onload = "getPlatform()">
</div>
Right now I can only assume the results, that you need. This is one of the ways, inwhich you can return the result from a JS function to the html division. If the onload doesnt work, I'd suggest using an onclick = "getPlatform()" function since that is more aggressive in its notation.
this is incorrect approach.
I would recommend you put all scripts before closer </body> html-tag.
Then in your script you can write such code like:
const platform = getPlatform();
const mobilelinkEl = document.querySelector('#mobilelink');
mobilelinkEl.setAttribute("src", platform);
Make sure, that your script tag with src attribute set placed after script tag with getPlatform, and also make sure you have access to getPlatform function.
If you'll have additional question, write comments, I'll try to help you.
the image is:
<img id="lawnButton" src="images/mowing.png" width="15%" height="45%" alt="mowLawn" border="0" onclick="cutLawn()">
The code in the .js is:
document.getElementById("lawnButton").disabled = true;
Is there anything off the bat that I am doing incorrectly? The image still works as a button after the code is executed.
The image tag doesn't have that attribute. Try removing the event.
var lawn = document.getElementById("lawnButton");
lawn.onclick = function() {
//do code
lawn.onclick = null;
}
//.. code to re-enable the trigger
if (some condition) lawn.onclick = cutLawn;
Since images don't have a disabled attribute, you might want to set some flag to it to be used in cutLawn.
You could use a class. For example, to disabled the button:
button = document.getElementById("lawnButton")
button.className = button.className+ " disabled"
And then in cutLawn:
cutLawn = function(){
button = document.getElementById("lawnButton")
if button.className.match(/disabled/){
return false;
}
// ...
}
I've spent the last few hours trying to find the answer to this, but nothing seems to work...
I need to execute a piece of code when a div (or anything inside of it; including iframe content) is clicked. The following code should do it (when added into the div tag), but it doesn't seem to work.
onclick="if(typeof(_vis_opt_top_initialize) =='function'){ _vis_opt_goal_conversion(200); _vis_opt_pause(500);}"
The purpose is to execute a custom conversion goal:
<script type="text/javascript">
if(typeof(_vis_opt_top_initialize) == "function") {
_vis_opt_goal_conversion(200);
}
</script>
Any help will be greatly appreciated :)
I hate using inline js... hate it...
If you need to account for IE (<8), then you can't use addEventListener, so you can do something like this:
function bindListener(el,eventName,eventHandler) {
if (el.addEventListener) { // Anything but IE <8
el.addEventListener(eventName,eventHandler,false);
} else if (el.attachEvent) { // For IE <8
el.attachEvent('on'+eventName,eventHandler);
}
}
Then you can call it using something like this:
var ele = document.getElementById('idOfElement');
bindListener(ele, 'click', functionToCall);
Try using addEventListener. Link here. The Example on that page is exactly what you are asking for.
First give your div a unique ID
<div id="yourDivID"></div>
then set the onclick function in window.onload
var yourDiv = document.getElementById("yourDivID");
yourDiv.onclick = function() {
if(typeof(_vis_opt_top_initialize) == "function") {
_vis_opt_goal_conversion(200);
}
}
}
I write simple example for you:(j Query answer)
Html Code
<div class="test">Click</div>
JavaScript Code
$('div.test').click(function(){
alert("some");
});
Demo
Edited
JavaScript example
<html >
<script type="text/javascript">
function AttachAllDivEvents()
{
var divCollection = document.getElementsByTagName("div");
for (var i=0; i<divCollection.length; i++)
{
AttachDivClickEvent(divCollection[i]);
}
}
function AttachDivClickEvent(divObj)
{
divObj.onclick = function()
{
document.getElementById("count").innerHTML = parseInt(document.getElementById("count").innerHTML) + 1;
};
}
window.onload = AttachAllDivEvents;
</script>
<body>
<div>click</div>
<p id="count" style="font:bold 20px Times;color:red;text-indent:20px">1</p>
</body>
</html>
I'm desperate having spent well over an hour trying to troubleshoot this. I am trying to access a node in the DOM which is created from an ASP.NET control. I'm using exactly the same id and I can see that they match up when looking at the HTML source code after the page has rendered. Here's my [MODIFIED according to suggestions, but still not working] code:
ASP.NET Header
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script type="text/javascript">
$(document).ready(
var el = document.getElementById('<%= txtBox.ClientID %>');
el.onchange = alert('test!!');
)
</script>
</asp:Content>
ASP.NET Body
<asp:TextBox ID="txtBox" runat="server"></asp:TextBox>
Resulting Javascript & HTML from above
<script type="text/javascript">
$(document).ready(
var el = document.getElementById('MainContent_txtBox');
el.onchange = alert('test!!');
)
</script>
...
<textarea name="ctl00$MainContent$txtBox" id="MainContent_txtBox"></textarea>
I can only assume that the script is loading before the control id has been resolved, yet when I look at the timeline with Chrome's "Inspect Element" feature, it appears that is not the case. When I created a regular textarea box to test and implement the identical code (different id of course), the alert box fires.
What on earth am I missing here? This is driving me crazy >.<
EDIT: Wierd code that works, but only on the initial page load; firing onload rather than onchange. Even jQuery says that .ready doesn't work properly apparently. Ugh!!
$(document).ready(function() {
document.getElementById('<%= txtBox.ClientID %>').onchange = alert('WORKING!');
})
Assuming the rendered markup does appear in that order, the problem is that the element doesn't yet exist at the time your JavaScript is attempting to locate it.
Either move that JS below the element (preferably right at the end of the body) or wrap it in something like jQuery's document ready event handler.
Update:
In response to your edits, you're almost there but (as others have mentioned) you need to assign a function to the onchange event, not the return result of alert(). Something like this:
$(document).ready(function() {
// Might as well use jQuery to attach the event since you're already using
// it for the document ready event.
$('#<%= txtBox.ClientID %>').change(function() {
alert('Working!');
});
});
By writing onchange = alert('Working');, you were asking JavaScript to assign the result of the alert() method to the onchange property. That's why it was executing it immediately on page load, but never actually in response to the onchange event (because you hadn't assigned that a function to run onchange).
Pick up jQuery.
Then you can
$(function()
{
var el = document.getElementById('<%= txtBox.ClientID %>');
el.onclick() { alert('test!!'); }
});
Other answers have pointed out the error (attempting to access DOM nodes before they are in the document), I'll just point out alternative solutions.
Simple method
Add the script element in the HTML below the closing tag of the element you wish to access. In its easiest form, put it just before the closing body tag. This strategy can also make the page appear faster as the browser doesn't pause loading HTML for script. Overall load time is the same however, scripts still have to be loaded an executed, it's just that this order makes it seem faseter to the user.
Use window.onload or <body onload="..." ...>
This method is supported by every browser, but it fires after all content is loaded so the page may appear inactive for a short time (or perhaps a long time if loading is dealyed). It is very robust though.
Use a DOM ready function
Others have suggested jQuery, but you may not want 4,000 lines and 90kb of code just for a DOM ready function. jQuery's is quite convoluted so hard to remove from the library. David Mark's MyLibrary however is very modular and quite easy to extract just the bits you want. The code quality is also excellent, at least the equal of any other library.
Here is an example of a DOM ready function extracted from MyLibrary:
var API = API || {};
(function(global) {
var doc = (typeof global.document == 'object')? global.document : null;
var attachDocumentReadyListener, bReady, documentReady,
documentReadyListener, readyListeners = [];
var canAddDocumentReadyListener, canAddWindowLoadListener,
canAttachWindowLoadListener;
if (doc) {
canAddDocumentReadyListener = !!doc.addEventListener;
canAddWindowLoadListener = !!global.addEventListener;
canAttachWindowLoadListener = !!global.attachEvent;
bReady = false;
documentReady = function() { return bReady; };
documentReadyListener = function(e) {
if (!bReady) {
bReady = true;
var i = readyListeners.length;
var m = i - 1;
// NOTE: e may be undefined (not always called by event handler)
while (i--) { readyListeners[m - i](e); }
}
};
attachDocumentReadyListener = function(fn, docNode) {
docNode = docNode || global.document;
if (docNode == global.document) {
if (!readyListeners.length) {
if (canAddDocumentReadyListener) {
docNode.addEventListener('DOMContentLoaded',
documentReadyListener, false);
}
if (canAddWindowLoadListener) {
global.addEventListener('load', documentReadyListener, false);
}
else if (canAttachWindowLoadListener) {
global.attachEvent('onload', documentReadyListener);
} else {
var oldOnLoad = global.onload;
global.onload = function(e) {
if (oldOnLoad) {
oldOnLoad(e);
}
documentReadyListener();
};
}
}
readyListeners[readyListeners.length] = fn;
return true;
}
// NOTE: no special handling for other documents
// It might be useful to add additional queues for frames/objects
else {
if (canAddDocumentReadyListener) {
docNode.addEventListener('DOMContentLoaded', fn, false);
return true;
}
return false;
}
};
API.documentReady = documentReady;
API.documentReadyListener = documentReadyListener;
API.attachDocumentReadyListener = attachDocumentReadyListener;
}
}(this));
Using it for your case:
function someFn() {
var el = document.getElementById('MainContent_txtBox');
el.onclick = function() { alert('test!!');
}
API.attachDocumentReadyListener(someFn);
or an anonymous function can be supplied:
API.attachDocumentReadyListener(function(){
var el = document.getElementById('MainContent_txtBox');
el.onclick = function() { alert('test!!');
};
Very simple DOM ready functions can be done in 10 lines of code if you just want one for a specific case, but of course they are less robust and not as reusable.