simple jQuery function working in codepen but not on server: - javascript

So I have this little function that takes the value or text input and gives it to an iframe's src attribute. It seems to work great on my codepen, but when I export it (with all of the files etc(codepen style) (jquery and everything is loaded properly) and put it on a server, it doesn't work. Does anyone have any ideas why this might be? or how I could be going about this in a better way? --
this is what shows in the url bar on submit with the live version in chrome if that means anything to you.
http://site.com/?url-input=http%3A%2F%2Fmy-site.com
A working codepen
HTML
<form class="visitor-input-form">
<label for="url-input" >
Type in your current URL and see what your website looks like to almost everyone else.
</label>
<input type="text" name="url-input"
class="currentUrl"
placeholder="http://nouveau.io" id="txtSRC" />
<input type="submit" class="submit-button" value="View site" />
</form>
jQuery
$(".submit-button").click( function() {
$(".i-frame").attr("src", $("#txtSRC").val());
});
Thanks for your time.
Update:
So to further test I'm using this. Page loads, tells me the dom is ready. So everything is loading in order. Then I input the url, it tells me the button was pushed, THEN - it tells me the dom is ready AGAIN. So, when I'm pressing enter, it is reloading the page. I do not want the page to reload. I just want the iframe to get switched out. So that is at least a little window to what might be the problem.
jQuery( document ).ready(function($) {
alert("dom is ready");
$(".submit-button").click( function() {
alert("button was pushed");
$(".i-frame").attr("src", $("#txtSRC").val());
});
}); // end dom ready

Make sure you either execute your jQuery at the end of the document, after the elements already exist in the page, or in the head within a document ready call:
$(document).ready(function () {
$(".submit-button").click(function () {
$(".i-frame").attr("src", $("#txtSRC").val());
});
});
Codepen does the former.

We found this:
Prevent reloading page after submiting form. ( no ajax )
<form onsubmit="return false">
Does the trick, but I have the feeling there is a better answer. I feel like on submit, it should run the scrip maybe instead of on click. I'm going to look into that. <form onsubmit="script"> etc... I'll wait a while before I mark this as answered in the hopes I get something more appropriate, but it is currently working as intended.

The page is reloading, try updating your jQuery to this:
jQuery( document ).ready(function($) {
$(".submit-button").click( function(e) {
e.preventDefault();
$(".i-frame").attr("src", $("#txtSRC").val());
});
});

Related

textarea onchange not firing within php script

