bootbox confirm: form not submitted on enter key press - javascript

I'm using bootbox to show a custom form to the user. Afterwards that form is used to modify the UI. Everything works fine, if I press the "Ok" button in the bootbox dialog. Pressing the ENTER button without touching the form (all values on default) also works properly. But if I put focus on one of my input fields and then press enter, my page just resets as if I pressed F5.
Can this be fixed?
My code:
bootbox.confirm({
message: "<form id='newGameForm' action=''>\
Playlist ID: <br> \
<input type='text' name='playlistID' size='35'/><br>\
Ruleset: <br>\
<input type='radio' name='rules' value='classic' checked> Classic\
<input type='radio' name='rules' value='adv'> Advanced\
</form>",
callback: function (result) {
if (result) {
let newGameParams = $('#newGameForm').serializeArray().reduce(function (obj, item) {
obj[item.name] = item.value;
return obj;
}, {});
initGame(newGameParams);
}
}
});
Edit: I found out that pressing enter while focusing the form is circumventing the bootbox's submit and instead uses the form's own submit. This adds ?playlistID=ABC123&rules=classic to the url and reloads the page. Can I somehow reroute the submit?

This isn't how the confirm helper is intended to be used - your use-case pretty much requires you to use the dialog helper. At a minimum, to make what you have probably work, you would need to capture the onsubmit event of the form you're inserting into the dialog.
Here's an example. I also moved your form out to a template script tag, since it makes the rest cleaner:
Template:
<script type="text/template" id="form-template">
<form id="newGameForm" action="">
Playlist ID: <br>
<input type="text" name="playlistID" size="35"><br>
Ruleset: <br>
<label><input type="radio" name="rules" value="classic" checked> Classic</label> <br>
<label><input type="radio" name="rules" value="adv"> Advanced</label> <br>
</form>
</script>
JavaScript:
var template = $('#form-template').html();
var $dialog = bootbox.confirm({
message: template,
callback: function (result) {
if (result) {
let newGameParams = $('#newGameForm').serializeArray().reduce(function (obj, item) {
obj[item.name] = item.value;
return obj;
}, {});
initGame(newGameParams);
}
}
});
$dialog.on('shown.bs.modal', function(e){
var $form = $('#newGameForm');
$form.on('submit', functino(fe){
fe.preventDefault();
$dialog.find('.btn-primary').trigger('click');
});
});
This only works if you do not override the btn class on the confirm button, but as-is, basically triggers a click on the confirm button when the embedded form is submitted. This example hooks into the form's submit event on the shown.bs.modal event (that link is for Bootstrap 4, but the same event is available in Bootstrap 3).

Related

Dynamic button enable knockout js based on error group

