Pass uploaded file as a parameter to javascript method - javascript

I am passing the uploaded file as a parameter in the JavaScript method. Then Firebug is throwing error like SyntaxError: illegal character.
<input type="file" id="fileUpload" name="employerLogoUpload" />
<a id="_fileUploadLink" href="#" onClick="javascript:ajaxFileUpload(" +document.getElementById('fileUpload').value+ ");">Upload</a>
Please help me out.

If you want to use inline event attributes change your onclick handler to look like this:
onClick="ajaxFileUpload(document.getElementById('fileUpload').value);"
That will, on click, call the ajaxFileUpload() function and pass it the current value of the fileUpload element.
The way you had it your onclick looked like this:
onClick="javascript:ajaxFileUpload("
...and the +document.getElementById('fileUpload').value+ ");" after that was not part of the onclick - the attribute ends with its closing quotation mark. (Also you don't need the javascript: part inside any inline event handler.)
But since you've tagged the question with jQuery you could lose the inline code and put the following in a script block after the elements and/or in a document ready handler:
$("#_fileUploadLink").click(function(e) {
ajaxFileUpload($("#fileUpload").val());
e.preventDefault();
});
The .preventDefault() is there to stop the browser moving to the top of the document when you click the link.

function ajaxFileUpload(val){
...
}
$(document).ready(function(){
$('a#_fileUploadLink').on('click', function(){
var val = $('#fileUpload').val();
ajaxFileUpload(val);
});
});

Related

How to check for multiple ID attributes if they are being clicked with JavaScript?

I am trying to check for activity on any of some specific ID attributes on my webpage with JavaScript, and if they are activated, I want to execute some code. The code is working for a single attribute with document.querySelector but not for document.querySelectorAll.
I have tried the solutions posted here but without success, as I run into the following error:
Uncaught ReferenceError: Invalid left-hand side in assignment
My code is simple:
document.addEventListener('DOMContentLoaded', function(){
Array.from(document.querySelectorAll("#id_types, #id_cons_1")).forEach(button=>button.click()) = function() {
document.querySelector("#id_new_name").value= some_value_to_be_assigned
}})
What am I doing wrong?
There's no need for the DOMContentLoaded event handler, just put a script with the following at the end of the body (just before the closing body tag).
There is also no need for Array.from since forEach is supported on the node list returned from querySelectorAll().
Then, you need to set up a click event for each button as shown below (button.click() = function...., doesn't set up an event handler, it invokes a click event).
document.querySelectorAll("#id_types, #id_cons_1").forEach(function(button) {
button.addEventListener("click", function(event){
document.querySelector("#id_new_name").textContent = "some_value_to_be_assigned";
});
});
<button type="button" id="id_types">button</button>
<button type="button" id="id_cons_1">button</button>
<div id="id_new_name">some value</div>

Replace onclick function of an object using Javascript

How do I replace the destination URL on a button when using onclick?
<div id="my_button" onclick="window.location.replace('/destination1')">Button<div>
So it would look like this
<div id="my_button" onclick="window.location.replace('/destination2')">Button<div>
The following Javascript code doesn't work though. Why?
<script>
document.getElementById("my_button").onclick="window.location.replace('/destination2')"
<script>
onclick that you have used in tag - is html event attribute, but onclick in tag, that you also tring to change - is div object property.
Both are like "onclick", but it's not the same.
So, if you want to make thing work, do this:
document.getElementById("my_button").onclick = () => window.location.replace('/destination2');
onclick div property need function(callback) not a string
A simple way to do it would be by adding a listener and preventing the default behavior of the event
document
.getElementById('my_button')
.addEventListener('click', function (event) {
event.preventDefault();
window.location.replace('/destination2');
});
working example
element.onclick requires a function to be assigned and differs from the attribute <node onclick=""> where the content will be wrapped up in a function automatically.
If you want to change the attribute, make use of element.setAttribute("onclick", "...");
element.setAttribute("onclick", "window.location.replace('/destination2');");
Behaves similar to:
element.onclick = function() { window.location.replace('/destination2'); };
Another solution would be using the data-attributes which can be accessed by element.dataset.name.
Example:
<div id="my_button" data-path="/destination2" onclick="window.location.replace(this.dataset.path);">Button</div>
And to change it:
my_button.dataset.path = "/otherPath";

How do I call this script?

I have a script for deleting a record without refreshing. I'm still new to javascript and trying to learn how to call out this script. Here's what I have.
My button:
<button id="<?php echo $rrr['id']; ?>" class="delbutton" onclick="">Delete</button>
My Javascript:
<script type="text/javascript" >
$(function() {
$(".delbutton").click(function() {
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
if (confirm("Sure you want to delete this note? This cannot be undone later.")) {
$.ajax({
type : "POST",
url : "delete-note.php", //URL to the delete php script
data : info,
success : function() {
}
});
$(this).parents(".record").animate("fast").animate({
opacity : "hide"
}, "slow");
}
return false;
});
});
I borrowed this code from someone else while doing research for deleting without reloading. Normally I'd see a function look something like this:
function myFunction()
Then I can call it using onclick like this:
onclick="myFunction()"
With the way this script is written, I'm not sure what "function" I'm supposed to be calling or if I need to add the name somewhere.
Any guidance or reading material would be helpful.
Thanks
You don't need to use an onclick here:
$(".delbutton") finds all the buttons with the CSS class delbutton.
.click(function() { ... }) says execute the given function when the button is clicked.
$(function() {
This means everything in there is being called when the document is ready.
As UncleDave already said, because of the .click your script should already be called onclick. It would be the same if you replace this line:
$(".delbutton").click(function() {
with this line:
function myOnClickFunction() {
and then call it onClick via onClick="myOnClickFunction()"
The click function binds the function as an event handler to the click event on all the elements matched by the selector passed to the jQuery function which is aliased to $.
(This replaces the onclick attribute)
To call the function, just click the matching element (any element that is a member of the delbutton class).
You could also trigger the event programatically with the trigger method:
$(".delbutton").trigger("click");
$(".delbutton").click(function() is listening to any click to trigger the action which is the code in your function.
You don't need onclick="" for the button tag.
How do I call this script?
You already do, it is self executing.
You do not need to register a sepperate click event to the button. The script is doing this already itself.
$(".delbutton").click(function() {
// code being executed when button is pressed
}
If you want to do it the way you are used to, just create your function in the tag like this:
<script>
function myFunction() {
// do something
}
</script>
then, your HTML element should look like this:
<button onclick="myFunction()" >

Replacing html page text by using JQuery

I have a simple javascript code which replaces the page content....by contents of another file(test2.html)
Code:
$(document).ready(function(){
$("[href='#']").click(function() {
function getcontent(url, id) {
$("#id").load("url");
}
});
});
Now am using
<div id = "content">
<p> REPLACE </p>
</div>
click here
So now on clicking click here REPLACE should be replaced by content of test2.html...but its not happening...
I have included the required jquery.js file in my script..
No, this won't work. getcontent is a function defined in a particular scope -- that of the click handler callback function. It is not accessible in the global scope -- the scope that the onClick method receives.
You should use a genuine click handler, perhaps setting data using data attributes:
$('[href="#"]').click(function() {
$('#' + $(this).data('id')).load($(this).data('url'));
});
Using the following HTML:
click here
You have a weird setup. The function getcontent is not defined in global scope, it cannot be found by the onclick event handler in the HTML. There are other issues as well.
I suggest something like:
click here
and
$(function(){
$("a[href^='#']").click(function(){
$(this.href).load(this.rel);
});
});
$('#' + id).load(url);
In your current method above, you are passing string literals, not the variables themselves.
You seem to be misunderstanding what certain parts of your code are doing. Also, I'd recommend giving your href a real id to make things easier. You don't need to use the jQuery 'click' method and ALSO assign an onclick handler inline in the HTML.
Try this instead:
<div id = "content">
<p> REPLACE </p>
</div>
<a id="clickThis" href="#">click here</a>
$(document).ready(function() {
$('#clickThis').click(function() {
$('#content').load('test2.html');
});
});
Your code with some comments:
$(document).ready(function(){
// this will assign a click handler, you don't need an 'onclick'
// attribute on the anchor tag also
$("[href='#']").click(function() {
// but what does your click handler do?
// It defines a function that is never called.
function getcontent(url, id) {
$("#id").load("url");
}
});
});

call javascript function on hyperlink click

I am dynamically creating a hyperlink in the c# code behind file of ASP.NET. I need to call a JavaScript function on client click. how do i accomplish this?
Neater still, instead of the typical href="#" or href="javascript:void" or href="whatever", I think this makes much more sense:
var el = document.getElementById('foo');
el.onclick = showFoo;
function showFoo() {
alert('I am foo!');
return false;
}
Show me some foo
If Javascript fails, there is some feedback. Furthermore, erratic behavior (page jumping in the case of href="#", visiting the same page in the case of href="") is eliminated.
The simplest answer of all is...
My link
Or to answer the question of calling a javascript function:
<script type="text/javascript">
function myFunction(myMessage) {
alert(myMessage);
}
</script>
My link
With the onclick parameter...
<a href='http://www.google.com' onclick='myJavaScriptFunction();'>mylink</a>
The JQuery answer. Since JavaScript was invented in order to develop JQuery, I am giving you an example in JQuery doing this:
<div class="menu">
Example
Foobar.com
</div>
<script>
jQuery( 'div.menu a' )
.click(function() {
do_the_click( this.href );
return false;
});
// play the funky music white boy
function do_the_click( url )
{
alert( url );
}
</script>
I prefer using the onclick method rather than the href for javascript hyperlinks. And always use alerts to determine what value do you have.
<a href='#' onclick='jsFunction();alert('it works!');'>Link</a>
It could be also used on input tags eg.
<input type='button' value='Submit' onclick='jsFunction();alert('it works!');'>
Ideally I would avoid generating links in you code behind altogether as your code will need recompiling every time you want to make a change to the 'markup' of each of those links. If you have to do it I would not embed your javascript 'calls' inside your HTML, it's a bad practice altogether, your markup should describe your document not what it does, thats the job of your javascript.
Use an approach where you have a specific id for each element (or class if its common functionality) and then use Progressive Enhancement to add the event handler(s), something like:
[c# example only probably not the way you're writing out your js]
Response.Write("My Link");
[Javascript]
document.getElementById('uxAncMyLink').onclick = function(e){
// do some stuff here
return false;
}
That way your code won't break for users with JS disabled and it will have a clear seperation of concerns.
Hope that is of use.
Use the onclick HTML attribute.
The onclick event handler captures a
click event from the users’ mouse
button on the element to which the
onclick attribute is applied. This
action usually results in a call to a
script method such as a JavaScript
function [...]
I would generally recommend using element.attachEvent (IE) or element.addEventListener (other browsers) over setting the onclick event directly as the latter will replace any existing event handlers for that element.
attachEvent / addEventListening allow multiple event handlers to be created.
If you do not wait for the page to be loaded you will not be able to select the element by id. This solution should work for anyone having trouble getting the code to execute
<script type="text/javascript">
window.onload = function() {
document.getElementById("delete").onclick = function() {myFunction()};
function myFunction() {
//your code goes here
alert('Alert message here');
}
};
</script>
<a href='#' id='delete'>Delete Document</a>

Categories