I have a php page with a form that has a textarea input object. The onchange isn't firing and I can't work out why - it should be so simple! I read through many similar questions online, and I tried adding onkey, onblur, and addEventListener (as per the example below), none of which worked.
But then I discovered that my code works fine in a html page but not in a php page. Is there something about php that makes this event fire differently?
Thanks!
<textarea name="Address" ID="Address" onChange="alert('You just changed the textarea.')">xxx</textarea>
</form>
<script type="text/javascript">
Address.addEventListener('input', () => {
console.log("You just changed the textarea.");
}, false);
</script>
Your code have error "Address" on Address.addEventListener(...), because Address is not an object. You need to replace the line:
Address.addEventListener('input', () => {
to
document.getElementById('Address').addEventListener('input', () => {
Change the onchange to onkeyup and will work as you expected:
<textarea name="Address" ID="Address" onkeyup="alert('You just changed the textarea.')">xxx</textarea>
So, I figured out what was causing the issue. There was a plug-in using the textarea object elsewhere in the app that was effecting any change events.
Many thanks to everyone who took the time to reply. Much appreciated!

check if dynamically inserted input field exists

I have a script that adds a button that will open up a window that allows us to design t shirts. All i have top do is include their script and the button gets automatically added.
Below is the code which is dynamically added to the page.
<input id="design_edit_btn" class=" btn btn-success btn-block" value="Edit the design" type="button">
What i need to do is that, if that button is available then show a message saying its customizable or else display cannot be customized.
I tried the below code
if($("#design_edit_btn").length) {
alert("exists");
}
I did a bit of research but couldn't find a way to achieve this. Can someone please let me know how this can be done?
Thanks
You probably need to wait until the script has been loaded and executed.
Try waiting when the document is finished and do something like this:
jQuery(($) => {
if($("#design_edit_btn").length) {
alert("exists");
}
} );
jQuery triggers a given callback as soon as the document is ready. If that doesn't work either you could try adding a setTimeout as well.
Since the button you look for is create by an external script, that script is likely not finished by the time the DOM is ready, hence you won't find it, not even at $(document).ready()
What you can try is to use the script tag's onload, and when it fires, check for the button, like I do here, fire a console.log when jQuery have loaded.
Note, the order of the script is important
Stack snippet
<script>
function checkForjQuery() {
console.log('jQuery loaded');
}
function checkForButton() {
if ($("#design_edit_btn").length) {
alert("exists");
}
}
</script>
<script onload="checkForjQuery()" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- temp. commented out
<script onload="checkForButton()" src="your_script_path"></script>
-->
have you tried something like this:
if(document.getElementById('design_edit_btn') != null)
{
alert("exists");
}
This should do the trick
if ($("#design_edit_btn").length > 0) {
alert("exists");
}

Javascript event handler (mouseover) not firing

I have a homepage that dynamically writes javascript in order to handle the mouseover of potential user choices. However, the .bind("mouseover",function()) does not seem to be working.
The PHP produces a script like this:
<script type="text/javascript">
function setPreview(art, title, rt, excerpt) {
$("#boxPreview").attr("src", art);
$("#selectedTitle").text(title);
$("#runningTime").text(rt);
$("#excerpt").text(excerpt);
}
$(document).ready(function() {
$("#tb0").bind("mouseover",setPreview(url,title,running time,excerpt));
$("#tb1").bind("mouseover",setPreview(url,title,running time,excerpt));
$("#tb2").bind("mouseover",setPreview(url,title,running time,excerpt));
$("#tb3").bind("mouseover",setPreview(url,title,running time,excerpt));
</script>
However, it seems that the mouseover event never fires. Instead, it seems that when the page is fully loaded, setPreview is run for the very last element (#tb3).
I have no idea what I'm doing wrong. If you would like to see the page in action for yourself, you can view it here.
You may try writing the same code like this
$("#tb0").bind("mouseover" , function(){
setPreview(url,title,running time,excerpt);
});
This may solve your issue. Because i've got same issue before but it was fixed writing this way.

Same JQuery click function for numerous links

I have a page that has multiple links with various attributes (these attributes will be pulled in from a database):
index.php
<html>
<head>
<script type='text/javascript' src='header.js'></script>
</head>
<body>
My_Link_1
My_Link_2
<div id='my_container'> </div>
</body>
</html>
My header.js file has:
$(document).ready(function(){
$('.link_click').click(function(){
$("#my_container").load("classes/class.project.php", {proj: $(this).attr('id')} );
return false;
});
});
class.project.php is pretty simple:
<?php
echo "<div id='project_container'>project = ".$_POST['proj']." : end project</div>";
?>
This loads and passes the ID variable (which actually comes from a database) to class.project.php. It works fine for the first link click (either link will work). Once one link is clicked no other links with this div class will work. It feels like javascript loads the class.porject.php and it will not refresh it into that #my_container div.
I tried running this as suggested by peterpeiguo on the JQuery Fourm, with the alert box for testing wrapped inside .each:
Copy code
$(document).ready(function() {
$('.link_click').each(function() {
$(this).click(function() {
alert($(this).html());
});
});
});
This seems to work fine for the alert box. But when applying it to .load() it does not reload the page with the new passed variable. As a matter of fact, it doesn't even reload the current page. The link performs no function at that point.
The example site can be viewed here: http://nobletech.net/gl/
I looked at the link you posted, and the problem is that when you're doing load you're replacing the elements on the page with new ones, thus the event handlers don't work anymore.
What you really want to do is target the load. Something like:
$("#project_container").load("classes/class.project.php #project_container", {proj: $(this).attr('projid')} );
This only loads stuff into the proper container, leaving the links and other stuff intact.
Ideally, the php script should only return the stuff you need, not the whole page's markup.
BTW- Caching shouldn't be an issue in this case, since .load uses POST if parameters are passed. You only have to worry about ajax caching with GETs
Sounds like the request is getting cached to me.
Try this:
$.ajaxSetup ({
// Disable caching of AJAX responses */
cache: false
});
Sorry but this might be completely wrong but after examining your XHR response I saw that you are sending back html that replaces your existing elements.
So a quick fix would be to also send the following in your XHR response (your php script should output this also):
<script>
$('.link_click').each(function() {
$(this).click(function() {
alert($(this).html());
});
</script>

Javascript: var is null

I have this piece of Javascript and it just won't work. I allready checked JSlint but that said everything works. Still doesn't work. The javascript is located not in the HTML but is linked in the <head>
note: I am working with a local server, so pageload in instant.
function changeVisibility() {
var a = document.getElementById('invisible');
a.style.display = 'block';
}
var changed = document.getElementById('click1');
changed.onchange = changeVisibility;
This here is the corresponding HTML
<input type="file" name="click[]" size="35" id="click1" />
<div id="invisible" style="display: none;">
Attach another File
</div>
So what happens is I click on the input, select a file and approve. Then then onchange event triggers and the style of my invisible div is set to block.
Problem is, I keep getting this error:
"changed is null:
changed.onchange = changeVisibility;"
i don't get it, I seriously don't get what I'm overlooking here.
EDIT: question answered, thank you Mercutio for your help and everyone else too of course.
Final code:
function loadEvents() {
var changed = document.getElementById('click1');
var a = document.getElementById('invisible');
document.getElementById('addField').onclick = addFileInput;
changed.onchange = function() {
a.style.display = 'block';
}
}
if (document.getElementById) window.onload = loadEvents;
This here is the corresponding HTML:
<input type="file" name="click[]" size="35" id="click1" />
<div id="invisible" style="display: none;">
Attach another File
</div>
Also, thanks for the link to JSbin, didn't know about that, looks nifty.
This sounds like the DOM object doesn't exist at the time of referencing it. Perhaps change your code to execute once the document has fully loaded (or place the javascript at the bottom of your page)
note: I am working with a local server, so pageload in instant.
that's not the issue - the constituent parts of a document are loaded in order. It doesn't matter how fast they are loaded, some things happen before others :D
The onlything I'd like to do now is remove the Javascript link from the ...
Place an id on there, and inside your function do this:
document.getElementById('addField').onclick = addFileInput;
Or, as you already have the div as the variable 'a':
a.firstChild.onclick = addFileInput;
But this obviously leaves you with an invalid anchor tag. Best practice suggests that you should provide a way to do it without javascript, and override that functionality with your javascript-method if available.
mercutio is correct. If that code is executing in the HEAD, the call to "document.getElementById('click1')" will always return null since the body hasn't been parsed yet. Perhaps you should put that logic inside of an onload event handler.
I think its because you are trying to modify a file element.
Browsers don't usually let you do that. If you want to show or hide them, place them inside of a div and show or hide that.
Right, I've modified things based on your collective sudgestions and it works now. Onlything bothering me is the direct reference to Javascript inside the anchor
You need to wrap your code in a window.onload event handler, a domReady event handler (available in most modern js frameworks and libraries) or place at the bottom of the page.
Placing at the bottom of the page works fine, as you can see here.
Decoupling event responder from your markup is covered under the topic of "Unobtrusive JavaScript" and can be handled in a variety of ways. In general, you want to declare event responders in a window.onload or document.ready event.

Categories

Resources