I have a text box and a button. When the text box is empty, I need the button to be disabled and when I start typing in the text box, I want the button to be enabled.
Currently, after inputing some text in the text box, the button is enabled the moment I focus out of the text box. But I want this to be enabled the moment is text box is not empty. I am using knockout.js and both my text box and the button are observables.
I have nore than 1 text field and I want to enable if all fields are not empty. If any field is empty, without loosing focus, I want to disable the button
Here's my code:
var email = ko.observable({ emailField: ko.observable().extend({ email:
true, required: { param: true, message: FILL_FIELD } })), enableButton
= ko.observable(), errorGroup = ko.validation.group([emailField]);
<input type="text" data-bind="value:emailField" />
<button data-bind="enable: enableButton>Press Next to enter password</button>
You have two options:
Use textInput for KO 3.2.0 and higher; or
Use value alongside valueUpdate: 'afterkeydown' for lower versions;
Both make sure your view model is updated immediately after key presses, cascading to other bindings like enable.
The thing that complicates your question is that you've got validation going on, and you want the validation to wait until focus exits, so having the values update continuously with your typing is not a solution.
Instead, you could watch input events separately, to keep track of which of your required fields are empty. watchForEmpty is a factory that takes an observable and returns a Knockout event handler. It sets up the initial state of the list of empties, and the event handler maintains it. The button is enabled when the list of empties has no entries.
vm = {
empties: ko.observableArray(),
thing: ko.observable('prefilled'),
thing2: ko.observable(),
watchForEmpty: function(observable) {
var initVal = observable();
if (initVal === '' || initVal === undefined) {
vm.empties.push(observable);
}
return function(context, event) {
var el = event.target;
if (el.value === '') {
vm.empties.push(observable);
} else {
vm.empties.remove(observable);
}
};
}
};
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input data-bind="value: thing, event: {input: watchForEmpty(thing)}" />
<input data-bind="value: thing2, event: {input: watchForEmpty(thing2)}" />
<button data-bind="enable: empties().length === 0">Go</button>
<div data-bind="text: thing"></div>
<div data-bind="text: thing2"></div>

Submit button is refreshing the page

I have a form inside of an mvc project and sending the inputs with post method to the controller. Everything is good if I use a "button", but it keeps refreshing the page if I change it to "submit".
html:
<form role="form" id="login">
<div class="form-group">
<input type="text" class="form-control border-purple" id="postCode" placeholder="Postcode" value="3208SC">
</div>
<div class="form-group">
<input type="text" class="form-control border-purple" id="huisNummer" placeholder="Huisnummer" value="20">
</div>
<div class="form-group">
<input type="email" class="form-control border-purple" id="eMail" placeholder="EMail" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-zoeken" id="btnZoeken">#ReinisResource.SidebarButton</button>
</div>
</form>
and this is my js code:
$("#login").submit(function() {
$("#mapStuff").empty();
$("#items").empty();
$("#historie").empty();
var selectedEmp = $(".drpDown :selected").text();
var postCodex = $("#postCode").val();
var huisNummerx = $("#huisNummer").val();
var eMailx = $("#eMail").val();
$("#empName").html(selectedEmp);
$.post("/Home/GetAddressCount", { postCode: postCodex, huisNumber: huisNummerx, eMail: eMailx }, function (response) {
if (response.Count === 0) {
$("#pers-info").hide();
$("#btn-section").hide();
$("#multipleAdd").hide();
document.getElementById('inCorrectInfo').click();
} else {
$("#employeesList").hide();
$("#pers-info").show();
var houseInfo1 = response.Straat + " " + huisNummerx;
var houseInfo2 = postCodex + " " + response.Woonplaats;
$("#perceelInfo").html(houseInfo1 + "<br>" + houseInfo2);
$("#meldingMaken-btn").addClass("active");
$("#historie-btn").removeClass("active");
if (response.Count === 1) {
$("#multipleAdd").hide();
reinis.ShowMapStuff();
reinis.ShowItemStuff();
} else {
reinis.ShowMultipleAddress();
}
}
});
});
If you ask me why I need to change it to "submit" from "button" I wanted to add Jquery validation. And I think submit is better to use it for good coding.
Thanks in advance
Since it is a submit event, it will submit unless you do preventDefault or return false, as i can see you need to '$.post` .
So it would be like this.
$("#login").submit(function(event){
event.preventDefault();
// followed by your code for $.ajax
});
More info- http://www.w3schools.com/jquery/event_preventdefault.asp
The event.preventDefault() method stops the default action of an element from happening.
For example: Prevent a submit button from submitting a form ( this is your case).
The default behavior of the <submit> and <button> element is to submit the form and redirect to another location. In order to prevent the page from being reloaded, make sure to prevent that behavior:
$("#login").submit(function(e) {
e.preventDefault();
// Your code here
});
A slightly less convenient method is to use return false, but you have to be careful because it is simply the shorthand of e.stopPropagation() and e.preventDefault(). It will prevent events from bubbling up, so if you are sniffing for events higher up in the DOM tree that originate from the #login element they will be lost.
Also, return false;, unlike e.preventDefault() has to be placed on the last line of the function so that it doesn't stop the function from being executed midway, i.e.:
$("#login").submit(function(e) {
// Your code here
// Last line
return false;
});
Well, that's what a submit button does :)
You can override this behavior by preventing the default behavior of the event when handling the submit event of the form:
$("#login").submit(function(e) {
e.preventDefault();
// the rest of the code
});
Ideally, in order to achieve graceful degradation, the submit button (and the form in general) should still perform the necessary actions for the application by way of posting the form and reloading the page. So the form should have an action which invokes the server-side operation being invoked.
Then the JavaScript code would override that behavior (using the above method) and provide a more UX-friendly AJAX approach to the operation being invoked.
Both should work, so that JavaScript isn't required in order to use the application.

Preventing form submission after validation by parsley.js

I have used parsley.js many times and have literally copied the code from my last use of parsley.
However, every time I submit the form the page refreshes. preventDefault seems to work on my other pages and stops the page from refreshing but for some reason when I tried now it won't work. Can anyone figure out why not?
<script>
$(function(){
$("#register_signup").submit(function(e){
e.preventDefault();
var form = $(this);
if ($('#rform').parsley( 'isValid' )){
alert('valid');
}
});
});
</script>
<form id='rform' name='rform' data-parsley-validate>
<input id='reg_password' class='register_input' type='text' autocomplete="off" data-parsley-trigger="change" placeholder='Password' required>
<input id='reg_cpassword' class='register_input' type='text' name="reg_cpassword" placeholder='Confirm password' data-parsley-equalto="#reg_password" required>
<input id='register_signup' type="submit" onClick="javascript:$('#rform').parsley( 'validate' );" value='Sign Up' />
</form>
You are binding the submit event to a input element. If you check the jquery $.submit() documentation, it states that:
The submit event is sent to an element when the user is attempting to submit a form. It can only be attached to <form> elements. Forms can be submitted either by clicking an explicit <input type="submit">, <input type="image">, or <button type="submit">, or by pressing Enter when certain form elements have focus.
This is your main problem and this is why alert will never be displayed (in fact, that code is never executed).
I would also change a few things:
$('#rform').parsley( 'validate' ) should be $('#rform').parsley().validate(), assuming you are using Parsley 2.*
$('#rform').parsley( 'isValid' ) should be $('#rform').parsley().isValid().
Use $.on() instead of $.submit().
Remove onClickfrom the register_signup element. Since you are already using javascript, I would do this directly in the javascript code instead of onclick. This is more a personal preference.
So, your code will be something like this:
<form id='rform' name='rform'>
<input id='reg_password' class='register_input' type='text' autocomplete="off"
data-parsley-trigger="change" placeholder='Password' required>
<input id='reg_cpassword' class='register_input' type='text' name="reg_cpassword"
placeholder='Confirm password' data-parsley-equalto="#reg_password" required>
<input id='register_signup' type="submit" value='Sign Up' />
</form>
<script>
$(document).ready(function() {
$("#rform").on('submit', function(e){
e.preventDefault();
var form = $(this);
form.parsley().validate();
if (form.parsley().isValid()){
alert('valid');
}
});
});
</script>
if you are using parsely 2 you can try this
$(function () {
//parsely event to validate form -> form:valiate
$('#rform').parsley().on('form:validate', function (formInstance) {
//whenValid return promise if success enter then function if failed enter catch
var ok = formInstance.whenValid()
//on success validation
.then(function(){
alert('v');
formInstance.reset();
})
//on failure validation
.catch(function(){
formInstance.destroy();
});
$('.invalid-form-error-message')
.html(ok ? '' : 'You must correctly fill *at least one of these two blocks!')
.toggleClass('filled', !ok);
// console.log(formInstance);
if (!ok)
formInstance.validationResult = false;
console.log(formInstance);
});
//parsely event to submit form -> form:submit
$('#rform').parsley().on('form:submit', function (formInstance) {
// if you want to prevent submit in any condition after validation success -> return it false
return false;
});
//default submit still implemented but replaced with event form:submit
$('#rform').submit(function () {
alert('dd');
});
});
for more details parsely documentation check Form with examples and events
When you apply data-parsley-validate to your form, you don't need to apply javascript to form to stop submit until all validation run.
But if you applying javascript return false when parsely() not valid.
And just make sure you have include parsley.js code file.

javascript - why doesnt this work?

<form method="post" action="sendmail.php" name="Email_form">
Message ID <input type="text" name="message_id" /><br/><br/>
Aggressive conduct <input type="radio" name="conduct" value="aggressive contact" /><br/><br/>
Offensive conduct <input type="radio" name="conduct" value="offensive conduct" /><br/><br/>
Rasical conduct <input type="radio" name="conduct" value="Rasical conduct" /><br/><br/>
Intimidating conduct <input type="radio" name="conduct" value="intimidating conduct" /><br/><br/>
<input type="submit" name="submit" value="Send Mail" onclick=validate() />
</form>
window.onload = init;
function init()
{
document.forms["Email_form"].onsubmit = function()
{
validate();
return false;
};
}
function validate()
{
var form = document.forms["Email_form"]; //Try avoiding space in form name.
if(form.elements["message_id"].value == "") { //No value in the "message_id"
box
{
alert("Enter Message Id");
//Alert is not a very good idea.
//You may want to add a span per element for the error message
//An div/span at the form level to populate the error message is also ok
//Populate this div or span with the error message
//document.getElementById("errorDivId").innerHTML = "No message id";
return false; //There is an error. Don't proceed with form submission.
}
}
}
</script>
Am i missing something or am i just being stupid?
edit***
sorry i should add! the problem is that i want the javascript to stop users going to 'sendmail.php' if they have not entered a message id and clicked a radio button... at the moment this does not do this and sends blank emails if nothing is inputted
You are using
validate();
return false;
...which means that the submit event handler always returns false, and always fails to submit. You need to use this instead:
return validate();
Also, where you use document.forms["Email form"] the space should be an underscore.
Here's a completely rewritten example that uses modern, standards-compliant, organised code, and works:
http://jsbin.com/eqozah/3
Note that a successful submission of the form will take you to 'sendmail.php', which doesn't actually exist on the jsbin.com server, and you'll get an error, but you know what I mean.
Here is an updated version that dumbs down the methods used so that it works with Internet Explorer, as well as includes radio button validation:
http://jsbin.com/eqozah/5
You forgot the underscore when identifying the form:
document.forms["Email_form"].onsubmit = ...
EDIT:
document.forms["Email_form"].onsubmit = function() {
return validate();
};
function validate() {
var form = document.forms["Email_form"];
if (form.elements["message_id"].value == "") {
alert("Enter Message Id");
return false;
}
var conduct = form.elements['conduct']; //Grab radio buttons
var conductValue; //Store the selected value
for (var i = 0; i<conduct.length; i++) { //Loop through the list and find selected value
if(conduct[i].checked) { conductValue = conduct[i].value } //Store it
}
if (conductValue == undefined) { //Check to make sure we have a value, otherwise fail and alert the user
alert("Enter Conduct");
return false;
}
return true;
}
return the value of validate. Validate should return true if your validation succeeds, and false otherwise. If the onsubmit function returns false, the page won't change.
EDIT: Added code to check the radio button. You should consider using a javascript framework to make your life easier. Also, you should remove the onclick attribute from your submit input button as validation should be handled in the submit even, not the button's click
Most obvious error, your form has name attribute 'Email_form', but in your Javascript you reference document.forms["Email form"]. The ironic thing is, you even have a comment in there not to use spaces in your form names :)

