<form action ="/submit-page/" method='post' class="editable">
<fieldset>
<select name="status" id='status'>
<option value="Submitted">Submitted</option>
<option value="Canceled">Canceled</option>
<option value="Application">Application</option>
</select>
<input type="submit" name="submit" value="SAVE">
</form>
I have a form above: When I click on the drop down value "Canceled" and hit the Save button I want to give alert box with a warning message with a Yes and No button.
If the user cicks on Yes, take him to the submit-page as desired in the form action parameter.
if the user clicks No, stay on the same form page without refreshing the page.
Can this be done in jQuery?
Hmm... theres is a problem with the other answers on here: they don't work against your HTML.
There's a bug in jQuery (I assume it's a bug), where if an element on your form has aname of submit, then triggering the submit event of the form will not work.
You will need to remove the name attribute from your input type="submit" button or simply give it a name other than "submit".
HTML
<form action ="/submit-page/" method='post' class="editable">
<fieldset>
<select name="status" id='status'>
<option value="Submitted">Submitted</option>
<option value="Canceled">Canceled</option>
<option value="Application">Application</option>
</select>
<input type="submit" value="SAVE" name="submit-button"/>
</fieldset>
</form>
jQuery
$('#status').on('change', function() {
var $this = $(this),
val = $this.val();
if (val === 'Canceled' && confirm("are you sure?")) {
$this.closest('form').submit();
}
});
PHP
$submitted = !empty($_POST['submit-button']);
if($submitted)
{
// Submit button was pressed.
}
else
{
// Form was submitted via alternate trigger.
}
Example
Working: http://jsfiddle.net/xixonia/KW5jp/
Not Working: http://jsfiddle.net/xixonia/KW5jp/1/
Edit
You have since updated your question, and this answer is no longer a valid solution for what you are looking for. Instead, look at Chris Platt's answer.
Edit Again
This is a modified version of Chris Platt's answer. It simply waits until the DOM is ready (elements are loaded) before it executes the logic contained within the first $(...).
$(function() { // this first jQuery object ensures that...
/// ... the code inside executes *after* the DOM is ready.
$('form.editable').submit(function(){
if ($('#status').val()=='Canceled') {
if (!confirm('Warning message here. Continue?')) {
return false;
}
}
});
});
$('form.editable').submit(function(){
if ($('#status').val()=='Canceled') {
if (!confirm('Warning message here. Continue?')) {
return false;
}
}
});
yes, it can be done:
$('#status').change(function(){
var val = $(this).val();
if( val == 'Submitted' ) {
$('.editable').submit();
return false;
} else if (val == 'Canceled')
{
var answer = confirm('are you sure');
return false;
} else {
...
}
});
This, as opposed to Chris Pratts solution will do it, as soon as you change the selected value in the dropdown box. His will do it, once you click the submit button.
The most direct method to intercept the form submission in jQuery is like this:
$("form.editable").submit(function(){
if(confirm("Really submit the form?")) {
return true;
} else {
return false; //form will not be sumitted and page will not reload
}
});
See http://jqapi.com/#p=submit for more detail.
Related
Is it possible to submit a form by clicking a div-element as if it was submitted by the submit button?
So that this PHP works:
if(isset($_POST["share"])) { /* do something*/ }
Form:
<form id="form" action="publish.php" method="POST">
<textarea name="description" maxlength="500">Description...</textarea>
<input type="submit" name="share" value="Share" />
</form>
This does NOT post the share value, $_POST['share'].
if($(".post-form").length){
$(".post-form").click(function(event) {
$("#form").submit();
return false;
});
}
Yes this is possible by using the .submit() function. You can use it like so:
// Wait until the document has been fully loaded
$(document).ready(function() {
// Bind a click event to your element
$('div').click(function(event) {
// Submit the form
// The callback should add a hidden field with the name "share"
$('form').submit(function(eventObj) {
$('<input />').attr('type', 'hidden')
.attr('name', "share")
.attr('value', "Share")
.appendTo('form');
return true;
});
});
});
You can find more information here
Demo: jsfiddle
Set an id for submit button:
<input type="submit" name="share" value="Share" id="btn_submit" />
then you can control it in jquery like this:
$("#btn_submit").onclick(function(){
if(condition==true)
{
return true;
}
else
{
return false;
}
});
If the value of the input box for charge_amt is not entered I'm using an onbeforeunload jquery event which notifys the user they didn't enter an amount. After they enter the amount they are allowed to save.
<td><input type="hidden" name="charge_cc" value="0" class="">
<input type="checkbox" id="charge_cc" name="charge_cc" value="1" checked="" class=""> Charge CC? Amount $ <input type="text" id="charge_amt" name="charge_amt" value="523" size="8" maxlength="6"></td>
<script>
$(document).ready(function(){
$("input[type='text'], select, textarea").change(function(){
window.onbeforeunload = function()
{
return "You have not saved an amount to be charged.";
}
});
$("charge_amt").submit(function(){
window.onbeforeunload = null;
});
});
</script>
The second event is for the complete button.
<input type='checkbox' name='reorder_comment_for_CC'> Verify Charge and Leave Comment" ?>
If they go to hit complete but this checkbox hasn't been marked i would like to alert them that they will not be able to complete the event without verifying/checking.
Maybe I should just use two separate events like so:
<script type="text/javascript">
$("#charge_amt").keypress(function() {
if($(this).val().length > 1) {
return "You have not input an amount to be charged.";
} else {
return "Thank you for entering a charge amount, you can now save.";
}
});</script>
You can check both if the user has entered a correct value in charge_amt and if they have checked the checkbox like this. You also seem to be a little confused about the jQuery syntax. You should use #the_id_of_the_element to find a single element. The submit() event is attached to your form not to the field charge_atm.
$("#id_of_your_form").submit(function() {
//Here you can check the checkbox
//This assumes you add the id of the checkbox to be the same as the name
var $checked = $(this).find("#reorder_comment_for_CC").is(":checked");
var $validValue = $(this).find("#charge_amt").val().length > 0;
if (!$checked) {
alert("You haven't verified charge");
return false;//prevent submitting
}
if (!$validValue) {
alert("Invalid value");
return false;
}
return true;
});
I have a form
<div id='formdiv'>
<form action='purchase.php' method="POST" id="purchaseform">
......
<input type="submit" value="Add Purchase" />
</form></div>
After user submits the form..he is first made to confirm the enteries:
$('#purchaseform').submit(function(){
$('#formdiv').hide();
$('#confirmdiv').show();
return false;
});
where the confirm div is:
<div id='confirmdiv'>
data to be confirmed....
<input type="button" value="Confirm" id = "confirmform"/>
<input type="button" value="Cancel" id = "cancelform"/>
</div>
I am trying to submit the form once user clicks on confirm button
$('#confirmform').click(function(){
$('#purchaseform').submit();
$('#formdiv').show();
$('#confirmdiv').hide();
});
But the form is not submitting...anyone knows what am i doing wrong here??
its because when you call the $('#purchaseform').submit(); it will again read your first statement which is
$('#purchaseform').submit(function(){
$('#formdiv').hide();
$('#confirmdiv').show();
return false;
});
try using a hidden input to indicate if the datas are confirmed or not. In your form put a hidden textfield
<div id='formdiv'>
<form action='purchase.php' method="POST" id="purchaseform">
<input type="submit" value="Add Purchase" />
<input type="hidden" name="isconfirm" id="isconfirm" value="0" />
</form></div>
then in your other statement put a condition before you call return false and the other functions
$('#purchaseform').submit(function(){
var confirm = $("#isconfirm").val();
if(confirm == 0) {
$('#formdiv').hide();
$('#confirmdiv').show();
return false; }
});
then change this as well
$('#confirmform').click(function(){
$("#isconfirm").val(1); //change the value to 1
$('#purchaseform').submit();
$('#formdiv').show();
$('#confirmdiv').hide();
});
It's pretty logical that it's not submitting. After all, whenever it tries to submit, it will instead go to your submit event handler, which always returns false. You have to make sure that if the submit comes from your script instead of from the button in the form, it does submit. One way to do that is like this:
var confirmed = false;
$('#purchaseform').submit(function(){
if (!confirmed)
{
$('#formdiv').hide();
$('#confirmdiv').show();
return false;
}
else
{
confirmed = false;
return true;
}
});
$('#confirmform').click(function(){
confirmed = true;
$('#purchaseform').submit();
$('#formdiv').show();
$('#confirmdiv').hide();
});
This can easily be edited to suit your needs. Another way to do this would be to instead bind the original event to the submit button instead of the actual submit event, but if you do that, you might get into trouble later on if you have a text field in the form and the user presses enter while it's selected. This would then directly submit without confirmation, whereas in the above solution it will neatly ask for a confirmation.
you want to have a confirm dialog, first i think that is better to use the jquery ui dialog plugin http://jqueryui.com/dialog/#modal-confirmation
Here is the code to use :
1- add "display:none" to your confirm dialog
<div id='confirmdiv' style="display:none">
data to be confirmed....
</div>
delete confirm event
$('#confirmform').click ....
2- init your dialog
$( "#confirmdiv" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Confirm": function() {
$('#purchaseform').submit();
},
"Cancel": function() {
$( this ).dialog( "close" );
}
}
});
3- Test your code
4- thats all folks
You are overriding what happens when the form gets submitted in
$('#purchaseform').submit(function(){
$('#formdiv').hide();
$('#confirmdiv').show();
return false;
});
Instead, how about you use
$('#purchaseform').find(":submit").click(function(e){
$('#formdiv').hide();
$('#confirmdiv').show();
return false;
}
Or, of course, you can set an ID on the submit button and use that.
That's because your $('#confirmform').submit() function invoke the 1st submit function again.
I have a form with number of input type images. I need to replace the webpage location to url of the image when a user clicks any image.
form is like,
<form action='free.php' id='freeForm' method='post' autocomplete="off">
<?
for($j=1;$j<=5;$j++)
{
?>
<input type="image" src="<?=$img;?>" />
<?
}
?>
</form>
$img and $url values from database.
My jquery is like,
$("#freeForm").submit(function()
{
var Form = { };
Form['inputFree'] = $("#inputFree").val();
Form['freeTOS'] = '1';
$('.anchor-url').click(function(e){
e.preventDefault();
alert($(this).attr('href'));
});
$.post('processFree.php', Form, function(data)
{
if(data == "Success")
{
$("#FreeErrors").html('').hide();
swapToPane('paneSuccess');
return;
}
swapToPane('paneFree');
$("#FreeErrors").html(data).show();
});
return false;
});
Now I am getting 'http://au.yahoo.com' when i click each image. But I want to replace 'http://au.yahoo.com' with URL of each image. How can I pass the PHP variable $url to this form?
Any idea?
Thanks!
This should work, if I understood what you were asking for correctly and though I haven't tried it. Basically you bind the click event to each image, and on click it replaces the window location with the value in the src attribute of the input element being clicked on.
$('input[type=image]').click(function(e){
e.preventDefault();
window.location.replace($(this).attr('src'));
});
EDIT
First you should add a class name to your anchor elements:
<form action='free.php' id='freeForm' method='post' autocomplete="off">
<?
for($j=1;$j<=5;$j++)
{
?>
<input type="image" src="<?=$img;?>" />
<?
}
?>
</form>
Your JS:
$('.anchor-url').click(function(e){
e.preventDefault();
window.location.replace($(this).attr('href'));
});
Notice how I added a class to the anchor links. This can be named almost anything. This gives you the ability to select for those elements with that classname only with jQuery using the $('.any-classname') selector.
Though a novice in javascript, I need to take javascript variable (an array) reflecting what a user has done on client side and post it to a PHP server page on submit.
It was suggested that I include this as a value in a hidden field in a form to post to the php page. However, since the JS variable is dynamically created by the user, I can't write to the page for inclusion in the form unless I call a function that refreshes the page. To avoid a double page refresh, I'd prefer to have the submit function both grab the data and simultaneously post it to the php script. AJAX if I understand correctly, should not be needed because I'm okay reloading the page once on submit. I just don't want to reload twice.
The following uses the function suggested by Andrew to set the js variable and post. Th form posts as I get the other hidden variable in the form but I am not getting the variable set by js, possibly because there is a mistake with the naming of the variables.
<html>
<head>
<style type="text/css">
select
{
width:100px;
}
</style>
<script type="text/Javascript">
function moveToRightOrLeft(side)
{
if (side == 1)
{
var list1 = document.getElementById('selectLeft');
var list2 = document.getElementById('selectRight');
}
else
{
var list1 = document.getElementById('selectRight');
var list2 = document.getElementById('selectLeft');
}
if (list1.options.length == 0)
{
alert('The list is empty');
return false;
}
else
{
var selectedItem = list1.options[list1.selectedIndex];
move(list2, selectedItem.value, selectedItem.text);
list1.remove(list1.selectedIndex);
if (list1.options.length > 0)
list1.options[0].selected = true;
}
return true;
}
function move(listBoxTo, optionValue, optionDisplayText)
{
var newOption = document.createElement("option");
newOption.value = optionValue;
newOption.text = optionDisplayText;
listBoxTo.add(newOption, null);
return true;
}
function postData(listBoxID)
{
var options = document.getElementById(listBoxID).options;
for (var i = 0; i < options.length; i++)
window.location = "posttoserver.php?data="+options[i].value;
}
function setTheValue(val) {
var options = document.getElementById(listBoxID).options;
var form = document.forms['myForm'];
hiddenField = oFormObject.elements["data"];
hiddenField.value = "val";
}
</script>
</head>
<body>
<select id="selectLeft" multiple="multiple">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>
<button onclick="moveToRightOrLeft(2)"><</button>
<button onclick="moveToRightOrLeft(1)">></button>
<select id="selectRight" multiple="multiple">
</select>
<form id="myForm" action="getdata.php" method="get">
<input type="hidden" name="data" />
<input type="hidden" name="mode" value="savedit">
<button onclick="setTheValue(options)">Submit Data</button>
</form>
</body>
</html>
On the other end I have in getdata.php:
<?php
$mode = $_REQUEST['mode'];
$option = $_REQUEST['data'];
echo $mode;
echo $option;
print_r ($option);;
?>
Finally solved it days later with document.getElementById('varname').value
For newbs like me, document.getElementById does not merely retrieve data as you might think and most documentation mentions. It also sets data.
The key is to write the statement backwards and also (as you must do to retrieve a value) put id== into the element you want to set.
If you write var test = document.getElementById('text'); and you have put id="text" in some field, it will retrieve the value of text. That's what the usual documentation mentions. However, if you write:
document.getElementById('varname').value = "dog"
it will insert "dog" into the element that contains id=varname.
While that may be obvious to the more experienced, it certainly confused me.
Following code works.
<html>
<head>
<script>
function Post(data)
{
document.getElementById('varname').value = data
}
</script>
</head>
<body>
<form action = "" method="get">
<input id="varname" type="hidden" name="d">
<button onclick="Post('dog')">Post to Server</button>
</form>
</body>
</html>
You can go ahead and create a form like you normally would with an empty hidden field:
<form id="myForm" action="posttoserver.php" method="get">
<input type="hidden" name="data" />
...
<input type="submit" value="Submit" />
</form>
And you can use a JavaScript function to set the value of the hidden field:
function setTheValue(val) {
var form = document.forms['myForm'];
hiddenField = oFormObject.elements["data"];
hiddenField.value = "val";
}
You can then call the function setTheValue(val) when your button is clicked or whatever.
I hope this helps!
jQuery actually makes this very simple. You have the right idea but using window.location is going to change your page. What you are looking to do is make a async request to another url while you remain on your current page.
http://api.jquery.com/jQuery.ajax/