Not working handler on "onchange" event - javascript

I'm trying to make some changes in DOM after an image is selected with an "input file" HTML5 element. So, I added a handler to the "onchange" event, but it is not working!
<span class="btn-file" >
Load and show alert
<input type="file" onchange="performSomeActions()"/>
</span>
And supose this is the function:
function performSomeActions(){
alert("lalala");
}
The error I get when I execute the code and after choosing a file is:
Uncaught ReferenceError: performSomeActions is not defined
I thought maybe I was wrong with the event name, but if you replace the input definition with the following line, it is working!
<input type="file" onchange="alert('alo');"/>
THE FIDDLE: http://jsfiddle.net/pvhaggrv/5/
Thanks in advance!

JSFiddle doesn't like calls to javascript embedded in your html. In the interest of keeping your code clean event handlers are assigned via javascript instead.
Change your html to:
<input type="file" id='fileInput'/>
and then in your JS
document.getElementById('fileInput').onchange = function() {
performSomeActions();
}
working fiddle: http://jsfiddle.net/bmartinelle/rhbphvhu/

just put javascript function in body tag just before ending of body tag like this
<span class="btn-file" >
Load and show alert
<input type="file" id="file" onchange="performSomeActions();"/>
</span>
<br/>
<img id="img"> </img>
<script>
var performSomeActions=function(){
alert("yyy");
}
</script>
see fiddle

Your fiddle doesn't work because fiddle executes all your javascript in the a anonymous function:
//<![CDATA[
window.onload=function(){
function performSomeActions(){
alert("yyy");
}
}//]]>
So your function isn't in the global scope and your HTML can't see it.
To your code works you need to include your function directly at the HEAD, you can do this in fiddle changing the checkbox at the left side: http://jsfiddle.net/pvhaggrv/12/
HOWEVER, you should not add event listeners this way, you should use addEventListener like kougiland said in his answer.

DEMO
HTML:
<span class="btn-file" >
Load and show alert
<input type="file" id="input">
</span>
<br/>
<img id="img"> </img>
SCRIPT:
function handleFiles() {
alert("lol");
var fileList = this.files; /* now you can work with the file list */
}
var inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
SOURCE:
Dynamically adding a change listener

Related

when jquery .html() is used to set inner HTML, .click() event on form button no longer works

