I am using bootbox which I downloaded from http://bootboxjs.com/.
user_update.php is loaded in a div in users.php with ajax.
In user_update.php I have a JavaScript function validateForm(), and below in the same document I have the form which calls this function like so:
<form name= "updateForm" onsubmit="return validateForm()" role="form-horizontal" method="post" action="index.php">
The function bootbox.alert works just fine.
When I use bootbox.confirm I see the dialog opening and closing within a few tenths of a second.
if (roleid != prevroleid) {
bootbox.confirm("Are you sure?", function (result) {
if (result) {
console.log("User confirmed dialog");
} else {
console.log("User declined dialog");
}
});
}
When I test the same function in a div that is not loaded in a div with ajax, then bootbox.confirm works as expected.
EDITED
this is the ajax call:
$(document).on("click", ".gebruiker", function (e) {
e.preventDefault();
//var url = "user_update.php";
//$("#details").load(url)
var idnr = $(this).attr('idnr');
$.ajax({
type: "get",
url: "view/user_update.php",
data: {
variable1: idnr
},
success: function (data) {
//do stuff after the AJAX calls successfully completes
$('#details').html(data);
}
});
});
this is the div it gets loaded in:
<div id="details" class="col-md-6">
</div>
added at 16:43
ValidateFormcode as requested:
<script>
function validateForm()
{
var fullname = $('#fullname').val();
var username = $('#username').val();
var role = document.getElementById("role");
var roleid = role.options[role.selectedIndex].value;
var password1 = $('#password1').val();
var password2 = $('#password2').val();
var prevroleid = $('#prevroleid').val();
if (roleid != prevroleid) {
bootbox.confirm("Are you sure?", function (result) {
if (result) {
console.log("User confirmed dialog");
} else {
console.log("User declined dialog");
}
});
}
if (!fullname)
{
bootbox.alert("Het veld 'Naam' mag niet leeg zijn")
return false;
}
if (!username)
{
bootbox.alert("Het veld 'Gebruikersnaam' mag niet leeg zijn")
return false;
}
if(password1 != password2)
{
bootbox.alert("De waardes in de wachtwoord velden komen niet overeen")
return false;
}
}
</script>
You should prevent the default behaviour of the form when it's not validated.
So validateForm should be like this:
function validateForm(e)
{
var valid = false; // do some validation
if(!valid){
e.preventDefault();
}
}
Elsewise the form gets submitted and the page refreshes, thus closing the confirm dialog.
Instead of using onsubmit="return validateForm()" attribute in the form tag. Put it on the submit button of the form as onclick="return validateForm();return false;"
<input type="submit" onclick="return validateForm();return false;" />
Return true/false from the validateForm() funtion. If true returned then form will be submitted else if false returned form will not be submitted.
Try it. It should work.
Related
I am faced with a problem which is a real disaster. After I click the send button to send variables via Ajax to my PHP page, a form reset will get triggered in success response. But the input values are liked to be cached, so when I click the send button while inputs are empty, it resends the previous inserted values.
Moreover, I have disabled the form submission event to prevent submitting the form.
Here is the sample code:
<body>
<form id="myform">
<input class="area" type="text"></input>
<input class="area" type="text"></input>
<input class="area" type="text"></input>
<button id="add">Add</button>
</form>
<div class="response"></div>
</body>
$(document).ready(() => {
$(document)
.off()
.on("click", "#add", function (e) {
e.preventDefault();
var area = $(".area");
area.each(function (i) {
if ($(this).val()) {
var x = $(this).val();
areadim.splice(i, area.length, x);
}
});
$.ajax({
type: "POST",
url: "addsettings.php",
data: {
area: area,
},
beforeSend: function () {
if (areadim.length == 0) {
alert("fill up all inputs");
currentRequest.abort();
} else if (areadim.length <= area.length) {
$.each(area, function () {
if ($(this).val() < 100) {
alert("input is less than 100");
currentRequest.abort();
}
});
}
},
success: function (response) {
$("#myform").trigger("reset");
$(".response").append(response);
$(".area").val("");
},
});
});
});
I want to print errors to the screen within a div and keep them there until there is a successful transmission. However this will not allow a submission. I can submit if I remove the e.preventDefault() but then the content of the error div flashes and vanishes. Is there a way to do both?
$("#submitButton").click(function (e)
{
e.preventDefault();
$('#message').hide();
//processing errors
if (errorstr !== "") {
var d;
d = document.getElementById("message");
d.innerHTML = errorstr;
$('#message').show();
}
else {
$('#message').hide();
}
}
#using (Html.BeginForm(...)
{
<div id="message"></div>
<input type="submit" name="submitButton" id="submitButton" class="form-input"/>
}
Either use ajax or URL.Action to submit the form.
ajax way:
function submitForm()
{
$.ajax({
url: 'Controller/Action',
data: { } // your data
}).done(function() {
alert('Success');
});
}
Usage:
if (errorstr !== "") {
var d;
d = document.getElementById("message");
d.innerHTML = errorstr;
$('#message').show();
}
else {
submitForm();
$('#message').hide();
} }
URL.Action way:
window.location.href = '#Url.Action("Action", "Controller")/' + data;
i have a live chat messaging system whenever user press enter button it refreshes the page i have tried using prevent default code also but did not worked for me.... here is the code and if there is any problem in the below code please let me know as i'm totally new to website programming
jQuery(document).ready(function() {
jQuery('.btn-success').click(function() {
var form_name = jQuery(this).attr('title');
var obj = jQuery(this);
jQuery(".ajax_indi").show();
switch (form_name) {
case "npost":
var message = jQuery("#message").val();
break;
default:
alert("something went wrong!");
}
if((jQuery(message) == ''))
{
alert("Message Cannot be Empty");
jQuery(".ajax_indi").hide();
return false;
} else {
jQuery(this).attr("disabled", "disabled");
jQuery(this).prop('value', 'Loading...');
jQuery(this).css('cursor', 'default');
}
var str = jQuery("#"+form_name).serialize();
jQuery.ajax({
type: "POST",
url: "chat.php",
data: str,
cache: false,
success: function(html){
jQuery('#chat1').append(html);
obj.attr("disabled", false);
obj.prop('value', 'Post');
obj.css('cursor', 'pointer');
jQuery(".ajax_indi").hide();
document.getElementById(form_name).reset();
}
});
});
});
Edited part
<form id="npost" name="npost">
<input class="form-control" placeholder="Type your message here..."
type="text" name="message">
<input type="hidden" name="id" value="1">
<span class="input-group-btn">
<button type="button" class="btn btn-success" title="npost" >Send</button>
if you want to prevent from submitting the form you can use return false if you want to stop executing the function and stop submitting it
You need to use preventDefault in order to stop form submission on clicking enter because by default form gets submitted when anyone presses enter. So use preventDefault like this:
<script type="text/javascript" >
jQuery(document).ready(function(){
jQuery('.btn-success').click(function(e){ // added e
e.preventDefault(); // added this line
var form_name = jQuery(this).attr('title');
var obj = jQuery(this);
jQuery(".ajax_indi").show();
var message = '';
switch (form_name)
{
case "npost":
var message = jQuery("#message").val();
break;
default:
alert("something went wrong!");
}
if((jQuery(message) == ''))
{
alert("Message Cannot be Empty");
jQuery(".ajax_indi").hide();
return false;
} else {
jQuery(this).attr("disabled", "disabled");
jQuery(this).prop('value', 'Loading...');
jQuery(this).css('cursor', 'default');
}
var str = jQuery("#"+form_name).serialize();
jQuery.ajax({
type: "POST",
url: "chat.php",
data: str,
cache: false,
success: function(html){
jQuery('#chat1').append(html);
obj.attr("disabled", false);
obj.prop('value', 'Post');
obj.css('cursor', 'pointer');
jQuery(".ajax_indi").hide();
document.getElementById(form_name).reset();
}
});
});
});
</script>
Here You should not stop form default action you to prevent enter key default answer here is the code to prevent.
$('#npost').on('keyup keypress', function(e) {
if (e.which== 13) {
e.preventDefault();
return false;
}
});
I have a very simple AJAX form that asks for an email address and sends it to me after submitting.
How can I can I get the form to submit when hitting the enter key?
This runs when user clicks submit button:
<script type="text/javascript">
$(document).ready(function () {
$("#submit_btn").click(function () {
// Get input field values:
var user_email = $('input[name=email]').val();
// Simple validation at client's end
// We simply change border color to red if empty field using .css()
var proceed = true;
if (user_email === "") {
$('input[name=email]').css('border-color', 'red');
proceed = false;
}
// Everything looks good! Proceed...
if (proceed) {
/* Submit form via AJAX using jQuery. */
}
});
// Reset previously set border colors and hide all message on .keyup()
$("#contact_form input, #contact_form textarea").keyup(function () {
$("#contact_form input, #contact_form textarea").css('border-color', '');
$("#result").slideUp();
});
});
</script>
I know this question has been asked before -- I'm having trouble getting the keypress function to work.
I tried this to no avail:
$("#contact_form").keypress(function (e) {
if ((e.keyCode == 13) && (e.target.type != "textarea")) {
e.preventDefault();
// Get input field values
var user_email = $('input[name=email]').val();
// Simple validation at client's end
// We simply change border color to red if empty field using .css()
var proceed = true;
if (user_email === "") {
$('input[name=email]').css('border-color', 'red');
proceed = false;
}
// Everything looks good! Proceed...
if (proceed) {
/* Submit form via AJAX using jQuery. */
}
}
});
The form is #contact_form.
Any help would be would appreciated…
Just bind the submit event to your form, and then the enter key will also work:
$("#contact_form").submit(function (e) {
e.preventDefault();
// Get input field values
var user_email = $('input[name=email]').val();
// Simple validation at client's end
// We simply change border color to red if empty field using .css()
var proceed = true;
if (user_email === "") {
$('input[name=email]').css('border-color', 'red');
proceed = false;
}
if (proceed) {
// Insert the AJAX here.
}
});
And the code is here: http://jsfiddle.net/6TSWk/6/
add new class in every fieldbox or checkbox => class keypressbutton
then replace your code on keypress with this, below :
$(document).on("keypress",".keypressbutton",function(event) {
var keyCode = event.which || event.keyCode;
if (keyCode == 13) {
$("#submit_btn").click();
return false;
}
});
$("#myform").keypress(function(event){
if(event.keycode===13){ // enter key has code 13
//some ajax code code here
//alert("Enter key pressed");
}
});
You have two opening brackets in your if statement and miss a closing bracket. Also, I would change e.target.type. Try this:
$("#contact_form").keypress(function (e) {
if ((e.keyCode == 13) && ($('input[name="email"]').is(':focus'))) {
e.preventDefault();
//get input field values
var user_email = $('input[name=email]').val();
//simple validation at client's end
//we simply change border color to red if empty field using .css()
var proceed = true;
if (user_email === "") {
$('input[name=email]').css('border-color', 'red');
proceed = false;
}
}
});
Instead of using button on click function you can use submit button.
Load the validate.js file
function validateEmail(email)
{
var reg = /^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/
if (reg.test(email))
{
return true; }
else{
return false;
}
}
$("#test-form").validate({
submitHandler: function(form) {
//form.submit();
var email=$("#email").val();
if(email=='' )
{
// Here you can type your own error message
$('#valid').css("display","none");
$('#empty').css("display","block");
return false;
}
if (!(validateEmail(email))) {
$('#empty').css("display","none");
$('#valid').css("display","block");
return false;
}
else {
$.ajax({
url: "signup.php",
type: form.method,
data: $(form).serialize(),
success: function(response) {
}
});
}
}
});
});
Simple way is this:
In HTML codes:
<form action="POST" onsubmit="ajax_submit();return false;">
<b>First Name:</b> <input type="text" name="firstname" id="firstname">
<br>
<b>Last Name:</b> <input type="text" name="lastname" id="lastname">
<br>
<input type="submit" name="send" onclick="ajax_submit();">
</form>
In Js codes:
function ajax_submit()
{
$.ajax({
url: "submit.php",
type: "POST",
data: {
firstname: $("#firstname").val(),
lastname: $("#lastname").val()
},
dataType: "JSON",
success: function (jsonStr) {
// another codes when result is success
}
});
}
<script LANGUAGE="JavaScript">
function confirmSubmit() {
jConfirm('Is the Appointment Confirmed?', 'Confirmation Dialog', function(r) {
if(r) {
return true;
} else {
return false;
}
});
}
</script>
<form name='cancel_form'id='cancel_form' method='POST' action="">
<center>
<input type='submit' name='confirm_appointment' value='Cancel Appointment' onclick='return confirmSubmit();'>
</center>
</form>
<script type='text/javascript'>
var ajax_load = "<img class='loading' src='img/load.gif' alt='loading...' />";
var saveUrl = "<?php echo $this->url(array('controller' => 'appointment', 'action' =>'cancelsave'));?>";
$('#cancel_form').ajaxForm({ success: saveCallbk , url : saveUrl });
function saveCallbk(responseText) {
jAlert(responseText,'Alert Dialog');
if(responseText.indexOf("ERROR")<0) {
$(location).attr('href',redirectUrl);
}
}
</script>
When I submit the form I call this function and use jConfirm from jQuery. I print r. It's printing properly (e.g. true and false), but return false or return true has no effect -- it just shows the pop up and submits the form, and does not wait for confirmation. How to solve this?
The ajaxForm plugin takes care of the submission by itself and it needs a submit button. If I use:
function confirmSubmit() {
var agree=confirm("Is the Appointment Cancelled?");
if (agree) {
return true;
} else {
return false;
}
}
like default javascript it works well
Use type="button" instead of type="submit" and attach this on the click event of your form button.
$('#button').click(function () {
jConfirm('Is the Appointment Confirmed?', 'Confirmation Dialog', function(r) {
if (r) {
$('#form').submit();
}
});
});
What Ivo said.
Your function confirmSubmit should return true or false.
Edit -
I am not familiar with jConfirm, but you may need to return the results from jConfirm, like this.
<script>
function confirmSubmit()
{
return jConfirm('Is the Appointment Confirmed?', 'Confirmation Dialog',
function(r) {
if(r){return true;} else {return false;}
});
}
</script>
if this is the case, you could do away with confirmSubmit() altogether and just say:
$('#form').submit(function() {
return jConfirm('Is the Appointment Confirmed?', 'Confirmation Dialog', function(r) { return r; } );
});
Hope this helps...
Dang that Ivo is GOOD :-) Personally, i do what Ivo has demonstrated. Create an input of type="button", then delegate a click function.
This is how I cancel submit events using JavaScript and jQuery:
First I have a utility function called cancelEvent: (Which I picked up from this blog entry.)
function cancelEvent(e)
{
e = e ? e : window.event;
if(e.stopPropagation)
e.stopPropagation();
if(e.preventDefault)
e.preventDefault();
e.cancelBubble = true;
e.cancel = true;
e.returnValue = false;
return false;
}
Then I'll have the main JavaScript file that will contain code something like this:
function validateForm(e)
{
var validated = true;
/*
Validation code goes here.
If validation fails set validated to false
*/
//If validation fails then at the end I'll want to cancel the submit event
if(validated)
{
return true;
}
return cancelEvent(e);
}
jQuery(document).ready(function()
{
jQuery("#theForm").submit(validateForm);
}