everybody. I'm hoping you can help me here, I'm trying to change the color of the body section of my document through javascript by clicking a button.
There are three buttons, each sets a background color. The problem is: When I click one of 'em, it changes the background color for just a second, then it returns to the originally set color, here's a sample of my code:
<html>
<head>
<script type="text/javascript">
function colorish(my_color){
if (my_color === 'gray'){
document.body.style.background = '#CCCCCC';
}else if (my_color === 'orange'){
document.body.style.background = '#FF9900';
}else if (my_color === 'blue'){
document.body.style.background = '#C1DAD6';
} else {
alert('on else');
}
}
</script>
</head>
<body style="background: orange;">
<form>
<button name="back_color" onclick="colorish('gray')">Gy</button>
<button name="back_color" onclick="colorish('orange')">Oe</button>
<button name="back_color" onclick="colorish('blue')">Be</button>
</form>
</body>
</html>
The script is on a separate file on my environment, but it is the exact same.
If in the script I include:
onload = selector();
function selector(){
var buttons = document.getElementsByName('back_color');
buttons[0].onclick = colorish('gray');
buttons[1].onclick = colorish('orange');
buttons[2].onclick = colorish('blue');
}
It just enters every buttons[].on... assignment and leaves the background set to the last assignment, being blue in this case.
I'm not an expert so maybe there's something I'm missing about html with js.
Without declaring a type for your buttons, they act as though they are type="submit". Since there's no configured action parameter on your <form> element, the action is the same page on which they are accessed. It's not that the background is only appearing for a split second and then returning to the normal color, the page is reloading and defaulting back to that color just as if you had just loaded it.
To stop this behavior, give each of your buttons a type="button":
<button type="button" name="back_color" onclick="colorish('gray')">Gy</button>
<button type="button" name="back_color" onclick="colorish('orange')">Oe</button>
<button type="button" name="back_color" onclick="colorish('blue')">Be</button>
As a side note, if you're not using buttons as part of a form to submit data, you don't need a corresponding <form> node - they will function and be standards-compliant all by themselves.
Removing the <form> tag will fix your problem. Clicking the button submits the form and reloads the page, resetting the page to its original state.
Related
For my school project I'm creating a mockup cinema website that has ticket booking service. Currently I'm trying to create the seat selection part.
I've successfully done that, and how the code detects if a seat has been selected is a Boolean value. (e.g. if they selected seat A1, a variable named "A1" will be set to true), now the only part left is to transfer the selection details users have selected to a popup webpage where they fill in their "payment" details. How do I exactly transfer variable values to a child webpage? Is a php file needed? I'm a noob at php so some guidance is appreciated.
I've been searching this technique for a while online(inc. stack overflow), but I couldn't find any right code that is right for my situation
<html>
<body>
The on/off button:
<button onclick="press_button"><img id="button" src="on.png" style="width:100px"></button>
<BR>
The button that opens a new webpage:
<button onclick="confirm()"> Confirm</button>
<script language="JavaScript">
var i=0, status;
function press_button(){
i++;
if(i%2 == 1){
document.getElementById('button').src='off.png';
status=true
}
else
document.getElementById('button').src='on.png';
status=false
}
//function that changes the look of the button when it is on/off and records down whether it is on/off
function confirm(){
window.open("confirm.html")
//opens a new webpage
</script>
</body>
</html>
For simplicity, I've made a simple web page that has an on/off button, and I'd like to have a confirm button that opens a new page and displays a text message depending on the status of the on/off button. Can anyone teach me how to do that?
You can do this with JS alone, but there are many other approaches too.
<body>
<input type='text' value='defaultParamValue'>
<button type='button'>send param</button>
<script type='text/javascript'>
document.querySelector('button').onclick
= () => window.location.href
= 'destination.html?nameOfParam='
+ encodeURIComponent(document.querySelector('[type=text]').value)
</script>
</body>
You can do this with PHP, which is more realistic and practical.
<body>
<form action='destination.php' method='get'>
<input name='param' type='text' value='defaultParamValue>
<input type='submit'>
</form>
</body>
And this is how you retrieve the value with PHP at destination.php.
$_POST['param'];
Here is how to do it with your own example.
<body>
The on/off button:
<!-- you need to include type='button', otherwise it acts as type='submit' -->
<button type='button' onclick='press_button()'>
<img id='button' src='on.png' style='width:100px'>
</button>
<BR>
The button that opens a new webpage:
<!-- you need to include type='button', otherwise it acts as type='submit' -->
<button type='button' onclick='confirm()'> Confirm</button>
<script type='text/javascript'> // the language attribute is deprecated
var
i=0,
button=document.querySelector('button'),
status
function press_button(){
i++
if(i%2 == 1){
button.src='off.png'
status=true
}
else{ // you were missing a curly bracket
button.src='on.png'
status=false
}
} // you were missing a closing curly bracket
function confirm(){
if(status){
// window in window.open is a global variable
// which means it is always accessible
// and you do not need to include it
open(`confirm.html?status=${encodeURIComponent(status)}`)
}
} // you were missing a closing curly bracket
</script>
</body>
Structuring your code makes it easier to spot issues (i.e. missing curly brackets) in your code.
The following JS will allow you to obtain the URL query string parameters on the new page.
const
urlParams = new URLSearchParams(location.search),
myParam = urlParams.get('status')
console.log(urlParams) // status=true/false
console.log(myParam) // true/false
I am trying to use elninotech/uppload, as it looks like it will do what I want (give me a portable, easy to use, powerful file upload button). However when I click on the button, the upload dialog appears and disappears (press pause, in debugger, before pressing button, then single step. On 2nd step dialog appears, on 3rd step it disappears).
What am I doing wrong?
<html>
<body>
<form class="profile">
<button id="uploadButton">upload image</button>
</form>
<img id="profilePicImage"/>
</body>
<script src="https://unpkg.com/uppload/dist/uppload.min.js"></script>
<script>
const profilePicture = new Uppload({
value: "https://randomuser.me/api/portraits/men/17.jpg",
bind: ["#profilePicImage"],
call: ["form.profile button#uploadButton"],
//endpoint: "https://example.com/upload_backend",
allowedTypes: "image"
});
</script>
</html>
I found a very complex example on their website https://elninotech.github.io/uppload/ I spent some time debugging, and looking at their code. This is what I found.
An element may have the attribute data-uppload-button to mark it as an uppload button. I don't know how that can work with more than one button.
A default button in form dose not work (it causes the problem described in the question). Changing the button to a span works (but is un-intuitive to user). Changing the form to a div, works. Changing the button type to button works.
From the git-hub issue tracker https://github.com/elninotech/uppload/issues/21#issuecomment-445997614
When you have an HTML form element without a method, it defaults to GET. If it has a button inside it, the form assumes it's a submit button, and therefore refreshes the page on pressing it. This means that if you have button without a type="button", the page is refreshed. This means the original state is reverted and you don't see Uppload open up. That's why you need a type="button" on buttons you don't want to submit the page. Alternately, you can have a event.preventDefault() and return false on the onSubmit event on the form too.
Here is the working code:
<html>
<body>
<form class="profile">
<button type="button" id="uploadButton">upload image</button>
</form>
<img id="profilePicImage"/>
</body>
<script src="https://unpkg.com/uppload/dist/uppload.min.js"></script>
<script>
const profilePicture = new Uppload({
value: "https://randomuser.me/api/portraits/men/17.jpg",
bind: ["#profilePicImage"],
call: ["div.profile button#uploadButton"],
//endpoint: "https://example.com/upload_backend",
allowedTypes: "image",
services: ["upload", "camera", "link"],
crop: {
startSize: [100,100, "%"]
}
});
</script>
</html>
I have not yet tested with a working endpoint (server)
This code is working but by clicking on the button then the page reload automatically.So, the new div is not appeared.
I can't find out what is the problem. Can you help me please.
<script src="jquery.min.js"></script>
<script>
function newJacky()
{
var new1= "<p>one more added</p>";
$(".apn").append(new1);
}
</script>
<button onclick="newJacky()">Add New</button>
<div id="apn" class="apn"></div>
This code is working but by clicking on the button then the page reload automatically (...)
From the above, I suspect that the <button> is placed inside a <form> element. That would explain why your page is reloaded after clicking the button.
An example using your code with button placed inside form. This would not happen if the button is placed outside the form - example
Solutions:
You can add a type=button attribute to the button (type=submit is by default if the attribute is not specified):
<button type="button" onclick="newJacky()">Add New</button>
DEMO 1
type attribute of <Button> element. Possible values are:
submit: The button submits the form data to the server. This is the default if the attribute is not specified, or if the attribute is dynamically changed to an empty or invalid value.
reset: The button resets all the controls to their initial values.
button: The button has no default behavior. It can have client-side scripts associated with the element's events, which are triggered when the events occur.
Reference
Prevent default form submission using event.preventDefault() (add "my-btn" class to the button):
<script src="jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".my-btn").click(function(event){
event.preventDefault();
var new1= "<p>one more added</p>";
$("#apn").append(new1);
});
});
</script>
<button class="my-btn">Add New</button>
<div id="apn" class="apn"></div>
DEMO 2
What you are getting from the page using jquery is not specified as an elements class or div. Like below:
$("apn").append(new1);
This should either be $(".apn").append(new1); where you are getting an element with class apn, or $("#apn").append(new1); where you are getting an element with div apn.
try that
If you are using jquery, I'd recommend using the on click functionality it provides:
<script src="jquery.min.js"></script>
<script>
$(function() {
$('.addNewBtn').click(function() {
var new1 = '<p>one more added</p>';
$('#apn').append(new1);
});
});
</script>
<button class="addNewBtn">Add New</button>
<div id="apn" class="apn"></div>
Just make sure to add the class to the button.
Fiddle
I am trying to make a refresh button, using an image (.jpg), in JavaScript for a website that every time it refreshes two images changes (uploaded from a database) but it wont work for some reason. This is my code so far:
<div align="center">
<SCRIPT LANGUAGE="JavaScript">
var body = document.getElementsByTagName("body")[0];
var s = document.createElement("input");
s.src = "/Volumes/playground_people/s1267664/html/dwd/buttons/next_btn.jpg";
s.type = "image";
body.appendChild(s);
document.write('<form><input type=button value="Next" onClick="history.go()"></form>')
</script>
</div>
Since it does not get clear to me what you actually want to achieve I can only guess what could help you.
The first thing is that your "Next"-input is missing some quotation marks around the type:
document.write('<form><input type="button" value="Next" onClick="history.go()"></form>');
I would advise you to put the form directly into the div-container instead of using the document.write.
Are you trying to add the image in the script to the button you defined below?
Then you have to refer to it, e.g. with an id:
<div align="center">
<input type="button" id="nextBtn" value="Next" onClick="location.reload(true)">
<script language="JavaScript">
var b = document.getElementById("nextBtn");
b.src = "/Volumes/playground_people/s1267664/html/dwd/buttons/next_btn.jpg";
b.type = "image";
</script>
</div>
I also removed the form, since it sends the image coordinates to the reloaded page, and used location.reload instead of history.go().
This code adds the image to the button, which refreshes the page when clicked.
I am using ASP.NET MVC 3 with the Yahoo API version 3. I am trying to get my YUI3 button to redirect to another page when I click on it, this button is my cancel button. The cancel button is a plain button type, but it is being treated like a submit button. It is not redirecting to the correct page, but acting like a submit button and it kicks off my page validation like what the submit button would do.
I thought that it might be with my HTML but I did validate it. It validated 100% correct. So I then stripped down the whole page to a bare minimum but the cancel button is still working like a submit button. Here is my HTML markup:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Create2</title>
</head>
<body class="yui3-skin-sam">
<h1>Test submit</h1>
#using (Html.BeginForm())
{
<button id="SaveButton" type="submit">Save</button>
<button id="CancelButton" type="button">Cancel</button>
}
<script src="http://yui.yahooapis.com/3.6.0pr4/build/yui/yui-min.js"></script>
<script>
YUI().use('button', function (Y) {
var saveButton = new Y.Button({
srcNode: '#SaveButton'
}).render();
var cancelButton = new Y.Button({
srcNode: '#CancelButton',
on: {
'click': function (e) {
Y.config.win.location = '/Administration/Department/List';
}
}
}).render();
});
</script>
</body>
</html>
I'm not sure what I am doing wrong here? Is this maybe a bug in their API? I am testing on IE8 and on the latest version of FireFox.
UPDATE:
I forgot to mention that if these buttons are not between form tags then the redirect works fine. If I put them in form tags then the redirect does not work.
I would use a link because you are redirecting to another page. Doing it this way you wouldn't need to initialize it with javascript or register the onClick listener.
<button id="SaveButton" type="submit">Save</button>
<a id="CancelButton" href='/Administration/Department/List'>Cancel</a>
Look at this link to style your link: http://yuilibrary.com/yui/docs/button/cssbutton.html
The Y.Button widget is removing the type attribute from the Cancel button. This makes that button behave like a submit button.
There are many possible paths to make this work. I'll start from simple to complex. The first is to avoid the issue entirely and not use JavaScript at all. Just use a link:
<form action="/Administration/Department/Create2" method="post">
<button class="yui3-button">Save</button>
<a class="yui3-button" href="/Administration/Department/List">Cancel</a>
</form>
After all, all that the Button widget is doing is adding a couple of css classes to each tag and a lot of other stuff that makes more complex widgets possible. As you can see in the Styling elements with cssbutton example, even <a> tags can look like nice buttons using just the YUI css styles. If you don't have to use JavaScript, better not to use it.
A second option is to avoid the Y.Button widget and use the Y.Plugin.Button plugin. It's more lightweight in both kb and processing power. And it doesn't touch the tag attributes, so your location code will work.
YUI().use('button-plugin', function (Y) {
Y.all('button').plug(Y.Plugin.Button);
Y.one('#CancelButton').on('click', function () {
Y.config.win.location = '/Administration/Department/List';
});
});
And finally you can hack around the behavior of the Y.Button widget by preventing the default action of the button:
var cancelButton = new Y.Button({
srcNode: '#CancelButton',
on: {
'click': function (e) {
e.preventDefault();
Y.config.win.location = '/Administration/Department/List';
}
}
}).render();