I have a html form which contains a button. This button has a .click() event attached within a js file. This was working fine, until I used jquery .html() to substitute my main page content with the form content. The form shows on the page but clicking the button no longer triggers the event. I am wondering why this is? Code below...
html:
<body>
<div id="mainContent">
<!-- Visible page content will show here -->
</div>
<div id="otherScreens">
<form id="loginForm">
<label for="email">Email</label>
<input type="text" id="email" spellcheck="false">
<label for="password">Password</label>
<input type="password" id="password">
<button type="submit" id="signInBtn">Sign In</button>
<ul id="signInMessages"></ul>
</form>
</div>
css:
#otherScreens {
display: none;
}
js:
const mainContentArea = $(document).find('#mainContent');
let onPageContent = $(document).find('#loginForm').html();
$(document).ready(function () {
mainContentArea.html(onPageContent);
});
$('#signInBtn').click(function (event) {
event.preventDefault();
console.log("Hello world!");
}
I tested changing the .click() event to target #mainContent and it triggered upon clicking anywhere within the div on the webpage, as expected. So I'm not quite sure what's happening with the form button?
(does not seem to relate to suggested duplicate Q)
Just put your click function in document.ready(function()
Please check below full jQuery code and replace it with your current code:
const mainContentArea = $(document).find('#mainContent');
let onPageContent = $(document).find('#loginForm').html();
$(document).ready(function () {
mainContentArea.html(onPageContent);
$('#signInBtn').click(function (event) {
event.preventDefault();
console.log("Hello world!");
});
});
Thanks.
This is quite logical (and can be explained). You create an object, wire events to that object - then replace that object with a similar object and you expect the events to magically be wired.. That doesn't happen.
Each time you dynamically add (delete, replace, whatever) elements with events bound to that element, you need the DOM to be aware of that event. Even so, you could even end-up having more than one event wired to the same element.
So let's say (as an example).
function replaceElement(htmlContent) {
$('.mybutton').off('click'); // drop the event handler
$('#mainContent').html(htmlContent); // replace content
// add event handler
$('.mybutton').click(function() {
console.log('yup, working again');
});
}

Why won't JavaScript run?

I was making an HTML code editor, I tested all of the HTML tags I know and they all work, except for script tags.
When I type <script>something</script> into the text area and click a button, the script doesn't execute.
Please help! Here is the code:
<span id="finishedProduct">
<p>When you enter code, your finished product will be here! Don't worry, if you make a mistake you can fix it later!</p>
</span>
<form name="userCode">
<textarea name="userCode" cols="90" rows="20" placeholder="Type your code here"></textarea></br>
<button type="button">Run Code!</button>
</form>
<script>
function makeCode() {
var userCode=document.forms["userCode"]["userCode"].value;
document.getElementById('finishedProduct').innerHTML = userCode;
}
</script>
Here is the working code:
<span id="finishedProduct">When you enter code, your finished product will be here! Don't worry, if you make a mistake you can fix it later!
</span>
<form name="userCode">
<textarea name="userCode" cols="90" rows="20" placeholder="Type your code here"></textarea>
<br/>
<button type="button" onClick="makeCode()">Run Code!</button>
</form>
<script type="text/javascript">
function makeCode() {
var userCode=document.forms["userCode"]["userCode"].value;
document.getElementById('finishedProduct').innerHTML = userCode;
}
</script>
Here's a link to the JSFiddle: http://jsfiddle.net/Q2qLF/. I've removed some broken HTML, such as; a button shouldn't be contained in a anchor tag, I've added a 'onclick' in your button that will call the 'makeCode()' function and I've added the 'type="text/javascript"' into your script tag as this maximises compatibility.
Please let me know if you need any more help
I've updated my JSFiddle http://jsfiddle.net/Xanco/Q2qLF/1/
Now there are 2 textareas, one for the HTML and one for the Javascript. i've also created a new function called 'makejs', this takes the value of the Javascript textarea and runs it through a 'eval' - this executes the Javascript passed to it.
I've put the answer in a Fiddle here: http://jsfiddle.net/joshnicholson/P8eh9/
I'm not sure why you're wrapping the button element inside an anchor, but I would do it a slightly different way.
Here is the revised javascript:
var myButton = document.getElementById("btnRunCode");
myButton.addEventListener("click", makeCode);
function makeCode() {
var userCode=document.forms["userCode"]["userCode"].value;
document.getElementById('finishedProduct').innerHTML = userCode;
}
I added an id of "btnRunCode" to your button element, just to make things easier for me. See the Fiddle.

How do I get an img click to execute js using jsfiddle

I need an image click to execute a js function. I have it working in my project, but I have other code to develop so I'm trying to use jsfiddle. But I can't get this simple code to work in jsfiddle. when I use jsfiddle and I click the image, nothing happens.
What am I missing in my efforts to use jsfiddle?
My HTML
<div>
<img id="additem" Title="Add Item" onclick="myfunc()" OnMouseOver="this.style.cursor='pointer';" OnMouseOut="this.style.cursor='default';" src="~/images/Sign_Add_Icon_32.png" />
</div>
My JS
function myfunc() {
alert("hello");
}
Remove onload in framework and extensions, set it to in head or in body.
DEMO
This works! But what was the problem?
You can't wait for the document to load in that case, because myfunc isn't defined before the Javascript is executed after the HTML loads.

how to clear an input field onclick of an image?

I'm creating a form inside a foreach loop. What actually I want is that... how can I clear the value of a particular input field on click of an image.
Following is the code which is inside loop. It has many more form fields. But I want to clear a particular input field, because I'm fetching the data from database, making changes and then saving it again.
<a onclick="clearField("<?php echo "field_id".$language["language_id"]; ?>")"
href="javascript:noAction();"><img src="view/image/delete.png">
</a>
<input type="text"
id="<?php echo 'field_id'.$language['language_id']; ?>"
name="file_name[<?php echo $language['language_id']; ?>]"
value="<?php echo isset($document_description[$language['language_id']]) ? $document_description[$language['language_id']]['file'] : ''; ?>"
readonly="readonly"/>
Following is the javascript which is used for above function--
<script>
function clearField(input,val) {
if(input.value == val)
input.value="";
};
</script>
EDITED :- there is one more problem with the following statement --
all quotes which are used inside this statement are not proper. i mean to say that the code do not gets parsed due to some missing or some additional quotes. So please tell me how to correct this.
<a onclick="clearField("<?php echo "field_id".$language["language_id"]; ?>")"
href="javascript:noAction();"><img src="view/image/delete.png">
</a>
You can do this very easily in javascript
HTML code
<img src="http://www.mricons.com/store/png/45804_11386_128_button_cancel_icon.png" height="35" width="35" onclick ="change()" />
<input type="text" name="name" value="name" id="ghd" />
JAVASCRIPT code
function change(){
var ab = document.getElementById('ghd').value;
document.getElementById('ghd').value = "";
$('#ghd').val('dsds');
}
Following is the link to jsfiddle also---
http://jsfiddle.net/nnRV5/
Hope it helps you!!
Try Following
<img src="view/image/delete.png" onclick="clearInput();">
<script>
function clearInput(){
document.getElementById('input_id').value = '';
}
</script>
Rather than using an anchor you could just listen for the click event on the image itself, like this:
<img id="clickable_image" src="delete.png" alt="Clear input text" />
<input id="the_input_to_clear" ... other attribs here ... />
<script>
(function(){
var image = document.getElementById('clickable_image'),
inputField = document.getElementById('the_input_to_clear'),
clickHandler = function() {
inputField.value = '';
};
if (image.addEventListener) {
// this attaches the event for most browsers
image.addEventListener("click", clickHandler, false);
} else {
// this attaches the event for IE...
image.attachEvent("onclick", clickHandler);
}
})();
</script>
From an accessibility perspective a clickable image that controls a form field is not good practice, but at least you're not having to worry about having an anchor that goes nowhere. If you want to improve the accessibility you might like to use a button element, and style it with a background image something like: http://jsfiddle.net/3vPpt/3/
The Javascript in my example dynamically attaches the click event to the image rather than specifying the function in the element's onclick attribute. This is to separate presentation from behaviour logic and is considered best practice.
The funky (function(){})(); notation executes the script immediately, but does not leak the variables created (image, inputField, clickHandler) into the global scope. This is also a best practice thing, and will prevent your script interfering with other code on the page.
Try this:
<script>
function clearField(input,val) {
if(document.getElementById(input).value == val){
document.getElementById(input).value = '';//This will clear the field
}
</script>

Can't change onclick dynamically through javascript: bookmarklet

I've tried to change the onclick function through a bookmarklet in the url using this code:
javascript: document.getElementById('Button1').onclick = function(){alert('foo')};void(0);
I can change the value of the button but just not the onclick function. Is it even possible?
Thanks ^^
Some notes: I've also tried putting the code in a .js file and creating an external .js file using createElementId but it still does not seem to work :/
You were missing the trailing semi-colon to terminate the alert call. It's easier to spot once you indent it:
document.getElementById('Button1').onclick = function() {
alert('foo');
};
This code works. So the only option is that Button1 is not an ID of an element on that page.
For example:
<div id="Button1">Button</div>
If an element on the page looks like that, you will get your alert ('foo');
Your code seems to work...
Try to insert this code into the w3schools jseditor http://www.w3schools.com/js/tryit.asp?filename=tryjs_events
<html>
<body>
<button type="button" id="Button1" onclick="alert('Some action');">Action!!</button>
<button type="button" id="Button2" onclick="document.getElementById('Button1').onclick = function(){alert('another action')};">Change onclick</button>
</body>
</html>

Categories