My goal is to click a button and upon click show a confirm box using bootbox. If I select ok it should postback, if I click cancel it should do nothing. Currently, when I click the button it posts back before showing the confirm box, so it appears then immediately disappers.
Script
<script>
function DeleteDeliverables(e,myform) {
e.preventDefault();
bootbox.confirm("Are you sure you would like to delete the selected deliverables? They will be permanently deleted", function (result) {
if (result) {
var deliverables = "";
var cbs = document.getElementsByTagName('input');
for (var i = 0; i < cbs.length; i++) {
if (cbs[i].type === 'checkbox') {
if (cbs[i].checked) {
deliverables += cbs[i].value + ',';
}
}
}
deliverables = deliverables.replace(/,\s*$/, "");
document.getElementById("hiddenDeliverable").value = deliverables;
myform.submit();
}
});
}
</script>
Button
<input type="submit" name="submitButton" class="btn btn-default" value="Delete" onclick="DeleteDeliverables(event,this.form)" /></td>
Postback
[HttpPost]
public ActionResult DeliverableManagement(string submit, DeliverableManagementModel model)
{
//omitted
}
You left out the argument when you call DeleteDeliverables(). It should be:
onclick="DeleteDeliverables(event)"
If you check your Javascript console, you'll probably see an error because undefined.preventDefault is not a function. Since you're not preventing the default action, clicking on the submit button submits the form.
You also need to put
document.getElementById("formID").submit();
in the bootbox.confirm() callback function, since preventDefault prevents the normal form submission.
Finally, for that to work, you need to use a different name for the submit button. Change name="submit" to something like name="submitButton". Otherwise, document.getElementById("formID").submit will refer to the button (because input names are properties of the form), not the function that submits the form.
Related
I created some textbox dynamically with javascript.
here is javascript code:
$(document).on('click','#AddHaContactNumberButton',function(e){
e.preventDefault();
var outerDiv = document.getElementById("HaContactDiv");
var textboxDiv = document.createElement('div');
textboxDiv.className = 'inputs';
var input = document.createElement('input');
input.type = "text";
input.setAttribute('name','numbersshowbox[number]');
textboxDiv.appendChild(input);
numberinfoDiv.appendChild(textboxDiv);
outerDiv.appendChild(numberinfoDiv);
});
Now, I want to access these textbox values in php code on submit button click and then save it to database.
here is html code:
<FORM ID="AddFORM" NAME="AddFORM" ACTION="./admin.php" METHOD=POST><br>
<div class="clear">
<INPUT CLASS="button" TYPE=SUBMIT NAME="AddHaContactNumberButton" VALUE="Add" ID="AddHaContactNumberButton">
</div>
<div class="left-text-align relative-position">
<INPUT CLASS="button" TYPE=SUBMIT NAME="AddHaContactButton" VALUE="Save" ID="AddHaContactButton">
</div>
</FORM>
my php code:
if ($AddHaContactButton == "Save") {
$test = $_REQUEST['numbersshowbox[number]'];
}
the problem is $test is null. I searched and found that since javascript is client side and php is server side I cannot get the value in php unless I use ajax request. So I wrote ajax request as below:
$(document).on('click','#AddHaContactButton',function(e){
e.preventDefault();
currentForm = document.getElementById("AddFORM");
var numberarray= currentForm.elements['numbersshowbox[number]'];
if (numberarray != null) {
var arry = [];
for (var i = 0; i < typearray.length; i++) {
arry.push([typearray[i].value, numberarray[i].value]);
$.ajax({
url: 'savePhoneNumbersInDatabase.php',
type: 'GET',
data: { numbersArray: arry},
success: function(data){
currentForm.submit();
}
});
}
});
Now it is working fine but the problem is that I want to save data in database in postback. I mean I want page to be refreshed after clicking submit button.
If your goal is to simply refresh the page after the click event and $.ajax() call, add the following to end of the success callback in the ajax options:
location.reload();
Beyond simply answering your question, I believe it would be best practice to attach the ajax call to the submit event of the form, rather than the click event of the button. Unless there's a compelling reason you're not doing that already. Something like:
$('#AddFORM').submit(<submit handler>)
I am submitting a form using AJAX. The fields are in a partial view that get sent to a controller action. The partial view is in a div that pops up when a button on the main form is clicked. If the user completes the form and clicks the submit button it then the update is performed in the controller action and all is well. However, if the user changes their mind I like to add a cancel button to hide the form. Adding the button and hiding the form works as expected, but the call to the controller action method still occurs. I've tried using
e.preventDefault();
but this hasn't worked.
I've tried using a second JQuery method attached to the cancel id but I can't get this to work.
My JQuery looks like this:
$('#VisitorModal').on('submit', '#visitorform', function (e) {
var data = $(this).serialize();
var url = '#Url.Action("CreateVisitor", "Meetings")';
var text = $('#title').val() + ' ' + $('#firstname').val() + ' ' + $('#surname').val() + ' (' + $('#company').val() + ')'; // a value from the form that you want as the option text
$.post(url, data, function (response) {
if (response) {
$('#VisitorID').append($('<option></option>').val(response).text(text)).val(response);
} else {
dialog.hide();
}
}).fail(function () {
dialog.hide();
});
dialog.hide();
e.preventDefault();
//return false; // cancel the default submit
});
$('#cancel').on('click', function () {
dialog.hide();
});
And here's my action method:
[HttpPost]
public JsonResult CreateVisitor(AppointmentViewModel model)
{
var visitor = new Visitor()
{
Title = model.VisitorTitle,
FirstName = model.VisitorFirstName,
LastName = model.VisitorSurname,
Company = model.VisitorCompany
};
db.Visitors.Add(visitor);
db.SaveChanges();
return Json(visitor.id);
}
And submit & cancel buttons here:
<div class="form-group">
<div class="col-md-offset-2 col-md-5">
<input type="submit" value="Create" class="btn btn-success" id="submit" />
<input type="button" value="Cancel" class="btn btn-warning" id="cancel" />
</div>
</div>
Does anyone have any suggestions that might get this to work as I hope?
Since your form is being loaded dynamically after the initial page has been rendered, you need to use event delegation by using .on() to add a listener to an ancestor that exists when the page is rendered
Instead of
$('#cancel').on('click', function () {
dialog.hide();
});
use
$(document).on('click', '#cancel', function () {
dialog.hide();
});
but replace document with the closest ancestor that exists when the page is first generated.
I trying to change action url on form, by jQuery. I have this code.
<form id='form_a' action='browse.php' method='get'>
<input type="submit" value="Filter" id='but_a'>
</form>
<script>
var def = [];
$('.attr_color').change(function () {
if ($(this).attr('checked')) {
def.push($(this).val());
} else {
def.splice($.inArray($(this).val(), def), 1);
}
color = "&attr_color=" + def.join(",");
if (def.length === 0) {
color = "";
}
$('#form_a').get(0).setAttribute('action', "browse.php?" + color);
});
</script>
When I inspect code by Chrome inspect, form action, is changing, but after the form is send, everything after "browse.php?" disappear.
When you use method="get", all the URL parameters come from the form fields, you can't put URL parameters in the action.
If you want to send additional parameters, you should add hidden input fields to the form, not modify the URL.
That's the GET behavior, see http://www.w3schools.com/tags/att_form_method.asp for more information.
What you want is to redirect your page and append the color variable in your query string.
You can do this in javascript:
window.location.replace("/browse.php?" + color);
i have 8 text fields and two textareas in my form.i am trying to access all of them and check whether they are empty or not.But somehow the javascript i wrote is not working.here is the code:
javascript:
function textboxes(formobj)
{
var ip = formobj.getElementsByTagName('input');
for(var i=0; i<ip.length; i++)
{
if(ip[i].value == "")
{
alert("empty field");
ip[i].focus();
return false;
}
}
}
The id of the form is 'genform' and this is passed as an arguement to the above javascript code while the button is clikced :
HTML:
<input type="submit" name="submit" value="Generate Questions"
onclick="return textboxes('genform'); return false;" />
This would be a lot easier with jQuery. Thats for another day :)
The onclick event handler passes the text 'genform' to your function. You have to grab the DOM element from this.
var ip = document.getElementById(formobj).getElementsByTagName('input');
I have this piece of javascript:
<script type="text/javascript">
function show_confirm()
{
var type = '<%= nameBean.getTxnType() %>';
var old_cd = '<%= nameBean.getCode() %>';
var new_cd = document.getElementById("tbCode").value;
var cd;
if (type == "Update")
{
if(old_cd != new_cd)
{
var response = confirm("Code already exists. Do you want to replace it?");
if (response){
document.NameUpdate.submit();
}
else{
cd = old_cd;
}
}
</script>
and this is what i am doing in my jsp page to invoke this script:
<INPUT TYPE=SUBMIT NAME="action" onclick="show_confirm()" VALUE="Save Changes">
Its working fine when I hit ok.. but my question is how can i pass the value of old_cd back to the bean so it wont update it with the new code that was entered by the user in the tbcode box.. when user hit cancel i want to ignore what value was entered in textbox and not to update that field in database
I'm not entirely clear on the use case here, but here are a couple of answers:
If the question is, "how do I stop the form from submitting when the user hits cancel?", then the answer is, return false in the click handler:
if (response){
document.NameUpdate.submit();
}
else{
cd = old_cd;
return false;
}
If you need to submit the form no matter which one the user clicks, then you probably need to submit the old value in a hidden input field and have a way to tell the server that user hit "cancel" (probably another hidden field), e.g.:
<!-- html -->
<input type="hidden" name="old_cd" value="<%= nameBean.getCode() %>">
<input type="hidden" id="canceled" name="canceled" value="0">
and javascript:
// js snippet
if (response){
document.NameUpdate.submit();
}
else{
document.getElementById("canceled").value = 1;
return true;
}