I am using the following script to set my colors:
<script type="text/javascript">
if (localStorage.buttonColor) {
document.getElementsByTagName('html')[0].className = localStorage.buttonColor
}
function getButtonColor(buttonName) {
localStorage.buttonColor = buttonName;
document.getElementsByTagName('html')[0].className = buttonName
}
</script>
Here's my HTML:
<form class="ng-pristine ng-valid">
<button name="darkBlue" onclick="getButtonColor(this.name)">Blue</button>
<button name="black" onclick="getButtonColor(this.name)">Black</button>
</form>
How can I make it so that when a color is chosen that the button to select that color is
disabled so that It cannot be selected again? Then when another button is clicked the other(s) are enabled. Also I need to set the button that's chosen from localstorage to disabled. Sorry I didn't not mention this fully in the question earlier.
function getButtonColor(button) {
button.disabled = "disabled"
localStorage.buttonColor = button.name;
document.getElementsByTagName('html')[0].className = button.name
}
and simply send this:
<button name="darkBlue" onclick="getButtonColor(this)">Blue</button>
<button name="black" onclick="getButtonColor(this)">Black</button>
<disclaimer> inline javascript is evil</disclaimer>
In addition to other answers (just send the button in the handler), you can use this when initially setting the color from localStorage (assuming your 'form' is the first child of 'body'):
if (localStorage.buttonColor) {
document.getElementsByTagName('html')[0].className = localStorage.buttonColor
var buttons = document.body.getElementsByTagName('form')[0].getElementsByTagName('button')
for(var i =0; i < buttons.length; i++)
if(buttons[i].name == localStorage.buttonColor) button.disabled = true
}
Although you might want to consider using jQuery if you often need to find elements in your code, since the getElementsByTagName selections can get verbose.
You can also use :
function getButtonColor(button) {
var elem=documentt.getElementById(button.id);
elem.removeAttribute("onclick");
}
Preferred is to use this and bind it to a variable (often that).
In this you get the html-object who called the function.
http://www.quirksmode.org/js/this.html
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
function getButtonColor() {
var that = this;
localStorage.buttonColor = that.Name;
document.getElementsByTagName('html')[0].className = that.Name;
that.disabled = "disabled";
}
Related
This question already has answers here:
How to check if a button has been clicked using javascript?
(4 answers)
Closed 2 years ago.
I was wondering if there is a way of checking if a button has been clicked? This is the button I want to check:
<button id="money" onClick="myFunction()"> £25 </button>
I've looked all over to try and find a solution but any method I've tried just creates errors, this is one solution I've tried:
function myFunction{
if(document.getElementById('money').clicked == true){
alert("button was clicked")
}
}
Any help is greatly appreciated! Thanks
you can add class isClicked at the end of your function and after that each time you click it never work in your condition
function myFunction(){
const el = document.getElementById('money');
if (!Object.values(el.classList).some(function(x) {return x == 'isClicked'})) {
alert('your code');
}
el.classList.add('isClicked');
}
<button id="money" onClick="myFunction()"> £25 </button>
It should work when you remove the if(document.getElementById('money').clicked == true){ line and the corresponding curly brace, e.g.:
var clickedPreviously = false;
function myFunction() {
if (clickedPreviously) {
alert("button was clicked");
}
clickedPreviously = true;
}
To do this you can add the element a specific class name which is "alreadyClicked" in this snippet after that you can check the element has this class or not with the hasClass() function that I share below.
function myFunction() {
if(hasClass(document.getElementById('money'),'alreadyClicked')){
console.log("button was already clicked");
}
else {
console.log("First click, added to class: alreadyClicked to element");
document.getElementById('money').classList.add("alreadyClicked");
}
}
function hasClass(el, cn){
var classes = el.classList;
for(var j = 0; j < classes.length; j++){
if(classes[j] == cn){
return true;
}
}
}
<button id="money" onClick="myFunction()"> £25 </button>
Another solution is using a new attribute with the same logic. You can add an attribute your element like data-clicked="false". According to Mozilla explained here;
Any attribute on any element whose attribute name starts with data- is
a data attribute. Say you have an article and you want to store some
extra information that doesn’t have any visual representation. Just
use data attributes for that.
<button
id="money"
data-clicked="true"
data-clicked-count="3">
£25</button>
To reach the data attributes with Javascript you can use below snippet.
var element = document.getElementById('money');
element.dataset.clicked; // true
element.dataset.clickedCount; // 3
And also you can set them more easily than class name updating and checking.
var element = document.getElementById('money');
element.dataset.clickedCount = 4
Full Solution with Data Attr
function myFunction() {
const myButton = document.querySelector('#money');
if(myButton.dataset.clicked == 'false'){
myButton.dataset.clicked = 'true';
console.log("data-clicked updated!");
}
myButton.dataset.clickedCount = parseInt(myButton.dataset.clickedCount)+1;
console.log("count of click : "+myButton.dataset.clickedCount);
}
function hasClass(el, cn){
var classes = el.classList;
for(var j = 0; j < classes.length; j++){
if(classes[j] == cn){
return true;
}
}
}
<button
id="money"
onClick="myFunction()"
data-clicked='false'
data-clicked-count='0'>
£25
</button>
You don't need the if statement. You would just have to add an event listener on the button like this:
function myFunction() {
document.getElementById('money').addEventlistener('click', () => {
alert('button clicked')
}
Try like this
document.getElementById('money').onclick = function() {
alert("button was clicked");
};
document.getElementById('money').onclick = function() {
alert("button was clicked");
};
<button id="money"> £25 </button>
I have this code in html I want to change the checkbox check and uncheck event using javascript on some event so I am calling function ChangeCheckBox() on button click
<div>
<label class="checkbox line">
<input type="checkbox" id="Add" />Add</label>
</div>
<script>
function ChangeCheckBox() {
var AddCheck = 0;
if (AddCheck == 1) {
document.getElementById("Add").checked = true;
} else {
document.getElementById("Add").checked = false;
}
}
</script>
So in above condition check box should unchecked but its not happening checkbox is remaining checked after running this code
Since you are setting AddCheck = 0;, of course it will not keep it's state, because you are reseting the value. If you want to simulate a toggle, here's a simpler alternative.
<script>
function ChangeCheckBox() {
var el = document.getElementById("Add");
el.checked = !el.checked;
}
</script>
How do you link 'ChangeCheckBox()' to your button ? Can you post this code too ?
The problem is probably because the button refresh your page and so, the checkbox return to it initial state.
i have javascript script :
<script type="text/javascript">//<![CDATA[
window.onload=function(){
document.mainForm.onclick = function(){
var radVal = document.mainForm.pages.value;
result.innerHTML = 'You selected: '+radVal;
}
}//]]>
</script>
radio button :
<form id="mainForm" name="mainForm">
<input name="pages" type="radio" value="p1">
<input name="pages" type="radio" value="p2">
<input name="pages" type="radio" value="p3">
</form>
<span id="result"></span>
<a href="http://localhost/folder/blabla.php?p=book'>Book</a>
i want form click radio button the value from radio button has place on the link url, so that can be :
link : <a href='http://localhost/folder/blabla.php?p=book&o=p1'>Book</a>
add value &o=p1
can anyone help me?
thank you before
Your form doesn't need a name, it's superfluous. The way you've attached the listener, this within the function will reference the form so you can do:
window.onload=function(){
document.mainForm.onclick = function(event){
var radVal = this.rads.value;
// do stuff with radVal
}
For your solution, consider the following which adds the listener onload, then conditionally modifies the URL whenever there's a click inside the form. You could use a click event on each button, or look at the event and see if it came from one of the buttons, but I think it's simpler to just update the URL ever time there's a click:
window.onload = function() {
var form = document.forms['mainForm'];
if (form) {
form.addEventListener('click', function() {
var link = document.getElementById('a0');
// Note that if there is only one such button, this will return a
// reference to the single element so maybe querySelectorAll is better
var buttons = this.pages;
// var buttons = this.querySelectorAll('[name=pages]');
for (var i=0, iLen=buttons.length; i<iLen; i++) {
if (buttons[i].checked) {
// Add to the href or replace if previously added
link.href = link.href.replace(/\&.*|$/, '&o=' + buttons[i].value);
// debug
console.log(link.href);
// Stop once checked button is found
return;
}
}
}, false);
}
}
How can I figure out what button was clicked on last? For example I have:
<input type="button" name= "zoomer" value="State View" id= 'States View' onclick="zoomout()"/>
<input type="button" name= "zoomer" value="County View" id= 'Counties View' onclick="countyView()"/>
But whenever I change a RADIO button, I want it to take into account which button was clicked last (County View or State View). Is it possible to do this?
You could keep a global JavaScript variable var last_clicked which is updated in the functions zoomout() and countyView(), and then check the value of last_clicked when you change the radio button. Alternatively, you can terminate the calls to the functions within the onclick event with a semicolon, then assign the value to last_clicked inside the onclick event string (although I wouldn't recommend it as it can make your code messy).
var lastClicked = "none";
function zoomout()
{
// your code
lastClicked = "states";
}
function countyView()
{
//your code
lastClicked = "county";
}
if(lastClicked == "county")
{
}
else if(lastClicked == "states")
{
}
it's possible by using an external variable such as
var clickedLast = "";
function zoomout() {
clickedLast = "stateview";
... your code ...
}
function countyView() {
clickedLast = "countyview";
... your code ...
}
Is there a way to make a HTML select element call a function each time its selection has been changed programmatically?
Both IE and FF won't fire 'onchange' when the current selection in a select box is modified with javascript. Beside, the js function wich changes the selection is part of framework so I can't change it to trigger an onchange() at then end for example.
Here's an example:
<body>
<p>
<select id="sel1" onchange="myfunction();"><option value="v1">n1</option></select>
<input type="button" onclick="test();" value="Add an option and select it." />
</p>
<script type="text/javascript">
var inc = 1;
var sel = document.getElementById('sel1');
function test() {
inc++;
var o = new Option('n'+inc, inc);
sel.options[sel.options.length] = o;
o.selected = true;
sel.selectedIndex = sel.options.length - 1;
}
function myfunction() {
document.title += '[CHANGED]';
}
</script>
</body>
Is there any way to make test() call myfunction() without changing test() (or adding an event on the button)?
Thanks.
If you can extend/modify the framework to give a hook/callback when they change the select options, it would be better (one way could be to use the dynamic capabilities of js to duck type it in?).
Failing that, there is an inefficient solution - polling. You could set up a setTimeout/setInteval call that polls the desired select option dom element, and fire off your own callback when it detects that something has changed.
as for the answer to your question
Is there any way to make test() call
myfunction() without changing test()
(or adding an event on the button)?
yes, by using jquery AOP http://plugins.jquery.com/project/AOP , it gives an easy-ish solution.
<body>
<p>
<select id="sel1" onchange="myfunction();"><option value="v1">n1</option></select>
<input type="button" onclick="test();" value="Add an option and select it." />
</p>
<script type="text/javascript">
var inc = 1;
var sel = document.getElementById('sel1');
function test() {
inc++;
var o = new Option('n'+inc, inc);
sel.options[sel.options.length] = o;
o.selected = true;
sel.selectedIndex = sel.options.length - 1;
}
function myfunction() {
document.title += '[CHANGED]';
}
//change to aop.after if you want to call afterwards
jQuery.aop.before( {target: window, method: 'test'},
function() {
myfunctino();
}
);
</script>
</body>
Define your own change function that calls the framework function and then calls a
callback function.
e.g.:
function change(callback)
{
frameworkchange();
callback();
}
The answer is .... no.
The DOM only fires the onchange event as a result of user action not code. It does not provide any additional events to hook in this regard.
You will need to customise the framework or drop your requirement.
ahem...
you can access the event 'onpropertychange' it contains a property within the event arguments to identify which property was changed.
It detects both 'selectedIndex' and 'value' changes - simply case test 'propertyName' I'm currently working with the ASP.NET js framework here is some straight copy-paste code for that:
1) define handler:
this._selectionChangedHandler = null;
2) assign handler
this._selectionChangedHandler = Function.createDelegate(this, this._onSelectionChanged);
3) attach handler to event
$addHandler(element, "propertychange", this._selectionChangedHandler);
4) create function
_onSelectionChanged: function(ev) {
if (ev.rawEvent.propertyName == "selectedIndex")
alert('selection changed');
},
With JQuery, you could do something like
$(document).ready(function(){
$('#select-id').change(function(e){
e.preventDefault();
//get the value of the option selected using 'this'
var option_val = $(this).val();
if(option_val == "v1"){
//run your function here
}
return true;
});
});
This would detect the change programmatically and let you respond to each item changed