I have this code:
<script type="text/javascript">
function changestate()
{
var StateTextBox = document.getElementById("State");
var IgnoreTextBox = document.getElementById("Ignore");
var PlayButton = document.getElementById("Play");
if(document.getElementById("Play").onclick == true)
{
StateTextBox.value = "Happy";
}
}
</script>
<input TYPE="button" VALUE="Play with Pogo" id="Play" onClick="changestate();"/>
I'm trying to know when the button is clicked, and have that if button is clicked in the if statement. I want to know this so I can change the value that is inside the text box. The problem is, I do not know how to tell when the button is clicked. If you could help me out that would be great.
The onclick attribute identifies what should happen when the user clicks this particular element. In your case, you're asking that a function be ran; when the function runs, you can rest assured that the button was clicked - that is after all how the function itself got put into motion (unless you invoked it some other way).
Your code is a bit confusing, but suppose you had two buttons and you wanted to know which one was clicked, informing the user via the stateTextBox value:
(function () {
// Enables stricter rules for JavaScript
"use strict";
// Reference two buttons, and a textbox
var playButton = document.getElementById("play"),
stateTextBox = document.getElementById("state"),
ignoreButton = document.getElementById("ignore");
// Function that changes the value of our stateTextBox
function changeState(event) {
stateTextBox.value = event.target.id + " was clicked";
}
// Event handlers for when we click on a button
playButton.addEventListener("click", changeState, false);
ignoreButton.addEventListener("click", changeState, false);
}());
You can test this code live at http://jsfiddle.net/Y53LA/.
Note how we add event-listeners on our playButton and ignoreButton. This permits us to keep our HTML clean (no need for an onclick attribute). Both of these will fire off the changeState function anytime the user clicks on them.
Within the changeState function we have access to an event object. This gives us some details about the particular event that took place (in this case, the click event). Part of this object is the target, which is the element that was clicked. We can grab the id property from that element, and place it into the value of the stateTextBox.
Here is the adjusted HTML:
<input type="button" value="Play with Pogo" id="play" />
<input type="text" id="state" />
<input type="button" value="Ignore with Pogo" id="ignore" />
You can know if button clicked by using a flag (true or false).
var flag = false;
window.addEventListener("load", changestate, false);
function changestate() {
var StateTextBox = document.getElementById("State");
var PlayButton = document.getElementById("Play");
PlayButton.addEventListener("click", function () {
flag = true;
})
PlayButton.addEventListener("click", change)
function change() {
if (flag) {
StateTextBox.value = "Happy";
}
}
}
Looking back on this, many years later, you could simply do:
<script type="text/javascript">
function changestate(action)
{
var StateTextBox = document.getElementById("State");
var IgnoreTextBox = document.getElementById("Ignore");
var PlayButton = document.getElementById("Play");
if(action == "Play")
{
StateTextBox.value = "Happy";
}
}
</script>
<input TYPE="button" VALUE="Play with Pogo" id="Play" onClick='changestate("Play");'/>
Related
Using the pen below you can see there are two elements, a button and a checkbox input.
When the button is clicked I would like to determine the status of checkbox (clicked/not-clicked).
Regardless of the visual check mark presence or not, the console always logs false. Why is this?
https://codepen.io/sterlingbutters/pen/ZEGGgvm
EDIT (code):
HTML:
<input id='stall' type="checkbox">
<button id='button'>Test
JS:
var stall = document.getElementById('stall').checked;
var button = document.getElementById('button');
button.onclick = function () {
console.log(stall);
}
You have to reasign stall on button click.
So Using
button.onclick = function () {
var stall = document.getElementById('stall').checked
console.log(stall);
}
It works fine.
Try this instead: assign the element to the variable, and then inside your onclick function you get the checked property every time it runs.
If you just store the boolean value of checked in a variable, it will never update. Primitive types like booleans are always stored as simple values, not as auto-updating references back to the original property.
var stall = document.getElementById('stall');
var button = document.getElementById('button');
button.onclick = function () {
console.log(stall.checked);
}
<input id='stall' type="checkbox">
<button id='button'>Test
Once you assigned "stall", it won't be re-assiged in "button.onclick". You must re-assign, such as
var button = document.getElementById('button');
button.onclick = function () {
var stall = document.getElementById('stall').checked;
console.log(stall);
}
or better
var stall = document.getElementById('stall');
var button = document.getElementById('button');
button.onclick = function () {
console.log(stall.checked);
}
I am trying to make a simple Shopping List App in which user can Add, Delete and mark the task done when completed. So far, I am able to add the task but facing problem in executing the done and delete functions. I am getting an error because when I execute it, the done and delete buttons are not there but what should I do to fix it?
var inp = document.getElementById("form");
var button = document.getElementById("click");
//Create List Function with Done and Delete Buttons
function addVal() {
var ul = document.getElementById("list");
var li = document.createElement("li");
var span = document.createElement("span");
var done = document.createElement("button");
var del = document.createElement("button");
li.appendChild(document.createTextNode(""));
span.appendChild(document.createTextNode(inp.value));
done.appendChild(document.createTextNode("Done"));
del.appendChild(document.createTextNode("Delete"));
li.appendChild(span);
li.appendChild(done);
li.appendChild(del);
done.setAttribute("class", "doneBut");
del.setAttribute("class", "delBut");
ul.appendChild(li);
inp.value = "";
}
//Get Input Length
function checkLength() {
return inp.value.length;
}
//Run function on Button Click
function onButtonClick() {
if (checkLength() > 0) {
addVal();
}
}
//Run function on Enter Keypress
function onEnter(event) {
if (checkLength() > 0 && event.which === 13) {
addVal();
}
}
//Trigger Events
button.addEventListener("click", onButtonClick);
inp.addEventListener("keypress", onEnter);
//Done and Delete Button Functions
var doneButton = document.getElementsByClassName("doneBut");
var deleteButton = document.getElementsByClassName("delBut");
function doneTask() {
doneButton.parentNode.classList.add("done");
}
function delTask() {
deleteButton.parentNode.classList.add("delete");
}
doneButton.addEventListener("click", doneTask);
deleteButton.addEventListener("click", delTask);
<input type="text" placeholder="Enter Your Task..." id="form" />
<button id="click">Add Task</button>
<h2>List:</h2>
<ul id="list"></ul>
Please Help.
Your problem is that the code tries to add events before the buttons exist. The buttons don’t exist until the addVal function gets called. Since addVal is not being called before the you try to add your event handlers, the getElementById returns null, and you attempt to add an event listener to null.
Additionally it looks like you’re planning to add multiple done and delete buttons. That wouldn’t normally be a problem, except you’re referencing them by ID, and IDs MUST be unique. You’ll need to switch this to a class or an attribute, since you’ll need one per item in the shopping cart.
You’ll probably want to look into event delegation, so that you can add your events once to the page before any buttons exist. https://javascript.info/event-delegation
It's most likely because your script is running before your code is running. Add the <script> tags just before the closing </body> tag to fix it:
<script>/* Your code here */</script>
</body>
You need to place this in a window.onload function, or run it in a function inside of the body tag's onload. Those elements don't exist yet when the script is run:
window.onload = function() {
var inp = document.getElementById("form");
var button = document.getElementById("click");
button.addEventListener("click", onButtonClick);
inp.addEventListener("keypress", onEnter);
}
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 ...
}
I have an html image. In its onClick event I have written code to show a calendar. I want to disable that image, which means I should not be able to click that image, but the image should be visible. I want to disable the onclick event of image. Can anybody help?
Or without making any changes to your calendar...
<div>Click the button because I am enabled... <img id="btnSubmit" src="submitbutton.gif" onclick="Foobar(this,event);" alt="submit button" /></div>
<p>
<span onclick="ToggleOnclick('btnSubmit');">Click here to disable/enable the image's onclick</span>
</p>
<script>
function ToggleOnclick(elID)
{
/// <summary>
///
/// </summary>
var el = document.getElementById(elID);
if (el.onclick)
{
// Disable the onclick
el._onclick = el.onclick;
el.onclick = null;
alert(el.id +'\'s .onclick has been disabled.');
}
else //if (!(button._onclick))
{
// Disable the onclick
el.onclick = el._onclick;
el._onclick = null;
alert(el.id +'\'s .onclick has been enabled.');
}
}
function Foobar(el, e)
{
alert('Submitting...');
}
</script>
The gold is in the ToggleOnclick. In fact you could generalise that any use it to disable/enable events on just about anything.
I assume you have something like:
...
<script>
var Calendar = function() {
var month = ...;
var updateDisplay = function() {
...
};
return {
prevMonth: function() {
month--;
updateDisplay();
}
};
};
var cal = new Calendar();
</script>
Calendar is a class with private members, cal is an instance of that class.
All you should have to do is add a new member to Calendar that tracks if your onclick should be disabled, e.g. isDisabled, and check for this in the function you call in your onclick, e.g.
prevMonth: function() {
if (isDisabled) {
return;
}
month--;
updateDisplay();
}
easiest method is to use some hidden field or javascript variable
HiddenField:
<asp:HiddenField id="hdnValue" runat="server" value="true"/>
<script type="text/javascript">
function ImageClickHandler(){
var i=document.getElementById(<%=hdnValue.ClientID%>).Value;
//don't know if .value works because I'm very much into jQuery
if(i=='true') //go ahead and show calendar
else //don't show !
}
</script>
Variable:
var showCal = "<%= VARIABLE_TO_SET_IF_CAL_ENABLED%>";
<script type="text/javascript">
function ImageClickHandler(){
if(showCal=='true') //go ahead and show calendar
else //don't show !
}
</script>
As has been said, just add a condition within the onclick handler.
<script type="text/javascript">
var _imageClickDisabled = false;
function disableImageClick()
{
_imageClickDisabled = true;
}
function onImageClick()
{
if (_imageClickDisabled)
{
return;
}
// show your calendar here
//
// : : :
}
</script>
<img ... onclick="onImageClick()" />
Just call the disableImageClick() function to stop the calendar showing.
Hi it is very very late,
But I too have got same requirement and I have fixed it by replacing the image tag with input element with type as image, the benefit of this element is it show the image as input element and disabled property will allow you disable click event. Below is the code I have used
<input type="image" src="<date icon>"
onclick="return showCalender('txtdate','dd\mm\y');" disabled="disabled"></input>
Keep in mind that, the disabled attribute will only work for form related elements
Thought might be helpful for other guys in future.