Check if the button has been pressed after js submit - javascript

I'm trying to check if a form type button has been pressed after i submit the form with javascript:
<script>
function DeleteIt(string){
var pattern = string.indexOf('_');
var prof_nr = string.substr(pattern+1);
var delete = confirm("Want to delete it?");
if( delete == true ){
document.forms['form'].submit();
}else{
alert('Cancel');
}
}
</script>
<form method="POST" name="form">
<input type="button" name="delete" value="Delete" id="prof_'.$row['code'].'" onclick="DeleteIt(this.id);">
</form>
if(isset($_POST['delete'])){
echo 'Pressed';
}
But it doesn't run into the condition though it has been pressed.
I can't use a submit type,because i already have one in the form , which is used for a search field.Whenever i type something and hit enter,it triggers the function,that's why i use button.

You have used so many language keywords as variable names in your code like delete, string.
You can not use reserved words of a programming language as your
variable names.
This is the working code-
<script type="text/javascript">
function DeleteIt(string1){
var pattern = string1.indexOf('_');
var prof_nr = string1.substr(pattern+1);
var delete1 = confirm("Want to delete it?");
if( delete1 == true ){
document.forms['form'].submit();
}else{
alert('Cancel');
}
}
</script>
<form method="POST" name="form">
<button name="delete" id="prof_'.$row['code'].'" onclick="DeleteIt(this.id);">delete</button>
</form>
<?php
if(isset($_POST['delete'])){
echo 'Pressed';
}

I guess a button, which is used to submit a form, will not submit its own value.
Since you do not want the form to be submitted by pressing the enter key, my idea is to add a hidden field which tells you what to do. The following code adds such a hidden field named specialAction, which is normally set to save. When the delete button is pressed, however, its value is changed to delete. In PHP, you would have to check the field's value then:
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
</head>
<body>
<script type="text/javascript">
function DeleteIt(id){
var pattern = id.indexOf('_');
var prof_nr = id.substr(pattern+1);
var deleteVar = confirm("Want to delete it?");
if( deleteVar == true ){
document.forms['form']['specialAction'].value = "delete";
document.forms['form'].submit();
}else{
alert('Cancel');
}
string
}
</script>
<form method="POST" name="form">
<input type="hidden" id="specialAction" name="specialAction" value="save">
<input type="text" name="testPurpose" value="Hit enter after focusing">
<input type="button" value="Delete" name="delete" id="prof_test" onclick="DeleteIt(this.id);">
</form>
<?php
if(isset($_POST['specialAction'])) echo $_POST['specialAction'];
?>
</body>
</html>
A side note: Do not use delete as a variable name, because it is already used as an operator. Also, you should tell the browser to interpret JavaScript using <script type="text/javascript"> and not just <script>.

Related

How do I take user input and link to corresponding HTML page using JavaScript?

So, I have a form on my HTML page, and a separate button that links to the form. My question is: when the user enters a certain input (in this case a string) and clicks on the button, how do I connect the user to a different HTML page based on the corresponding user input from the form? I know I have to use javascript, but any specific code will be extremely helpful. Thanks!
ADDDED MY CODE:
<!doctype html>
<html>
<head>
<title>Home</title>
</head>
<body>
<form id = "user-info" onSubmit="myFunction()">
<div class = "favorite-fruit">
<p>Enter your favorite fruit<br></p>
<input type="text" name="fav-fruit" id = "fruit"><br>
</div>
<div class="favorite-vegetable">
<p>Enter your favorite vegetable<br></p>
<input type="text" name="fav-vegetable" id="vegetable">
</div>
</form>
<a class = "confirm" onSubmit="myFunction()">
<button form= "user-info" type="button" name= "confirm-input">Confirm</button>
</a>
</div>
<script type="text/javascript">
function myFunction(){
var firstFruit = document.getElementById("fruit").innerHTML;
var secondVegetable = document.getElementById("vegetable").innerHTML;
var f = firstFruit;
var s = secondVegetable;
if(f.value == "Apple" && s.value == "Broccoli"){
//GO TO "appleBroccoli.html"
}
else if(f.value == "Grapes" && s.value == "Carrots"){
//GO TO "grapesCarrots.html"
}
else if(f.value == "Strawberry" && s.value == "Kale"){
//GO TO "strawberryKale.html"
}
}
</script>
</body>
</html>
It can be done by taking up the value of input tag like :-
var value = $(element).val();
Then resetting the action attribute of the form tag with the new value like :-
$(formElem).attr("action",value+".html")
I guess this would help u..
Your form, user-info doesnt have a submit button
add <input type = 'submit' name='conform'>Confirm</input> inside the form
Set action and method to the form to the corrosponding target HTML page.
<form action='..target html' method ='get'>
</form>
If the input is brocolli, you can change the form action as
document.getElementById('user-info').action = <new target>

