i'm trying to send a variable through to a function when clicking an image, but can't get any of it to work. not sure where I am going wrong.?
jsfiddle http://jsfiddle.net/cibravo/rNGMR/
HTML
<input type="submit" value="send" onclick="alert('works')" />
<br/><br/>
<img onclick="alert('works')" src="http://firmakurser.studieskolen.dk/images/web/Facebook-logo-small.png" />
<br/><br/>
<!-- this doesn't work -->
<input type="button" value="send" onclick="myFunction()" />
<br/><br/>
<!-- this doesn't work -->
<img onclick="showhide('works')" src="http://firmakurser.studieskolen.dk/images/web/Facebook-logo-small.png" />
JS
function myFunction(){
alert("works");
}
function showhide(field){
alert(field);
}
Both of your examples that you say don't work will work provided the functions they call are globals, not contained within any scoping function.
The reason it's not working in your fiddle is that jsFiddle's (surprising) default is to wrap your JavaScript code in a window load event handler, like this:
window.onload = function() {
// your code here
};
...so your functions aren't globals. (I say it's surprising because waiting until the window load event runs, which is very late in the page load process, is not best practice.)
Here's an updated fiddle: http://jsfiddle.net/rNGMR/4/ As Juhana points out, you change tehs second drop-down box on the upper left to one of the "no wrap" options (I went with "no wrap - body").
For clarity, here's a complete all-in-one example: Live Copy | Live Source
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Global Functions</title>
</head>
<body>
<input type="submit" value="send" onclick="alert('works')" />
<br/><br/>
<img onclick="alert('works')" src="http://firmakurser.studieskolen.dk/images/web/Facebook-logo-small.png" />
<br/><br/>
<!-- this doesn't work -->
<input type="button" value="send" onclick="myFunction()" />
<br/><br/>
<!-- this doesn't work -->
<img onclick="showhide('works')" src="http://firmakurser.studieskolen.dk/images/web/Facebook-logo-small.png" />
<script>
// Note that these are globals
function myFunction(){
alert("works");
}
function showhide(field){
alert(field);
}
</script>
</body>
</html>
More or less an alternity to your current approach
(which was solved while I wrote this.)
Please try avoid using the 'onclick' event when you work on bigger projects. It's usually better to keep HTML, CSS und JavaScript modularly separated.
When I encounter problems like this I usually use anonymous functions, who then call the
function with the right parameters.
This technique also solves the problem that everything needs to be global -- which is discouraged too.
It suited me well trough the last 3 years and around 15k lines of JavaScript code.
Here is an example:
http://jsfiddle.net/8jSaT/1/
<!-- HTML -->
<img id="btnSomething" src="http://firmakurser.studieskolen.dk/...">
// (plain) Javascript
var btn = document.getElementById('btnSomething');
// this is where the anonymous function comes in:
// Its only purpose is to redirect the onClick-Event
// and serve proper parameters
var btn.onclick = function() { showhide('works'); };
// Your code
////////////////
function myFunction(){
alert("works");
}
function showhide(field){
alert(field);
}
Related
I am a cybersecurity student trying to understand some basic HTML injections. I have been working on this code for a few days and can't understand what I am doing wrong. The code that I have currently does allow for injection, for example if I put <h1>test</h1> into the textbox, it will display test as a header. But if I try <script>alert(1)</script> it won't actually run the script. I have tried setting the value of the text box to "" or with the thought that I could close out that line by inputting the following into the textbox: "><script>alert(1)</script>
I've also tried to cancel out the remainder of the code by adding a comment to the end like this: <script>alert(1)</script><!--
I've tried a number of combinations of each with no luck. Now I actually need to be able to inject a script since I'm playing around with CSP and how that affects injection of scripts into the webpage. I currently DO NOT have a csp specified that would restrict the JavaScript from running. Some other things I've tried include using different browsers, changing browser security, and ensuring that JavaScript is enabled in the browser. Any help would be greatly appreciated!!
<html>
<script language='JavaScript'>
function getwords(){
textbox = document.getElementById('words');
label = document.getElementById('label');
label.innerHTML = textbox.value;
}
</script>
<body>
<input type="text" id="words">
<input type="button" onclick="getwords()" id="Button" value="Enter" />
<label id="label">
</label>
</body>
</html>
That's because <script>s run at page load, and, when the label's content change, the scripts have ran already.
However, if you inject <script> tags to a different page (through the backend (XSS means Cross-Site Scripting)), it does work.
Alternatively, to make it work in a scenario, where the content injected after page load (like your case), you can use JS events (like onclick) to run your code:
<div onclick="alert(1)">Click me!</div>
Or, to execute it without user interaction, you could use an <iframe>'s onload event:
<iframe onload="alert(1)" style="display:none"></iframe>
to execute javascript from your form, you can try:
<iframe src=javascript:alert(1)>
or
<img src=x onerror=alert(1)>
Also worth noting:
script elements inserted using innerHTML do not execute when they
are inserted.
To manually execute JavaScript, you may do the following
without editing your HTML file, add this to the Input field on your Browser.
<iframe onload="alert(1)" style="display:none"></iframe>
More information on why this works here
More on how you can perform actions like this here: developer.mozilla.org
<html>
<script language='JavaScript'>
function getwords(){
textbox = document.getElementById('words');
label = document.getElementById('label');
label.innerHTML = textbox.value;
}
</script>
<body>
<input type="text" id="words">
<input type="button" onclick="getwords()" id="Button" value="Enter" />
<label id="label">
</label>
</body>
</html>
My button does not work for my website I am developing right now, I did the exact same thing for my other buttons. But just on that specific page my buttons won't work.
<head>
<link rel="stylesheet" href="bestelling.css" />
<link rel="shortcut icon" href="#">
</head>
<script>
function Aanvaarden()
{
window.location.assign=("Welcome.php")
}
function Annuleren()
{
window.location.assign=("Annuleren.php")
}
</script>
<br>
<input class="MyButton" type="button" value="Aanvaarden" onclick="Aanvaarden()" />
<input class="MyButton" type="button" value="Annuleren" onclick="Annuleren()" />
this is my code behind my buttons, what do I need to do?
window.location.assign is a function.
Assigning a string to it (with =) will just remove the function and replace it with a string.
It will have no visible effect unless some other code tries to call assign, at which point it will throw an error because it isn't a function.
To use it, you should call the function and pass an argument:
window.location.assign("Annuleren.php")
That said, a regular link instead of a button with some JavaScript would almost certainly be a better, easier, more accessible solution.
Remove the equal to sign after "assign". Your code should now work with the revision below.
function Aanvaarden()
{
window.location.assign("Welcome.php")
}
function Annuleren()
{
window.location.assign("Annuleren.php")
}
I'm trying to figure out why my javascript function isn't storing my JS variable.
Here's the issue. I trigger my storeMacAddress function with an onclick event, and the alert shows that the 'userMac' variable gets the form value properly. I need to be able to use this value later on, so I need the value stored in a variable that my other functions can user.
However, when I call my testVariable function, the console says that the 'usermac' variable is not defined.
Here's the javascript:
function storeMacAddress()
{
var userMac = document.getElementById("MacAddress").value
alert("testing: " + userMac);
return userMac;
}
function testVariable(MacAddress)
{
alert(MacAddress);
}
Here's the html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src='./index.js'>
</script>
</head>
<body>
<h1></h1>
<p></p>
<div>
<form id="userRequest">
Mac Address: <input type="text" id="MacAddress"><br>
<input type="submit"
onclick="storeMacAddress();"
value="Save Mac Address">
</form>
</div>
<button onclick="
testVariable(userMac);
">Test</button>
</body>
</html>
Since you are defining the variable inside the function, it is not visible outside the function or even to other functions, hence we can define it outside where it will be accessible to all the functions, you can just assign values inside the function or access it inside the function!
Note: I have changed type attribute of input to text, so that the
variable assignment is visible in the snippet!
var userMac;
function storeMacAddress() {
userMac = document.getElementById("MacAddress").value
if (userMac)
alert("testing: " + userMac);
return userMac;
}
function testVariable(MacAddress) {
if (MacAddress)
alert(MacAddress);
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src='./index.js'>
</script>
</head>
<body>
<h1></h1>
<p></p>
<div>
<form id="userRequest">
Mac Address: <input type="text" id="MacAddress"><br>
<input type="button" onclick="storeMacAddress();" value="Save Mac Address">
</form>
</div>
<button onclick="
testVariable(userMac);
">Test</button>
</body>
</html>
You are creating the variable within the scope of the function, and not within a closure. Learn about closure.
You are wiring the function inline, which means that your return is completely useless. Look up the concept of “unobtrusive JavaScript”. Keep your JS and HTML separate, if you don't use a view-binding layer, like JSX, and even if you did, keep your services and your view logic separate.
You are using a submit, inside of a form. Even if this did what you wanted, the page would immediately be reloaded, and you would lose everything. Look up form actions.
To submit to the server, your form field should have a name.
I wrote the following code:
<form name=f>
<input type=button value="Button1" onclick=b1click()>
<input type=button value="Buttone2" onclick=b2click()>
<script language=javascript>
function b1click()
{
f.action="Login.jsp";
f.submit();
}
function b2click()
{
f.action="Logout.jsp";
f.submit();
}
</script>
</form>
This works code properly in Internet Explorer but the action does not work in Mozilla Firefox 3.6.2. How to solve this problem? Please any one help me.
I know this will sound snide, but the truth of the matter is: it's not 1995 anymore.
That code would have worked great a decade ago, but standards and specifications have changed significantly since then.
Lets start from the top:
<form name=f>
All html attribute values should be enclosed in quotes. For consistency sake, use double quotes: <form name="f"> is much better.
<input type="button" value="Button1" onclick="b1click()">
Avoid inline-script events. If the functionality ever changes, or you want to remove a function, you'll have to go through every page and adjust the function. A better way is to give the button an ID, and add the onclick event via scripts:
HTML:
<input type="button" value="Button1" id="button1">
JS:
document.getElementById('button1').onclick = b1click;
Now the script's turn:
<script language=javascript>
You should use the type attribute with a valid MIME type. Additionally, whenever possible, move your scripts to an external script file. When that's not possible, make sure to either XML encode your script, or encase it in CDATA tags:
<script type="text/javascript" src="path/to/script.js"></script>
OR
<script type="text/javascript">
/* <![CDATA[ */
... some code ...
/* ]]> */
</script>
Finally the real issue with your script.
The f property you're referencing is a member of the document, and not the window. I believe IE will put the reference on both, but it's just not safe to rely on either behavior.
Give the form an ID: <form id="f">, and get the element from the b[12]click functions
function b1click()
{
var f = document.getElementById('f');
f.action = 'Login.jsp';
f.submit();
}
First off, change that name="foo" to id="foo". Names are mostly used within the form itself.
Now, try to reference your form using document.formID, not just formID. formID is a variable, which is undefined, but document.formID is the actual form element:
function b1click()
{
document.f.action="Login.jsp";
document.f.submit();
}
function b2click()
{
document.f.action="Logout.jsp";
document.f.submit();
}
Give form an id and refer to it using:
var form = document.getElementById('formId');
You should quote the input attributes, or any attributes for that matter. And your script does not belong AFTER the form, e.g. in body, but rather in the HEAD element.
This works in IE, Firefox and Chrome.
<html>
<head>
<script language="javascript">
function b1click()
{
f.action="Login.jsp"; // better is document.f., but f. appears to work as well
f.submit();
}
function b2click()
{
f.action="Logout.jsp";
f.submit();
}
</script>
</head>
<body>
<form name="f">
<input type="button" value="Button1" onclick="b1click()">
<input type="button" value="Buttone2" onclick="b2click()">
</form>
</body>
</html>
There are a couple ways to reference your form.
If you define your form as <form name="Login" id="LoginFrom"></form>,
Method 1
If your form is the only one in the page, you can use:
document.forms[0].action = 'Login.jsp';
Method 2
If your form is not the only one form in the page, you can use the form name to reference the form, such as
document.Login.action = 'Login.asp';
Method 3
The form can also be referenced with DOM function getElementByID.
document.getElementByID('LoginForm').action = 'Login.asp'
This is a newbie question: Can the following HTML/JavaScript code be further simplified by just keeping the DIV to be updated + the INPUT button?
<div id="main_section" name="main_section">
<div id="update_div">Old stuff</div>
<input type="button" value="Update" id="update_button"/>
</div>
<script type="text/javascript" src="/jquery.js"></script>
<script type='text/javascript'>
$("#update_button").click(function() {
$("#update_div").html("New stuff");
})
</script>
Thank you.
You can even inline JavaScript code in your HTML but that is a horrible practice unless you know exactly what you're doing. Reads as:
<div id="update_div">Old stuff</div>
<input type="button" value="Update" onclick="$('#update_div').html('...')" />
If you want to encode the knowledge of what gets updated with that on click, then you can encode that knowledge in the HTML elements itself.
<div id='target'>Old</div>
<input type='button' value='Update' data-target='#target' date-value='New' />
In jQuery's onload, define this for all such buttons:
Since the data seems to be static here, a better global approach might be to define the data on the elements itself, and setup all handlers in one global sweep of the DOM.
$(function() {
$(':button').click(function() {
var dest = $(this).attr('data-target');
var value = $(this).attr('data-value');
$(dest).html(value);
});
});
The above code still requires external JavaScript but only need it once for all such button and div elements on the page.