Modal box + checkbox + cookie

I would like to achieve the following:
On homepage load, display modal box
Within modal box, display a form with a single mandatory checkbox
On checking the checkbox, hit submit and close the modal box, proceed to homepage
Remember this checkbox tick preference using a cookie
On a users return to the homepage, if they have checked the checkbox,
the modal box won't display
I've been getting somewhere with this:
http://dev.iceburg.net/jquery/jqModal
In that I can get the modal box displaying on page load, but I can't work out how to get the form to make the checkbox mandatory and close the box. I also don't know where to start when setting a cookie.
Any pointers would be much appreciated.
Thanks
EDIT: to include code:
Index.html - to display modal box on page load
$().ready(function() {
$('#ex2').jqm({modal: 'true', ajax: '2.html', trigger: 'a.ex2trigger' });
setTimeout($('#ex2').jqmShow(),2000);
});
2.html - modal box content loaded via ajax
function validate(frm) {
if (frm.checkbox.checked==false)
{
alert("Please agree to our Terms and Conditions.");
return false;
}
}
<form action="" method="POST" onSubmit="return validate(form);" name="form">
<input type="checkbox" name="checkbox" id="checkbox" value="1"> I hereby agree to all Terms and Conditions</a>
<input type="submit" value="Submit">
</form>
Load the jquery cookie plugin to allow to set/read cookies: http://plugins.jquery.com/project/cookie
then.. something like this below. Untested, but you get the idea
index.html:
$().ready(function() {
if (!$.cookie('agreed_to_terms'))
{
$('#ex2').jqm({modal: 'true', ajax: '2.html', trigger: 'a.ex2trigger' });
$('#ex2').jqmShow();
}
});
2.html:
$().ready(function()
{
$('#agreeFrm').submit(function(e)
{
e.preventDefault();
if ($(this).find('input[name=checkbox]').is(':checked'))
{
$.cookie('agreed_to_terms', '1', { path: '/', expires: 999999 });
$('#ex2').jqmHide();
}
});
});
<form id="agreeFrm" action="" method="POST" name="form">
<input type="checkbox" name="checkbox" id="checkbox" value="1"> I hereby agree to all Terms and Conditions</a>
<input type="submit" value="Submit">
</form>
I used a JQuery plugin not long ago called SimpleModal
I was very impressed with how easy it was. On the modal I had multiple checkboxes and to carried the values of the checkboxes back to the page the modal was on after a submit button was hit.
All the info and demos are on the SimpleModal homepage
It works, finally!
I was missing the callback when the cookie exists and these tics '' around the value of the cookie.
Here is how it looks like. Please, let me know if there is some obvious mistake.
(many thanks for your support)
function confirm(msg,callback) {
$('#confirm')
.jqmShow()
.find('p.jqmConfirmMsg')
.html(msg)
.end()
.find(':submit:visible')
.click(function(){
if(this.value == 'Proceed'){
$.cookie("agreed_to_terms", '1', { expires : 1, path: '/' }); //set cookie, expires in 365 days
(typeof callback == 'string') ?
window.location.href = callback :
callback();
}
$('#confirm').jqmHide();
});
}
$().ready(function() {
$('#confirm').jqm({overlay: 88, modal: 'true', trigger: false});
// trigger a confirm whenever links of class alert are pressed.
$('a.confirm').click(function() {
if ($.cookie('agreed_to_terms') == '1'){window.location.href = callback =
callback()
//they already have cookie set
}else{
confirm('About to visit: '+this.href+' !',this.href);
}
return false;
});
});// JavaScript Document

Categories

Resources