I didn't find an answer here (maybe because my knowledge in JS is very limited), so I decided to ask the question myself:
How can I execute my javascript after a certain event? I have a form and I want the JS to run after the last radio is selected but before submitting the form.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form id="myform">
//various fields
</form>
<script type="text/javascript">
function myfunction() {}
</script>
</body>
</html>
I managed the function to run when loading the website and after the last field was filled/radio was checked, but i want it to run ONLY when the last radio was checked.
Thx for everyone to help me
You can use element.addEventListener(“event”, function) and element.removeEventListener(“event”, function) instead of the on attributes. It can make your code much cleaner! Here’s a simple example:
document.getElementById(“button”).addEventListener(“click”, myFunction);
function myFunction(){
alert(“hello world!”);
}
Try: onclick=“myfunction()”
For example if your code is <input type=“checkbox” onclick=“myfunction()”>
Then it might run something like this:
/* Notice how the function below corresponds with the onclick function */
function myfunction() {
alert("Box Checked!")
//Put whatever you want in here
}
function Yes() {
alert("Thanks!")
//Put whatever you want in here as well
}
function No() {
alert("Aw...")
//Put whatever you want in here as well
}
function Submit() {
alert("Thanks!")
}
<!Doctype html>
<html>
<p>Check this box!</p>
<input type="checkbox" onclick="myfunction()">Check me!</input>
<!-- notice the onclick function here -->
<br>
<br>
<p>Fill this form!</p>
<label for="username">Username: </label>
<input type="text" id="username" name="username">
<br><br>
<input onclick="Submit()"type="submit" value="Submit">
<!-- notice the onclick function here as well -->
<p>Is this answer good?</p>
<input onclick="Yes()" type="radio">
<!-- You know the drill ;) -->
<label>Yes! 😀</label>
<br>
<input onclick="No()" type="radio">
<!-- Ditto -->
<label>No! 😭</label>
</html>
This will work for most elements with a user required click (i.e Check Box, Submit button, so on...)
Just insert onclick="myfunction()".
For more information, go to this site:
https://www.w3schools.com/jsref/event_onclick.asp
Hoped this helped!
You can make a function that will do something when a certain condition is met(that is sorta an event in theory in the first place)
In other words, not every living thing that happens dispatches an event of some sort, especially composite things like that. For things like those, just wait until your logical event happens then execute some code.. the following function works like that
function onEvent(condition,whenFulfiled,eventParam){
var i=setInterval(()=>{
if(condition()){
clearInterval(i)
whenFulfiled(eventParam)
}
},0)
}
var checkboxes=document.getElementsByClassName('checkbox')
//example uses
onEvent(
function(){
return [...checkboxes]
.filter(a=>a.checked)
.length == checkboxes.length
},
function(boxes){
console.log("all boxes checked :D\nunchecking them...")
boxes.forEach(a=>a.checked=false)
},
[...checkboxes]
)
<div><h3>when checked all are checked(which is not a real event, this ad-hoc "event listener" would activate)</h3></div>
<div><input class="checkbox" type="checkbox" /></div>
<div><input class="checkbox" type="checkbox" /></div>
<div><input class="checkbox" type="checkbox" /></div>
<div><input class="checkbox" type="checkbox" /></div>
Related
I have tested all the code, it is fine except calc_price() that isn't executed even when I deleted all the code in function body except message.
<?php
include("header.php");
?>
<script type="text/javascript">
function calc_price()
{
alert('ooooooooooooooooooooooooooooo');
var pro_qty=<?php echo($row['pro_qty']);?>;
var price=document.getElementById('pro_price').value;
var count=document.getElementById('pro_qty').value;
var total_price;
if(count>pro_qty)
{alert('تعداد موجودی انبار کمتر از درخواست شماست');
document.getElementById('pro_qty').value=0;
count=0;
}
if(count==0 || count='') total_price=0;
else total_price=count*price;
document.getElementById('total_price').value=total_price;
}
</script>
<form action="action_order.php" method="post" name="order">
<p>
<label for="textfield3">تعداد درخواستی</label>
<input type="text" name="pro_qty" id="pro_qty" onChange="calc_price();">
</p>
<input type="submit" name="button" id="button" value="خرید محصول">
</p>
</form>
<?php
include("footer.php");
?>
I have made a quick test, onchange or onChange are working both fine. The function what you attach as an event triggers when you leave the focus from the input. You can read further about onchange event in this link. HTML is not considered case sensitive but it is a good practice to keep it lowercase (Source: Is HTML case sensitive?).
If you would like to trigger on each key press your function just change the event to on key up like the below example:
<input type="text" name="pro_qty" id="pro_qty" onkeyup="calc_price()">
Source: onkeyup Event
I need one help .I need to check radio button and set the value using Jquery/Javascript.I did something but its not working.
<input type="radio" name="con" id="con" value="" onClick="checkCon();">Country
<button type="button" id="btn">Check</button>
document.getElementById('btn').onclick=function(){
var condata='123';
$("input[name=con][value=" + condata+ "]").prop('checked', true).trigger('click');
}
Here when user will click on check button it can not check the check box and can not set the value.Please help me.
try this, it can help:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<script>
$(document).ready(function(){
var condata = '123';
$("#btn").click(function(){
$('#con').val(condata).prop('checked', true).trigger("click");
});
});
function checkCon()
{
alert($('#con').val());
}
</script>
</head>
<body>
<input type="radio" name="con" id="con" value="" onClick="checkCon();">Country
<button type="button" id="btn">Check</button>
</body>
</html>
this code is working I've checked this, you can also try
its probably because you are mixing up javascript and jQuery , either you should use jQuery or JavaScript. Hope the above code help. and make sure you have added jQuery library before using this code
You have to use the cotes.
Reference
$("input[name='con'][value='" + condata+ "']").prop('checked', true).trigger('click');
It's clear that there's no radio button with value '123'.
Note 1 : You don't need to prop and trigger at the same time, just prop or trigger the click events.
$("input[name=con][value=" + condata+ "]").trigger('click');
Note 2 : Click trigger automatically change the radio button properties. If you want to force it checked, do something like this.
$("input[name=con][value=" + condata+ "]").on('click', function(e) {
e.preventDefault();
$(this).prop('checked', true);
});
<input type="radio" name="con" id="con" value="" onClick="checkCon();">
Your radio button don't have value="123"
That is why it's not getting checked.
This is the corrected tag
<input type="radio" name="con" id="con" value="123" onClick="checkCon();">
and it will work as intended
I´m trying to do a program that save the state of the radio button and check it. This is my code but I don´t know what it`s wrong. Help me please
<script>
function saveState(){
var ans1 = document.getElementById('grupo1');
if (ans1.value == 1)
{
ans1.setAttribute("checked","checked");
ans1.checked = true;
}
</script>
<input type="radio" name="group" id="grupo1" value="1"> One
<input type="radio" name="group" id="grupo2" value="0"> Two
<input type="submit" onclick="saveState()" value="update">
Try this:
<script>
function saveState(){
var ans1 = document.querySelector('input[name="group"]:checked').value;
if (ans1.value == 1){
ans1.setAttribute("checked","checked");
ans1.checked = true;
}
}
</script>
Being consequent in your approach towards placing brackets helps preventing situations like thisone.
For example, if you place the opening bracket to functions, loops, conditional (if) statements etc on the same line as the condition itself (like you do above at the declaration of the function), you'll only have to look for the closing ones.
On the other hand, if you place both opening and closing brackets on their own line your code will be much more vertically symmetrical, which makes it easier to spot missing brackets if you're dealing with larger chunks of code.
You should check out this article that deals with this particular issue: http://encosia.com/in-javascript-curly-brace-placement-matters-an-example/
You perhaps mean this?
You code does not make much sense unless the grupo1 button can change value
The following script assumes you have a standard cookie script somewhere
<script>
window.onload=function() {
if (getCookie("grupo1")=="true") {
document.getElementById('grupo1').click();
}
// either this
document.getElementById('grupo1').onclick=function() {
setCookie("grupo1","true")
}
// or this - depending on when you want to save the state
document.getElementById("form1").onsubmit=function() {
setCookie("grupo1",document.getElementById('grupo1').checked?"true":"false");
}
}
</script>
<form id="form1">
<input type="radio" name="group" id="grupo1" value="1"> One
<input type="radio" name="group" id="grupo2" value="0"> Two
<input type="submit" value="update">
</form>
I'm trying to create a page that generates simple custom reports based on the checkboxes a user clicks. On the left side I will have a vertical column of checkboxes. For simplicity's sake, lets say I have two checkboxes labeled "Population" and "Employment".
When a user is interested in seeing employment data they check the "Employment" box and the image file of the data "employment.jpg" will be displayed to the right. If they then uncheck the box, the image will disappear. If they check both boxes, both images will be similarly displayed, one below the other in the order clicked.
I'm am loosely familiar with HTML, and new to Javascript. I've been trying to do this with if statements and document.write but can't keep my checkboxes on the page when the image is generated.
Here's my current code:
<html>
<head>
<script language="javascript" type="text/javascript">
function checker(that) {
if (that.checked) {
document.write("<br /><br /><img src='employment.png'>");
}
}
</script>
</head>
<body>
<form>
<input type="checkbox" name="Box" onclick="checker(this)"> Employment <br />
</form>
</body>
</html>
Here's a quick example to get you started. You can see it in action here.
function toggleVisibility(id) {
var el = document.getElementById(id);
if (el.style.visibility=="visible") {
el.style.visibility="hidden";
}
else {
el.style.visibility="visible";
}
}
<label for="chkemployment">Employment</label>
<input type="checkbox" id="chkemployment" onChange="toggleVisibility('imgemployment');" /><br/>
<label for="chkpopulation">Population</label>
<input type="checkbox" id="chkpopulation" onChange="toggleVisibility('imgpopulation');" />
<hr />
<img id="imgemployment" src="http://www.gravatar.com/avatar/c0d7be6d99264316574791c1e4ee4cc4?s=32&d=identicon&r=PG" style="visibility:hidden"/>
<img id="imgpopulation" src="http://www.gravatar.com/avatar/c0d7be6d99264316574791c1e4ee4cc4?s=32&d=identicon&r=PG" style="visibility:hidden" />
This is how the solution looks like in AngularJS:
<script src="http://docs-next.angularjs.org/angular-0.10.1.min.js"
ng:autobind></script>
<p>
<input type="checkbox" name="production" id="production" />
<label for="production">Production</label>
</p>
<p>
<input type="checkbox" name="employment" id="employment" />
<label for="employment">Employment</label>
</p>
<img src="http://i.i.com.com/cnwk.1d/i/bto/20071106/OLPC_photo_540x360.jpg"
ng:show="production" />
<img src="http://www.sunriseenterprisesinc.com/main/Portals/0/EmploymentSmall.jpg"
ng:show="employment" />
You can play with the example here: http://jsfiddle.net/psyho/nrdnx/
You can handle the change event of the checkboxes. Here's a full example (without images, though): http://jsfiddle.net/minitech/hsF9s/
Usually people use a framework such as jQuery. It allows you to abstract away from the nitty gritty details and cross-browser pains. Using that, you would do the task you describe like this:
http://jsfiddle.net/3vQJZ/3/
And here's the code from that working demo:
<input type="radio" name="selectPicture" value="http://i170.photobucket.com/albums/u277/AmandaisAwesomeQUACK/monkey.gif"/>
<input type="radio" name="selectPicture" value="http://freesmileyface.net/smiley/animals/monkey-crush2.gif" checked/>
<img id="image" src="http://freesmileyface.net/smiley/animals/monkey-crush2.gif" alt="image selected by radio buttons"/>
$(document).ready(function(){
$('input[name=selectPicture]').click(function(){
$('#image').attr('src', $('input[name=selectPicture]:checked').val());
});
});
I am basing my question and example on Jason's answer in this question
I am trying to avoid using an eventListener, and just to call handleClick onsubmit, when the submit button is clicked.
Absolutely nothing happens with the code I have.
Why is handleClick not being called?
<html>
<head>
<script type="text/javascript">
function getRadioButtonValue(rbutton)
{
for (var i = 0; i < rbutton.length; ++i)
{
if (rbutton[i].checked)
return rbutton[i].value;
}
return null;
}
function handleClick(event)
{
alert("Favorite weird creature: "+getRadioButtonValue(this["whichThing"]));
event.preventDefault(); // disable normal form submit behavior
return false; // prevent further bubbling of event
}
</script>
</head>
<body>
<form name="myform" onSubmit="JavaScript:handleClick()">
<input name="Submit" type="submit" value="Update" onClick="JavaScript:handleClick()"/>
Which of the following do you like best?
<p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
<p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
<p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
</form>
</body>
</html>
edit:
Please do not suggest a framework as a solution.
Here are the relevant changes I have made to the code, which results in the same behavior.
function handleClick()
{
alert("Favorite weird creature: "+getRadioButtonValue(document.myform['whichThing'])));
event.preventDefault(); // disable normal form submit behavior
return false; // prevent further bubbling of event
}
</script>
</head>
<body>
<form name="aye">;
<input name="Submit" type="submit" value="Update" action="JavaScript:handleClick()"/>
Which of the following do you like best?
<p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
<p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
<p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
</form>
You can either use javascript url form with
<form action="javascript:handleClick()">
Or use onSubmit event handler
<form onSubmit="return handleClick()">
In the later form, if you return false from the handleClick it will prevent the normal submision procedure. Return true if you want the browser to follow normal submision procedure.
Your onSubmit event handler in the button also fails because of the Javascript: part
EDIT:
I just tried this code and it works:
<html>
<head>
<script type="text/javascript">
function handleIt() {
alert("hello");
}
</script>
</head>
<body>
<form name="myform" action="javascript:handleIt()">
<input name="Submit" type="submit" value="Update"/>
</form>
</body>
</html>
In this bit of code:
getRadioButtonValue(this["whichThing"]))
you're not actually getting a reference to anything. Therefore, your radiobutton in the getradiobuttonvalue function is undefined and throwing an error.
EDIT
To get the value out of the radio buttons, grab the JQuery library, and then use this:
$('input[name=whichThing]:checked').val()
Edit 2
Due to the desire to reinvent the wheel, here's non-Jquery code:
var t = '';
for (i=0; i<document.myform.whichThing.length; i++) {
if (document.myform.whichThing[i].checked==true) {
t = t + document.myform.whichThing[i].value;
}
}
or, basically, modify the original line of code to read thusly:
getRadioButtonValue(document.myform.whichThing))
Edit 3
Here's your homework:
function handleClick() {
alert("Favorite weird creature: " + getRadioButtonValue(document.aye.whichThing));
//event.preventDefault(); // disable normal form submit behavior
return false; // prevent further bubbling of event
}
</script>
</head>
<body>
<form name="aye" onSubmit="return handleClick()">
<input name="Submit" type="submit" value="Update" />
Which of the following do you like best?
<p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
<p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
<p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
</form>
Notice the following, I've moved the function call to the Form's "onSubmit" event. An alternative would be to change your SUBMIT button to a standard button, and put it in the OnClick event for the button. I also removed the unneeded "JavaScript" in front of the function name, and added an explicit RETURN on the value coming out of the function.
In the function itself, I modified the how the form was being accessed. The structure is:
document.[THE FORM NAME].[THE CONTROL NAME] to get at things. Since you renamed your from aye, you had to change the document.myform. to document.aye. Additionally, the document.aye["whichThing"] is just wrong in this context, as it needed to be document.aye.whichThing.
The final bit, was I commented out the event.preventDefault();. that line was not needed for this sample.
EDIT 4 Just to be clear. document.aye["whichThing"] will provide you direct access to the selected value, but document.aye.whichThing gets you access to the collection of radio buttons which you then need to check. Since you're using the "getRadioButtonValue(object)" function to iterate through the collection, you need to use document.aye.whichThing.
See the difference in this method:
function handleClick() {
alert("Direct Access: " + document.aye["whichThing"]);
alert("Favorite weird creature: " + getRadioButtonValue(document.aye.whichThing));
return false; // prevent further bubbling of event
}
Pretty example by Miquel (#32) should be refilled:
<html>
<head>
<script type="text/javascript">
function handleIt(txt) { // txt == content of form input
alert("Entered value: " + txt);
}
</script>
</head>
<body>
<!-- javascript function in form action must have a parameter. This
parameter contains a value of named input -->
<form name="myform" action="javascript:handleIt(lastname.value)">
<input type="text" name="lastname" id="lastname" maxlength="40">
<input name="Submit" type="submit" value="Update"/>
</form>
</body>
</html>
And the form should have:
<form name="myform" action="javascript:handleIt(lastname.value)">
There are a few things to change in your edited version:
You've taken the suggestion of using document.myform['whichThing'] a bit too literally. Your form is named "aye", so the code to access the whichThing radio buttons should use that name: `document.aye['whichThing'].
There's no such thing as an action attribute for the <input> tag. Use onclick instead: <input name="Submit" type="submit" value="Update" onclick="handleClick();return false"/>
Obtaining and cancelling an Event object in a browser is a very involved process. It varies a lot by browser type and version. IE and Firefox handle these things very differently, so a simple event.preventDefault() won't work... in fact, the event variable probably won't even be defined because this is an onclick handler from a tag. This is why Stephen above is trying so hard to suggest a framework. I realize you want to know the mechanics, and I recommend google for that. In this case, as a simple workaround, use return false in the onclick tag as in number 2 above (or return false from the function as stephen suggested).
Because of #3, get rid of everything not the alert statement in your handler.
The code should now look like:
function handleClick()
{
alert("Favorite weird creature: "+getRadioButtonValue(document.aye['whichThing']));
}
</script>
</head>
<body>
<form name="aye">
<input name="Submit" type="submit" value="Update" onclick="handleClick();return false"/>
Which of the following do you like best?
<p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
<p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
<p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
</form>
Everything seems to be perfect in your code except the fact that handleClick() isn't working because this function lacks a parameter in its function call invocation(but the function definition within has an argument which makes a function mismatch to occur).
The following is a sample working code for calculating all semester's total marks and corresponding grade. It demonstrates the use of a JavaScript function(call) within a html file and also solves the problem you are facing.
<!DOCTYPE html>
<html>
<head>
<title> Semester Results </title>
</head>
<body>
<h1> Semester Marks </h1> <br>
<script type = "text/javascript">
function checkMarks(total)
{
document.write("<h1> Final Result !!! </h1><br>");
document.write("Total Marks = " + total + "<br><br>");
var avg = total / 6.0;
document.write("CGPA = " + (avg / 10.0).toFixed(2) + "<br><br>");
if(avg >= 90)
document.write("Grade = A");
else if(avg >= 80)
document.write("Grade = B");
else if(avg >= 70)
document.write("Grade = C");
else if(avg >= 60)
document.write("Grade = D");
else if(avg >= 50)
document.write("Grade = Pass");
else
document.write("Grade = Fail");
}
</script>
<form name = "myform" action = "javascript:checkMarks(Number(s1.value) + Number(s2.value) + Number(s3.value) + Number(s4.value) + Number(s5.value) + Number(s6.value))"/>
Semester 1: <input type = "text" id = "s1"/> <br><br>
Semester 2: <input type = "text" id = "s2"/> <br><br>
Semester 3: <input type = "text" id = "s3"/> <br><br>
Semester 4: <input type = "text" id = "s4"/> <br><br>
Semester 5: <input type = "text" id = "s5"/> <br><br>
Semester 6: <input type = "text" id = "s6"/> <br><br><br>
<input type = "submit" value = "Submit"/>
</form>
</body>
</html>
Remove javascript: from onclick=".., onsubmit=".. declarations
javascript: prefix is used only in href="" or similar attributes (not events related)