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.
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>
Can anyone help me simplify this code?
Right now, I have to add to this code whenever I upload a new entry.
I would like it to work so that there is just one script that will identify the element IDs ("#rolly" or "#lagrimas") and run a code (.toggle('show')) on an entry depending on its state.
Also please let me know if this is better done with php. Although I would prefer javascript if that's possible...
The javascript that I add to everytime there is a new profile upload is this:
jQuery(document).ready(function(){
jQuery("#rolly").toggle('show');
jQuery("#lagrimas").live('click', function(lagrimas) {
jQuery("#rolly").toggle('show');
});
jQuery("#rodrigo").toggle('show');
jQuery("#ferber").live('click', function(ferber) {
jQuery("#rodrigo").toggle('show');
});
jQuery("#michael").toggle('show');
jQuery("#cruz").live('click', function(cruz) {
jQuery("#michael").toggle('show');
});
jQuery("#rodolfo").toggle('show');
jQuery("#paladin").live('click', function(paladin) {
jQuery("#rodolfo").toggle('show');
});
jQuery("#rommel").toggle('show');
jQuery("#abadiano").live('click', function(abadiano) {
jQuery("#rommel").toggle('show');
});
});
While below is an example of one of the html entries (corresponding to the first javascript above):
[btn_default_disabled id="lagrimas" class="btn" value="show/hide" fomable_id=3 default='Select' disabled='Reserved']
<br>
<div id="rolly">[formidable id=3]</div>
You can use common classes and DOM traversal to make your code more DRY.
Also note that live() was deprecated a long time ago. It's even been removed from jQuery v3. I would strongly suggest you don't use it, and also look to upgrade your version of jQuery to at least 1.12.
$(".btn").on('click', function() {
$(this).next('.target').toggle();
});
.target { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="lagrimas" class="btn">Toggle</button>
<div id="rolly" class="target">rolly</div>
<button id="ferber" class="btn">Toggle</button>
<div id="rodrigo" class="target">rodrigo</div>
It's a bit unclear what do you mean by upload a new entry in the question. I'll answer your question based on guessing.
It seems like you have having a set of a div and a button associated with it.
To simplify the code, you should abstract out this relationship by using class, and then binding the jquery event using the class selector instead of using the id.
Sample as below.
$(function() {
$('.display').toggle('show');
$('.container').on('click', '.btn', function() {
$(this).siblings('.display').toggle('show');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
<button class="btn" id="lagrimas">Click lagrimas</button>
<div class="display" id="rolly">
I am Rolly.
</div>
</div>
<div class="container">
<button class="btn" id="ferber">Click ferber</button>
<div class="display" id="rodrigo">
I am Rodrigo.
</div>
</div>
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);
}
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'
I've just recently discovered the power of jQuery. Just a quick question though.
What is a replacement for onclick="DeleteSomething('THE ID NUMBER LOADED IN BY SERVER SIDE')" ?
Is there even a way somehow to pass custom information such as an ID to a jQuery onclick? Or do I have to stay with the old fashioned way?
I usually use a rel="" for some extra data i might need attached to the button or whatnot.
for example
<input class="btnDelete" rel="34" value="Delete" />
then in jquery
$('.btnDelete').click(function() {
DeleteMethod($(this).attr("rel"));
});
If you stick the ID of the object you want to delete in the rel parameter, you can do it this way:
<script type="text/javascript>
$('a.deleter').click(function(){
if($(this).attr("rel") != ""){
DeleteSomething($(this).attr("rel"));
}
});
</script>
Delete Widget
$(document).ready(function () {
$('#selector').click(function() {
//here goes your onclick code
});
);
Please, post some markup for more help.
Also, you should read the Getting started with jQuery resources, linked in the main page of the library.
In jQuery you would more likely do something like:
$('a').click(function(){
# code here
});
With 'a' being whatever selector you want to use to find the right link.
In response to your comment:
Probably the best way, as someone else mentioned, would be to provide the dynamic data in one of the attributes of the link:
<a rel="{id}" >
$('a').click(function(){
deleteFunction($(this).attr('rel'));
});
Instead of this:
<button onclick="DeleteSomething('THE ID NUMBER LOADED IN BY SERVER SIDE')">
Do this:
<button id="thing">
<script>
$(function() {
$("#thing").click(function() {
DeleteSomething('THE ID NUMBER LOADED IN BY SERVER SIDE');
}
}
<script>
It would much cleaner if you do it this way:
<tag class="someclass" prop1="id from serverside" />
$('.someclass').click(function(){
var prop1 = $(this).attr('prop1');
//DeleteSomething(prop1)
});
Use the server to replace {ID} with the actual ID.
HTML:
<form id="deleter">
<input type="hidden" name="id" value="{ID}" \>
<input type="submit" value="Delete" rel="{ID}" \>
</form>
jQuery:
$('form#deleter input[type="submit"]').click(function() {
var id = $(this).attr('rel');
DeleteSomething(id);
return false;
}
Don't forget to implement the deleting server-side also for people who don't have Javascript enabled!