I am creating a form such that when the user click the "submit" button, it prevents the default action, serializes a subset of the fields, and then proceeds to submit all of the information via the POST array (PHP).
I am encountering a problem where the form is basically not submitting when I use the .submit() method. When I disable my javascript, the form submits fine (just with the wrong information, as the array is not serialized). But as soon as I re-enable my js, clicking the submit button does nothing except show my test console.log(var) in console. Here is some of my code, hopefully you can see what I am doing wrong. All of the online documentation says to use .submit(), but it doesn't seem to work, no matter what I try.
HTML:
<form id="entryForm" action="add_entry.php" method="post">
<div class="leftDiv">
<input type="text" class="inputFormTitle" name="entryName" placeholder="Name your entry..." />
<span class="regText">
<b>Entry Properties</b>
Specify entry properties, permissions, etc.</span>
<table class="formTable">
<tr>
<th>Parameter</th>
<th>Value</th>
<tr>
<td>Group</td>
<td><select name="group"><option></option><option>Graham Test</option></select>
</tr>
<tr>
<td>Project</td>
<td><select name="project"><option></option><option>Project 1</option><option>Project 2</option></select>
</tr>
<tr>
<td>Protocol</td>
<td>
<select id="protocolloader" name="protocol">
<option></option>
<option>PCR & Gel</option>
<option>Item Storage</option>
<tr>
<td>Permissions</td>
<td><input type="radio" name="permission" value="0">Only I can access this entry</input>
<input type="radio" name="permission" value="1">Only group members can access this entry</input>
<input type="radio" name="permission" value="2">Everyone can access this entry</input>
</select>
</tr>
</table>
<input type="submit" id="submitEntry" style="font-family:Raleway;" class="inputButton" type="button" name="submit" value="Submit Entry" /
<br/>
</div>
<div class="rightDiv">
<input type="text" class="inputFormTitle" id="ppt" placeholder="Please select a protocol" disabled/>
<div class="formHolder" id="protocolForm">
</div>
</div>
<input type="hidden" id="serialInput" name="protocolValues" value="nuttin" />
</form>
And the accompanying javascript:
var entrySubmit = $('#submitEntry');
entrySubmit.on('click', initEntrySubmission);
function initEntrySubmission(e) {
e.preventDefault();
var serializedProtocol = $("#protocolForm :input").serialize();
console.log(serializedProtocol);
$('#serialInput').val(serializedProtocol);
$('#entryForm').submit();
}
PHP Form (which I don't think is the issue but figured I would include it anyways)
<?php // add_entry.php
session_start();
include_once 'creds.php';
$con=mysqli_connect("$db_hostname","$db_username","$db_password","$db_database");
if (isset($_POST['group'])){
$lab = $_SESSION['labname'];
$author = $_SESSION['username'];
$name = $_POST['entryName'];
$group = $_POST['group'];
$protocol = $_POST['protocol'];
$permission = $_POST['permission'];
$array = $_POST['serialInput'];
$filearray = $_POST['fileArray'];
$project = $_POST['project'];
$query = "INSERT INTO data (protocol, name, lab, author, uniquearray, filearray, group, project, permissionflag)
VALUES ('$protocol', '$name', '$lab', '$author', '$array', '$filearray', '$group', 'project', '$permission')";
mysqli_query($con, $query);
mysqli_close($con);
}
?>
I wouldn't normally include so much HTML but I thought maybe I messed something up in there that may be the issue, and I just don't realize it. I tried to take out most of the break and header tags to clean up the code a bit.
Thanks for any help!
Regards.
The documentation of .submit() states, that
Forms and their child elements should not use input names or ids that conflict with properties of a form, such as submit, length, or method. Name conflicts can cause confusing failures.
You have an input that has the name submit.
<input type="submit" id="submitEntry" style="font-family:Raleway;" class="inputButton" type="button" name="submit" value="Submit Entry" />
I tried it with and without that name. It works without!
I found the following to work:
<script>
function initEntrySubmission() {
var serializedProtocol = $("#protocolForm :input").serialize();
alert(serializedProtocol);
$('#serialInput').val(serializedProtocol);
return true;
}
</script>
<form id="entryForm" action="" method="post" onSubmit="return initEntrySubmission();">
...
<input type="submit" id="submitEntry" style="font-family:Raleway;" class="inputButton" value="Submit Entry"/>
</form>
The main things to do are to add an onSubmit to your form tag. The function must return either true or false. Return true will submit the form.
Also, you do need to clean up your HTML, there are select statements in there, without closing tags and your submit button
<input type="submit" id="submitEntry" style="font-family:Raleway;" class="inputButton" type="button" name="submit" value="Submit Entry" /
has no ending >, it also has 2 type attributes type="button" and type="submit"(its both a button and a submit?) and has a name=submit, which is also unnecessary .
You don't have to preventDefault(), the Code will still be run before the Form is submitted.
function initEntrySubmission() {
var serializedProtocol = $("#protocolForm :input").serialize();
console.log(serializedProtocol);
$('#serialInput').val(serializedProtocol);
}
You can try something like below
In HTML just add
<form id="entryForm" action="add_entry.php" method="post" onsubmit="return false;">
And in JS function
function initEntrySubmission(e) {
var serializedProtocol = $("#protocolForm :input").serialize();
$('#serialInput').val(serializedProtocol);
$('#entryForm').removeAttr('onsubmit');
$('#entryForm').submit();
}
Just change:
$('#entryForm').submit();
To:
$('#entryForm')[0].submit();
Also rename your submit element as #Matmarbon has so eloquently explained.
Explanation:
$('#entryForm').submit(); simply triggers the submit event and takes you back to square one.
$('#entryForm')[0].submit(); submits the form ... more like the default action, without triggering the submit event.
Related
I have a multi form page in view:
<?php echo form_open("account"); ?>
// input fields
<input type="submit" name="change-password" value="Change Password"/>
</form>
<?php echo form_open("account"); ?>
// input fields
<input type="submit" name="change-email" value="Change Email"/>
</form>
And in controller I'm checking:
if (!empty($_POST['change-password']))
{
//
}
if (!empty($_POST['change-email']))
{
//
}
$_POST['change-password'] is always null.
So I tried to switch them places and even added third form. Whatever I do, I can't get submit name from FIRST submit form, but can get them from second, and third.
UPDATE:
I have found the bug.
I didn't mention this, but my submit buttons on forms have an id="submit-btn"
and JavaScript that prevent double submit is making all the trouble:
$("form").one('submit', function() {
$('#submit-btn').prop("disabled", true);
});
And I don't understand why, but this is another question.
Add unique hidden fields for both forms and check that fields name in method (here post) in controller.
<?php echo form_open("account"); ?>
// input fields
<input type="hidden" name="first_form" value="first_form"/>
<input type="submit" name="change-password" value="Change Password"/>
</form>
<?php echo form_open("account"); ?>
// input fields
<input type="hidden" name="second_form" value="second_form"/>
<input type="submit" name="change-email" value="Change Email"/>
</form>
if ($_POST['first_form'])
{
// inside first form
}
if ($_POST['second_form'])
{
// inside second form
}
I have a form on my page and want to be able to submit the text box value (partnumber) as a query string in a hyperlink without submitting the form itself ? Is this possible ?
I have done some research and have tried document.getElementById("partnumber").value but am getting the error "Object Required". Code Below.
<form id="form3" name="form3" method="post" action="formpost?rmaid=<%=rmaid%>">
<input name="partnumber" type="text" id="partnumber" size="10" />
<span class="style11">Suggest Link</span>
<input name="invoice" type="text" id="invoice" size="15" />
</form>
I'll set the new page to open in a pop up window and list a series of values in the database but then I need the value selected to come back into the invoice field on the original page. I believe this can be done with JavaScript but I am new to this, can anyone help ?
For those Looking to pass values back I have found this snippet that works...
Put this in the child window
<script language="javascript">
function changeParent() {
window.opener.document.getElementById('Invoice').value="Value changed..";
window.close();
}
</script>
<form>
<input type=button onclick="javascript:changeParent()" value="Change opener's textbox's value..">
</form>
For the input field you should add an OnChange to it. This event should call a function which will then set your link's value.
You can see an example of this here (it uses a button press though and not an input OnChange Event): http://www.java2s.com/Code/JavaScript/HTML/ChangeURLandtextofahyperlink.htm
Edit: Added a Stack Snippet illustrating the solution.
function SetSuggestLink() {
var suggest = document.getElementById('partnumber').value;
document.getElementById('innerSpan').innerHTML =
"Suggest Link: suggest.asp?partnumber=" + suggest;
document.getElementById('QueryLink').href =
"suggest.asp?partnumber=" + suggest;
}
.style11 {
color:black;
}
.style2 {
text-decoration:none;
}
<form id="form3" name="form3" method="post" action="formpost?rmaid=SomeValue">
<input name="partnumber" type="text" id="partnumber" size="10"
OnChange="SetSuggestLink()" /> </br>
<a id="QueryLink" class="style2" href="#">
<span id="innerSpan" class="style11">Suggest Link</span>
</a></br>
<input name="invoice" type="text" id="invoice" size="15" />
</form>
How can I submit all the cloned forms at the same time?
I made a script to clone my form, and I want to submit all the cloned forms. How can I do that?
HTML:
<div id='forms'>
<div class='cform'>
<form id='form' method='POST'>
<input style='width: 80px;' class='hihi' type='submit' name='add_jo' value='Submit all' />
<td><input class='txtedit' placeholder='Job name' type='text' name='jo[]' maxlength='130' /></td>
</form>
</div>
</div>
jQuery
$('.clone').click(function(event) {
event.preventDefault();
var tr = $('.cform:first');
var newTr = tr.clone();
newTr.find(":input").val(''); // find all input types (input, textarea etc), empty it.
newTr.appendTo(tr.parent());
});
Submitting a form is triggering request for new page load, thus you can't submit several forms simultaenously. Try to collect all forms' values in a hidden form to be submitted or use some AJAX to do the job without actually submitting form data.
Alternatively you could clone your form's content to extend the form itself.
<form action="..." method="post">
<div class="cloneable">
<input name="data[]" value="" />
</div>
<button id="extend">Clone</button>
<button type="submit" id="submit">Submit</button>
</form>
Your JS might look like this:
$("#extend").click( function() {
$(".cloneable")
.clone()
.insertBefore( $("#extend") );
} );
I am trying to set-up a form that has 2 buttons, accept and deny. It doesn't seem to be working. Any thoughts on what I should fix?
<form name="iform" method="post" onsubmit="" onreset="" enctype="multipart/form-data" action="formapprovedeny" class="iform">
Form content here.
<input type="button" onclick="submitForm('html_form_approve.php')" class="submit_button" value="Approved" name="Approved" />
<input type="button" class="submit_button" onclick="submitForm('html_form_deny.php')" value="Denied" name="Denied" />
</form>
Here is the script part.
<script>
function submitForm(action)
{
document.getElementById('formapprovedeny').action = action;
document.getElementById('formapprovedeny').submit();
}
</script>
Your Javscript is trying to submit a form with an id of formapprovedeny but your form does not have an id. Try adding id="formapprovedeny" to your form
It should id="formapprovedeny" not action="formapprovedeny"
<form name="iform" method="post" onsubmit="" onreset="" enctype="multipart/form-data" id="formapprovedeny" class="iform">
You have a problem with your naming.
You try to get the form by it's id, but it is not set. It's name is.
You should use either getElementByName or give your form an id.
The type of button must be 'submit' and the value whatever you want, look this:
<input type="submit" class="submit_button" value="Approved" name="Approved" />
<input type="submit" class="submit_button" value="Denied" name="Denied" />
What do you want to achieve using the 2 buttons? What do you expect?
http://jsfiddle.net/xaW5P/
<script>
function submitForm(action)
{
alert('hello submitForm '+action);
document.getElementById('formapprovedeny').action = action;
document.getElementById('formapprovedeny').submit();
}
</script>
if I use your code (added an alert) this seems to work...whatever it should be doing ;)
I am trying to show or hide div after submitting an action. so let say I have textarea and I put "example" there then checked the checkbox. after submitting, the "receipt.php" page must display "example" , and if I unchecked the checkbox and submit, the receipt.php page must hide the "example". I tried searching similar to my problem but I really don't have idea how to solve it. I have this code so far but i dont have any codes in "receipt.php" since I really don't have idea. pls help me
<form method ="POST" action ="receipt.php">
<textarea name ="comment"></textarea><br>
<input type="checkbox" id="checkbox" value ="1" >Show this comment in receipt<br>
<input type ="submit" value ="Print">
</form>
You don't need the server response to recognize if the checkbox was checked unless you have some validation on server side. If using JQuery, you can do this:
$('#checkbox').change(function(){
$('#your_div').toggle();
});
If you want to rely on what your server says you need to return something to your ajax call.
for example {response: true/false}
In Html:-
<form method ="POST" action ="receipt.php">
<textarea name ="comment"></textarea><br>
<input type="checkbox" name="reciept-chk" id="checkbox" value = "1" >Show this comment in receipt<br>
<input type ="submit" value ="Print">
</form>
In receipt.php:
<?php
..//recept.php
if(isset($_POST['reciept-chk'])){
// Write Code example here
}
?>
If you want to validate it client side before posting your value in receipt.php then
you can simply validate by piece of jquery.
$(document).ready(function(){
$('#checkbox').change(function(){
if ($('#checkbox').is(':checked')) {
$("#exampleDiv").show();
} else {
$("#exampleDiv").hide();
}
});
});
Please avoide toggle() as it deprecated in 1.8
Here is the code you'll need in your unique PHP file :
<form method="POST">
<textarea name="comment">
<?php (isset($_POST['checkbox1']) && $_POST['checkbox1'] == '1') ? echo "Example"; : echo ""; ?>
</textarea>
<br>
<label for="checkbox1">Show this comment in receipt</label>
<input type="checkbox" id="checkbox1" name="checkbox1" value="1" />
<br>
<input type="submit" value="Print" />
</form>
Replace what you want in place of "Example".
If you are using javascript only, you might try something like this:
<script>
function show(){
if(form.toggledisplay.checked == false){
document.getElementById('example').style.display = "none";
}
else{
document.getElementById('div').style.display = "block";
}
}
</script>
<form method = "POST" action="receipt.php" onsubmit="show()">
<textarea name = "comment"></textarea><br>
<input type="checkbox" name="toggledisplay" id="checkbox" value = "1" >Show this comment in receipt<br>
<input type = "submit" value = "Print">
</form>
<div id="example" style="display:none;">This is the div you want to show</div>
If you are populating the contents of the div from the receipt.php file, you could make a post request to it, when the onsubmit() function is fired and fill the contents of the div like:
document.getElementById('div').innerHTML = "Result from the get/post request"
Hope this points you in the right direction.