The JavaScript function in form isn't executed - javascript

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

Related

Execute JS after a certain event

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>

Get the value from the form and insert that value in the table by using JavaScript

I have created simple form and table.. So I need to add values from the form. I have created the code but it is not working.
<html>
<body>
<script>
function clickFunction(){
document.getElementByName('inputvalue').innerHTML = document.getElementByName('name');
}
</script>
<form>
Name: <input type="text" name="name">
<input type="submit" value="Done" onclick="clickFunction()">
</form>
<table border="1">
<tr><td>Data input: </td><td><label name="inputvalue" > null </label></td></tr>
</table>
</body>
</html>
There are few things you have to fix first:
It should be document.getElementsByName, you are missing a 's'.
Since, the submit is in a form element. Once you click it, it will submit the form. So, you should stop it by using return false in the function.
To get the value from the input box, you should add 'value' after document.getElementByName('name'). it should be document.getElementByName('name').value.
I have added e.preventDefault. In-case, it tries to submit. In that case, there is a slight change in HTML.
...
<input type="submit" value="Done" onclick="clickFunction(event)">
...
The corrected source code: https://jsfiddle.net/gy03xz4b/4/
HTML is fine, the js will change a bit:
function clickFunction() {
document.getElementsByName('inputvalue')[0].innerHTML = document.getElementsByName('name')[0].value;
return false;
}
Hope that helps!
Refers:
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName
http://www.irt.org/script/155.htm (What does 'return false' do?)
https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault (e.preventDefault)

Send value of div on form submit

I am trying to submit a form with a couple of different inputs, which all work fine. However, one of the inputs is a textarea (sort of). I had to alter it into a content editable div, mainly because I created my own bold, italic and underline buttons which wouldn't work with normal textareas. The problem is that the form on submit is not sending the text to the php and i was wondering what i could do to get the value of the div in the php.
Here is the "textarea":
<div id="dash_new_shout_textarea" name="dash_new_shout_textarea"
class="dash_new_shout_textarea" contenteditable="true"
placeholder="Write your shout..." name="dash_new_shout_textarea"
value="<?php echo isset($_POST['dash_new_shout_textarea']) ?
$_POST['dash_new_shout_textarea'] : '' ?>"></div>
The form is just a normal form with method=post.
Here is the php:
$newShoutTextarea = $_POST['dash_new_shout_textarea'];
Thanks for the help
I would suggest that you follow the other answers and use jQuery, but since there is no jQuery tag in your question I suppose that I should provide a good non-jQuery solution for you.
HTML
<form onsubmit="prepareDiv()">
<div id="dash_new_shout_textarea" class="dash_new_shout_textarea" contenteditable="true" placeholder="Write your shout..." name="dash_new_shout_textarea" value="<?php echo isset($_POST['dash_new_shout_textarea']) ? $_POST['dash_new_shout_textarea'] : '' ?>"></div>
<input type="hidden" id="dash_new_shout_textarea_hidden" name="dash_new_shout_textarea" />
</form>
Javascript
function prepareDiv() {
document.getElementById("dash_new_shout_textarea_hidden").value = document.getElementById("dash_new_shout_textarea").innerHTML;
}
Your PHP remains the same.
What you can do is this:
<div id="dash_new_shout_textarea"></div>
<input type="hidden" name="dash_new_shout_textarea" id="dash_new_shout_textarea_hidden" />
<script type="text/javascript">
setInterval(function () {
document.getElementById("dash_new_shout_textarea_hidden").value = document.getElementById("dash_new_shout_textarea").innerHTML;
}, 5);
</script>
the problem is that a DIV is not a form element and cannot be posted. If you use some javascript, you could populate a hidden input field with the data and then receive it server side as POST variable
You can add a hidden input to your form and update it with jquery
<div id="dash_new_shout_textarea" name="dash_new_shout_textarea"
class="dash_new_shout_textarea" contenteditable="true"
placeholder="Write your shout..." name="dash_new_shout_textarea"
value="></div>
<form id="target" method="post" action="destination.php">
<input id="textarea_hidden" name="textarea_hidden" type="hidden" value="">
<input type="submit" value="Submit">
</form>
script
$("#target").click(function() {
$("#textarea_hidden").val($("#dash_new_shout_textarea").val());
});
What you can do is use jQuery for this.
DEMO HERE
Proper scenario would be:
*Get value from div and save it into hidden field. *
This has to be done when you submit form:
$(function () {
$("#send").on("click", function () {
$("#hiddenfield").val($("#dash_new_shout_textarea").text());
alert($("#hiddenfield").val());
$("form#formID").submit();
});
});

AJAX function not being called with button onclick function

I have a simple form with 2 input fields and one button. When the button is clicked, the value of the 2 input fields should be sent to the AJAX function to be handled in a servlet. For some reason, the servlet is not being reached. Can anyone see why? I have an almost identical method working with a different form, and I can't see why this one isn't working.
Here is the HTML form code:
<div id="addCourses" class="hidden" align="center" >
<form id="addCourse" name="addCourse">
<input type="text" id="courseID" name="courseID" value="courseID" size="40" /><br />
<textarea rows="5" cols="33" id="courseDesc" name="courseDesc">Description</textarea><br />
<input type="button" value="Add Course" onclick="addCourse(this.courseID.value, this.courseDesc.value);"/>
</form>
</div>
Here is the Script function:
<script type ="text/javascript">
function addCourse(id, descr)
{
var fluffy;
fluffy=new XMLHttpRequest();
fluffy.onreadystatechange=function()
{
if (fluffy.readyState==4 && fluffy.status==200)
{
//do something here
}
};
fluffy.open("GET","ajaxServlet?courseID="+id+"&courseDescription="+descr,true);
fluffy.send();
}
</script>
Because this is the button and not the form
so
this.courseID.value
this.courseDesc.value
returns an error.
You should use
this.form.courseID.value
this.form.courseDesc.value
Second problem is you have a name clash. The form and function are named addCourse. It will lead to problems. Rename one of them to be different.
Running Example
When you use this, as in onclick="addCourse(this.courseID.value, this.courseDesc.value);", I think that would refer to the input element, and therefore the values aren't being passed correctly.
Bind your event handlers in javascript, where they should be, and you can avoid the issue entirely.
HTML:
<input type="text" id="courseID" name="courseID" value="courseID" size="40" /><br />
<textarea rows="5" cols="33" id="courseDesc" name="courseDesc">Description</textarea><br />
<input type="button" id="addCourse" value="Add Course"/>
JS:
document.getElementById('addCourse').onclick = function () {
var fluffy = new XMLHttpRequest();
var id = document.getElementById('courseID').value;
var descr = document.getElementById('courseDesc').value;
fluffy.onreadystatechange=function() {
if (fluffy.readyState==4 && fluffy.status==200) {
//do something here
}
};
fluffy.open("GET","ajaxServlet?courseID="+id+"&courseDescription="+descr,true);
fluffy.send();
};
As epascarello pointed out, you need to change the ID of your form as having two elements with the same ID is not allowed and will cause unpredictable javascript behavior.
Try a fluffy.close; after the if ready state expression.

Calling Javascript from a html form

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)

Categories