How to verify the elements of a form in Javascript then Move to a PHP page?

I want to verify the inputs by javascrpit function perform() and move to a php page named i.php to save the datas in the databasse.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="i.php" method="post">
<br>
Name <input type="text" name="name" id="name" >
<span id="err"></span>
</br>
<br>
Password <input type="Password" name="Password" id="password">
<span id="perr"></span>
</br>
<br>
Gender
<input type="radio" name="gender" id="gender" value="male">Male
<input type="radio" name="gender" id="gender" value="female">Female
</br>
<br>
Department <select name="department" id="department">
<option>------</option>
<option>ECE</option>
<option>BBA</option>
<option>ENG</option>
</select>
</br>
<br>
<button name="btn" type="button" id="btn" onclick="perform()" >Button</button>
<input type="submit" name="submit" value="Submit">
<input type="reset" name="reset" value="Clear">
</br>
</form>
<script type="text/javascript">
function perform()
{
var name = document.getElementById('name').value;
var pass = document.getElementById('password').value;
var dept = document.getElementById('department').value;
var gender = document.getElementsByName('gender');
var r =3;
if (name.length==0)
{
document.getElementById('err').innerHTML = "name not found";
r++;
}
if (pass.length<=6 || pass.length>=32 )
{
document.getElementById('perr').innerHTML = "password error";
r++;
}
if(r==3)
{
window.location= "i.php";
}
}
</script>
</body>
</html>*
In i.php page i used var_dump to see the datas whether it has been submitted or not. code of the i.php page:
<!Doctype html>
<html>
<head></head>
<body>
<?php
var_dump($_POST);
?>
</body>
</html>
But its showing arry(0) {}
looks like there nothing that has been submitted.
The issue is that you're redirecting with javascript, and losing the entire form and it's data by doing so.
When the form is valid, submit it rather than redirecting
function perform() {
var _name = document.getElementById('name').value;
var pass = document.getElementById('password').value;
var dept = document.getElementById('department').value;
var gender = document.getElementsByName('gender');
var valid = true;
if (_name.length === 0) {
document.getElementById('err').innerHTML = "name not found";
valid = false;
}
if (pass.length <= 6 || pass.length >= 32) {
document.getElementById('perr').innerHTML = "password error";
valid = false;
}
if (valid) {
document.querySelector('form').submit();
}
}
Note that name is not a good name for variables or form elements, as it already exists in window.name, and that a submit button can not be named submit as it overwrites the named form.submit() function
Another option would be to just remove all the javascript, and use HTML5 validation instead.
Use this code:
<form action="i.php" method="post" onsubmit="perform();">
And in javascript make these changes:
if(r!=3) {
alert('please complete the form';
return false;
}
Javascript doesn't send POST headers with window.location!
By using this code, you don't need to use a button, javascript perform() function runs when the submit button is clicked in the form.
If form values are entered truly, javascript perform() does not return and form submits; else, the function returns and prevents submitting the form.
The problem is you are not submitting the form you are just going to a different page with javascript without passing along any variables. so instead of doing
window.location= "i.php";
you should submit the form like so
document.getElementById("formId").submit();
so you should give the form the id formId
The problem is that you are merely redirecting to the i.php page without posting any data. Replace this line in your JS:
window.location = "i.php";
with this
document.getElementsByTagName('form')[0].submit();
This will find the form in your DOM and submit it along with the data that has been input, preserving the values for your action page.
You also need to rename your submit-button for this to work. Otherwise you will not be able to call the submit function on the form programmatically.
<input type="submit" name="submit-btn" value="Submit" />
should do the trick. However, I don't really see the point of the submit button in addition to your validation/submission button.
Full code sample of the solution here: https://jsfiddle.net/dwu96jqw/1/
by press btn you redirect only and your form dont submitted for transfer via _POST
you should change your code :
<form action="i.php" method="post" id ="form1">
and :
if(r==3)
{
form1.submit();
}
window.location will redirect you to the page, to preserve field values return it
if(r==3)
{
return true;
}

Javascript setting value of textbox by function, without getting reset

My goal is to have a text box and a button. If I enter "Hello" in the text box and press the submit button I would like to have see the text box filled with "World.
For the moment the value of the text box will be changed betweeen the
<html>
<body>
<script>
function validateForm() {
var x = document.forms["myForm"]["Input"].value;
if (x == "Hello") {
alert("test");
document.getElementById("Input").value = "World";
alert("test2");
}
}
</script>
<form name="myForm" action="test.html" onsubmit="return validateForm()" method="post">
Input: <input type="text" id="Input"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
The problem is that the form gets submitted right after the validation. So you are redirected to test.html again.
If you don't want that to happen, add event.preventDefault(); to your Event Handler (check out the fiddle to see it working):
<html>
<body>
<script>
function validateForm(event) {
event.preventDefault();
var x = document.forms["myForm"]["Input"].value;
if (x == "Hello") {
alert("test");
document.getElementById("Input").value = "World";
alert("test2");
}
}
</script>
<form name="myForm" action="test.html" onsubmit="return validateForm(event)" method="post">
Input: <input type="text" id="Input"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
You can learn more about event.preventDefault() at MDN.
Just as a sidenote: It is generally better to use addEventListener instead of the onsubmit attribute (Better separation of concerns, you can add multiple event listeners, etc.).
When you submit your page, then the content in the action page will be loaded.
In your case test.html will be loaded.
If you want the value "World" to be shown in the text box on hitting the submit, then return false on your validateForm() method.
Use return false; to stay on the same page and stop form submission.
function validateForm() {
var x = document.forms["myForm"]["Input"].value;
if (x == "Hello") {
document.getElementById("Input").value = "World";
return false;
}
}

Form in JSP Page not Submitting

I have a jsp page which has a form embedded and I'm submitting the form via JavaScript.
When the page has say aroung 10-50 items the submit is working fine but if the page has aroud 500 items or more its not submitting.
After I click the submit button the page just stays in the current page and it just keeps loading.
How can I solve this issue.
A sample code is shown below:
<html>
<script type="text/javascript">
function submitChecked() {
var approveStr="";
var approveArr=new Array();
if(document.frmReleaseDetail.checkBoxVer.length != undefined)
{
for(var i=0; i < document.frmReleaseDetail.checkBoxVer.length; i++)
{
if(document.frmReleaseDetail.checkBoxVer[i].checked)
{
approveStr +=document.frmReleaseDetail.checkBoxVer[i].value + ",";
approveArr.push(document.frmReleaseDetail.checkBoxVer[i].value);
}
}
if(approveStr=="")
alert("Please make a selection by clicking atleast one checkbox");
else
{
document.getElementById("passCheckVerVal").value=approveArr;
document.forms["newForm"].submit();
}
} //end of if checking multiple checkboxes
else //if the page has only one checkbox(version)
{
if(document.frmReleaseDetail.checkBoxVer.checked)
{
window.location = "process.jsp?passCheckVer="+document.frmReleaseDetail.checkBoxVer.value+'&u_trackingRequestID=<%=request.getParameter("u_trackingRequestID")%>';
}
else
alert("Please make a selection by clicking atleast one checkbox");
}
}
</script>
<body>
<%
String newTrackingReqId=request.getParameter("u_trackingRequestID");
%>
<form name=frmReleaseDetail>
//jdbc code
//100's checkbox named checkBoxVer
//button to invoke submitChecked javascript function
</form>
<form name=newForm" id="newForm" action="process.jsp" method="post">
<input type="hidden" name="passCheckVer" id="passCheckVerVal"/>
<input type="hidden" name="u_trackingRequestID" id="u_trackingRequestIDVal" value="<%=newTrackingReqId%>"/>
</form>
</body>
</html>
You need to change the form method to POST.
<form name=frmReleaseDetail method="post">
By default the method is GET. More informations here. You have quantity of data limitation lot smaller in GET.
EDIT :
Code suggestion with only one form :
<html>
<script type="text/javascript">
function submitChecked() {
var checked = false;
for(var i=0; i < document.frmReleaseDetail.checkBoxVer.length; i++)
{
if(document.frmReleaseDetail.checkBoxVer[i].checked)
{
checked = true;
break;
}
}
if((document.frmReleaseDetail.checkBoxVer.length != undefined and checked) or (document.frmReleaseDetail.checkBoxVer.checked))
{
document.forms["frmReleaseDetail"].submit();
}
else
{
alert("Please make a selection by clicking atleast one checkbox");
}
</script>
<body>
<%
String newTrackingReqId=request.getParameter("u_trackingRequestID");
%>
<form id="frmReleaseDetail" name="frmReleaseDetail" action="process.jsp" method="post">
<input type="hidden" name="u_trackingRequestID" id="u_trackingRequestIDVal" value="<%=newTrackingReqId%>"/>
//jdbc code
//100's checkbox named checkBoxVer
//button to invoke submitChecked javascript function
</form>
</body>
</html>
For anyone making noob (newbie) mistakes:
1: Type is "submit" NOT "button"
GOOD/CORRECT:----------------------------------------------
<input type="submit" value="some_button_label" />
BAD/INCORRECT:----------------------------------------------
<input type="button" value="some_button_label" />
2: Submit button needs to be nested inside the form.
GOOD/CORRECT:----------------------------------------------
<form action="cookies-personalize-response.jsp">
SEL_YOUR_FAV_PROG_LANG
<select name="fav_lan">
<option>LANG_01</option>
<option>LANG_02</option>
<option>LANG_03</option>
</select>
<input
type ="submit"
value="some_button_label"
/>
</form>
BAD/INCORRECT:------------------------------------------------
<form action="cookies-personalize-response.jsp">
SEL_YOUR_FAV_PROG_LANG
<select name="fav_lan">
<option>LANG_01</option>
<option>LANG_02</option>
<option>LANG_03</option>
<option>LANG_04</option>
</select>
</form>
<input
type ="submit"
value="some_button_label"
/>
3: Referesh page after fix, view source in browser to make sure actually changed.
As silly as the last answer is, it is actually the one that I got stuck on the longest.

html form with multiple submitbuttons

I have 2 submit buttons in an HTML form.
How can I know which submit button has triggered the JavaScript function?
<script language="javascript" type="text/javascript">
function verifyData(formdata) {
// Here I want to know from which submit button this function is triggered
// I can't use type button instead of submit
// I can't use onclick handler
// I can't use JQuery.. I want to do only with javascript
}
</script>
<form onsubmit="verifyData(this);" method="post">
<input type="submit" value="submit1">
<input type="submit" value="submit2">
</form>
<button value="delete row" id="but1" onclick="disps()">delete row</button>
I want to do different actions based on the different submit buttons clicked.
It is not possible to check the button clicked through the onsubmit event. Instead move the call to verifyData() to the onclick handler of each button. Use return in the onclick call to cancel submission if false is returned by verifyData()
<script language="javascript" type="text/javascript">
function verifyData(button) {
// validate
switch (button.value) {
case "submit1":
// do somehting
break;
case "submit2":
// do somehting
break;
// ...
};
// submit the form
return true;
}
</script>
<form method="post">
<input type="submit" value="submit1" onclick="return verifyData(this);">
<input type="submit" value="submit2" onclick="return verifyData(this);">
</form>
How about putting an onclick event handler on both buttons which will set a variable to say which button was clicked?
like so:
<script language="javascript" type="text/javascript">
function verifyData(formdata) {
alert(btnClicked);
// Here I want to know from which submit button this function is triggered
// I can't use type button instead of submit
}
var btnClicked = 0;
function setSubmit(which) {
btnClicked = which; return true;
}
</script>
<form onsubmit="verifyData(this);" method="post">
<input type="submit" value="submit1" onclick="return setSubmit(1);">
<input type="submit" value="submit2" onclick="return setSubmit(2);">
</form>
Are you allowed to use the jQuery library?
If you can using this you can easily bind to each submit button based on an id.
For example:
<form id="form1" method="post">
<input type="submit" value="submit1" id="submit1">
<input type="submit" value="submit2" id="submit2" >
</form>
<script type="text/javascript">
$("#submit1").click(function(e)
{
// Do stuff when 1 is clicked.
$("#form1").submit();
});
$("#submit2").click(function(e)
{
// Do stuff when 2 is clicked.
$("#form1").submit();
});
</script>
you could also have the buttons as a type of button to avoid any issues, but you should be able to simply return false; to stop the button of type submit from... submitting
Here is how I would do it... Firstly I would use jQuery so you must include that in your document like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
It would also mean your HTML can be simplified to:
<form method="post">
<input type="submit" value="submit1"/>
<input type="submit" value="submit2"/>
</form>
Then you can use jQuery:
<script>
// When the document is ready
$(function(){
// Action performed when a submit button in the form is clicked
$("form[type='submit']").click(function(e){
// Get the value attribute
var val = $(this).val(),
validation_has_passed = false;
// If it is submit1
if(val == "submit1") {
// Validate submit 1
validation_has_passed = true;
// If it is submit2
} else if(val == "submit2") {
// Validate submit 2
validation_has_passed = true;
}
// If all validation is OK submit the form
if(validation_has_passed === true) {
$("form").submit();
}
// Ensure pressing these buttons doesn't submit the form
e.preventDefault();
});
});
</script>

Categories

Resources