Kube modal closes when pressing enter in form - javascript

I'm using a modal from the Kube CSS & JS framework (6.5.2) with a form inside it. When I hit enter, the modal closes without submitting the form.
Edit: this doesn't happen when focused on password or search inputs - changing the type from 'text' to 'password' fixes the issue.
<!DOCTYPE html>
<html>
<head>
<title>Basic Template</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Kube CSS -->
<link rel="stylesheet" href="dist/css/kube.css">
</head>
<body>
<h1>Hello, world!</h1>
<div id='ui-modal-test' class='modal-box hide'>
<div class='modal' style='width:95%'>
<span class='close'></span>
<div class='modal-header'>Modal Form Test</div>
<div class='modal-body'>
<form id="ui-modal-form">
<input type="text" name="field1">
<input type="text" name="field2">
<input type="text" name="field3">
<button>Apply</button>
</form>
</div>
</div>
</div>
<button data-component="modal" data-target="#ui-modal-test">Open</button>
<!-- Kube JS + jQuery are used for some functionality, but are not required for the basic setup -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="dist/js/kube.js"></script>
</body>
</html>
JS:
$('#ui-modal-form').on('submit', function(event){
event.preventDefault(); // modal still closes before submitting form
var field1 = $(this).find('input[name=field1]').val().toLowerCase();
var field2 = $(this).find('input[name=field2]').val();
var field3 = $(this).find('input[name=field3]').val();
$.post('/post.php', {
field1: field1,
field2: field2,
field3: field3,
}, function(response){
var response = JSON.parse(response);
});
});
I'd like the form to submit when the user hits enter on any of the inputs, without closing the modal box.

I had no idea about Kube, but I tried what you said, that was an issue. Then I opened the kube.js file in dist folder to check out the modal.
I found this specific function to be the cause at line number 2167 -
handleEnter: function(e)
{
if (e.which === 13)
{
e.preventDefault();
this.close(false);
}
}
13 is the code for Enter key event. It's by default in kube, I guess. Maybe you can override this, I think there are some functions in it to disable events. If I change the parameter like this this.close(true), it works well.
Hope this gives you the cause of why this is happening.
Kube seems nice :)

<form onSubmit={event => event.preventDefault()}>
<input type="text" name="field1">
<input type="text" name="field2">
<input type="text" name="field3">
<button>Apply</button>
</form>
you can also refer if still not work:
submit isn't required, so in your case I would recommended moving your logic over to beforeSubmit and always return false as this is triggered before the modal closes. Currently, there's no way to manually close the modal, other than triggering the event modal:destroy. This is an example:
var Modal = Backbone.Modal.extend({
template: _.template($('#modal-template').html()),
submitEl: 'button',
beforeSubmit: function() {
// show your awesome loader here
this.model.save(this.model.attributes, success: function() {
this.trigger('modal:destroy');
});
return false;
}
});
Your modal doesn't submit if it doesn't succeed and beforeSubmit is only triggered onEnter and onClick of the button.

$('input[type=text]').keypress(function (e) {
if (e.which == 13) {
e.stopPropagation();
$('form').submit();
}
});

Related

addEventListener redirects to the same page with a '?' at the end of the url

After I click the button or click the send button here's what happens:
HTML super simplified code:
<!DOCTYPE html>
<html>
<body>
<!-- Page Preloder -->
<!-- Header section -->
<header class="header-section">
<form class="header-search-form">
<input id= "searchBarP" type="text" placeholder="Search on divisima ....">
<button id= "searchIconP"><i class="flaticon-search"></i></button>
<script>
var searchBarP = document.getElementById("searchBarP");
searchBarP.addEventListener("searchP",function(){
alert("Trial");
});
</script>
</form>
</header>
<!-- Header section end -->
</body>
</html>
Here what happens before clicking the button:
After:
searchBarP.addEventListener("searchP",function(){
alert("Trial");
});
The first parameter of addEventListener should be an event. You have searchP which is the element. Try putting click instead.
Your button doesn't have a type and the default type, in this case, is "submit". Since you also didn't specify the form's method, it defaults to GET. This method appends all parameters to the URL after a question mark, that's why you see it after clicking the button.
Solution 1:
If you want both the button and the searchbar to perform the same action, listen for the submit event:
<form class="header-search-form" id="form">
<input id="searchBarP" type="text" placeholder="Search on divisima ....">
<button type="submit" id="searchIconP"><i class="flaticon-search"></i></button>
<script>
const form = document.getElementById("form");
form.addEventListener("submit", function(e) {
e.preventDefault();
alert("Trial");
});
</script>
</form>
Solution 2:
Set the button's type to "button" in order to prevent it from submitting the form.
<form class="header-search-form">
<input id="searchBarP" type="text" placeholder="Search on divisima ....">
<button type="button" id="searchIconP"><i class="flaticon-search"></i></button>
<script>
const searchBarP = document.getElementById("searchBarP");
searchBarP.addEventListener("searchP", function() {
alert("Trial");
});
</script>
</form>
Keep in mind, though, that your searchP listener won't work because there's no event called "searchP". If you want to separate the behaviour of clicking the button and hitting "enter" while typing in the search bar, you can do something like this:
<form class="header-search-form">
<input id="searchBarP" type="text" placeholder="Search on divisima ....">
<button type="submit" id="searchIconP"><i class="flaticon-search"></i></button>
<script>
const searchIconP = document.getElementById("searchIconP");
const searchBarP = document.getElementById("searchBarP");
searchIconP.addEventListener("click", function(e) {
e.preventDefault(); //Remove this if you want to submit the form when you click the button
alert("Button click");
});
searchBarP.addEventListener("keydown", function(e) {
if (e.keyCode === 13){
alert("Search bar enter hit");
e.preventDefault(); //Remove this if you want to submit the form when you hit enter while typing in the search bar
}
});
</script>
</form>

how to change the action of submit button after submission

I want to change the submit button to call signout function after the user signed in
<html>
<head>
/* Here I have the links for jQuery and bootstrap so, they are working properly
</head>
<body>
<form onsubmit="signIn(event)">
<input type="text" id="username" />
<input type="password" id="password" />
<input type="submit" id="connect_disconnect">
</form>
</body>
<script type="text/javascript">
function signIn() {
code ....
// Below I just change the caption of the submit button from 'Connect' to
// 'Disconnect'
$("#connect_disconnect").text('Disconnect');
}
</script>
<script type="text/javascript">
function signOut() {
code...
}
</script>
</html>
with the above code, when I click on submit button, it will call the signIn function even when I am already signed in. I want it to call signOut function when I am already signed it. any ideas?
Thanks in advance and please let me know if my question is not clear.
If you apply a "submit" event handler to your form, then run event.preventDefault() you can prevent the form from submitting the native way and you can run any Javascript you want.
Below I've added a code example showing what you could do to capture the event.
I try not to add too much philosophy into my answers, but I've decided to include an example of a linked Javascript file.
HTML
<body>
<form id="theForm">
<input type="text" id="username" />
<input type="password" id="password" />
<input type="submit" id="connect_disconnect">
</form>
<script type="text/javascript" src="/script.js"></script>
</body>
Javascript (script.js)
(function() { // Create closure to avoid global-scoped variables
var theForm = document.getElementById('theForm'); // Select the <form> element
theForm.addEventListener('submit', handleFormSubmission); // Bind event listener.
function handleFormSubmission(event) {
event.preventDefault(); // Keep the form from taking any further native action
if( /* user is signed in */ )
signOut();
else
signIn();
}
function signIn() {
// Sign In Code
}
function signOut() {
// Sign Out Code
}
})(); // End closure

How to prevent form submit when input is focused and enable it when out of focused with vuejs2?

I am working on a form with a vue component that has an autocomplete functionality, I would like to let user select from suggestions. I am handling keyup events for up, down and enter. Unfortunately, when enter is hit, the form is submitted. I would like to prevent form submit if the input field is focused. I have tried using v-on:submit.prevent in the form tag but that disables form submit completely and I need to create an separate form submit function.
You could do it like this. But I don't really know vue so I might be wrong.
window.onload = function() {
new Vue({
data() {
return {
focused: false
}
},
methods: {
onSubmit: function() {
return this.focused;
}
}
}).$mount('#app')
}
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.4/vue.js"></script>
</head>
<body>
<div id="app">
<form v-on:submit="onSubmit">
<input type="text" #focus="focused = true" #blur="focused = false" />
<button :disabled="focused">Submit</button>
</form>
</div>
</body>
</html>

Inserting data in MySQL database using JS

I have this basic HTML page and there is a form to upload data to a MySQL database.
There is also a JavaScript that passes data to the process.php file. Into this file, I have an INSERT query. I use this script because I do not want to reload the page on submit.
Now I have 2 problems:
1) When I send data to the MySQL table (clicking on submit button), the first time 1 data = 1 record inserted and this is correct. If I insert a new data into the input form field, I have 1 data = 2 records equal. The third time, 3 records and so on...
But if I print what is passed by POST with print_r($_POST), I have always one data Array ( [comune] => foo ).
I also tried to use unset() without success.
2) When I click for the first time on submit button, there's no action, I have to click twice.
This is the HTML page with the JS script:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta charset="utf-8" />
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".formValidation").validate({
debug: false,
rules: {
name: "required",
email: {
required: true,
email: true
}
},
messages: {
name: "Please let us know who you are.",
email: "A valid email will help us get in touch with you.",
},
submitHandler: function(form) {
// do other stuff for a valid form
$('.formValidation').on('submit', function () {
$.post('process.php', $(this).serialize(), function(data){
$('#results').html(data);
});
})
}
});
});
</script>
</head>
<body>
<div class="row">
<div class="col-xs-12">
<form id="myform2" class="formValidation" name="myform2" action="" method="post"></form>
<div class="col-xs-12 col-sm-4">
<div class="widget-box">
<div class="widget-body">
<div class="widget-main">
<div>
<label for="form-field-select-1">form</label>
</div>
<hr>
<div class="widget-body">
<div class="widget-main">
<div>
<input type="text" name="comune" id="comune" value="" placeholder="Add something" form="myform2">
<input type="submit" name="submit" value="Submit" class="btn btn-sm btn-success" form="myform2">
<p id="result"></p>
<div id="results"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</body>
</html>
and the process.php
foreach( $_POST as $key => $value ) {
$sql = "INSERT INTO tbl_".$key."(nome_".$key.") VALUES ('$value')";
$result = dbQuery($sql);
unset($key);
unset($value);
}
You have too many submit handlers.
Just do the ajax in the submitHandler callback option of the plugin.
Internally it is already doing the on('submit') so the first time you click it...the handler you wrote to do the ajax is created but isn't sending yet
The next time it will actually send the form twice and add another submit handler. A third click would send 3 times and add another submit handler and so on
submitHandler: function(form) { // fires only when valid
$.post('process.php', $(form).serialize(), function(data) {
$('#results').html(data);
});
}
your submit handlers are stacking one by one.. and each time requests to the php files increases, causing inserting more than once in database.
Use
submitHandler: function (form) {
$.post('process.php', $(this).serialize(), function (data) {
$('#results').html(data);
});
return false;
}
Hope this helps

Submit form data without refreshing entire page

This simple chat works except when I submit the form; the entire page reloads. I need only for the form itself to submit the data to the database and clear the form. The div that displays the output refreshes automatically with no trouble. I have tried every conceivable variation of includes, divs, frames, etc for days. If I separate the form from the page containing the div, it works ...but I need everything on one page.
here is the html:
<% #LANGUAGE = "VBScript" %>
<!-- #INCLUDE VIRTUAL="000_scripts/asp/chat_config.asp" -->
<!-- #INCLUDE VIRTUAL="chat_scripts.asp" -->
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="chat.js"></script>
</head>
<body>
<div id="div_db1">not loading db1</div>
<form name="Send_Chat" id="Send_Chat" action="<% toDB() %>" method="post">
<textarea name="T_Body_Field" id="T_Body_FieldID" onKeyPress="return submitenter(this,event)" ></textarea>
<input type="submit" value="send" onClick="submitform()">
</form>
</body>
</html>
here is the js:
function submitenter(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
if (keycode == 13)
{
myfield.form.submit();
return false;
}
else
return true;
}
function submitForm() {
var frm = document.getElementsByID('Send_Chat')[0];
frm.submit(); // Submit
frm.reset(); // Reset
return false; // Prevent page refresh
}
$.ajaxSetup ({
cache: false
});
$(document).ready(function(){
setInterval(function(){
$('#div_db1').load('viewalldb3.asp');
}, 50);
});
window.onload = function() {
var input = document.getElementById("T_Body_FieldID").focus();
}
Use jquery.post. You can do it on a button click, so
$(":button").click(function(){
$.post({url where data is posted}, formData)
you have to prevent the submit event to bubble up to avoid the default page refresh behavior.
so your code would need to be changed to something like this (i moved your event handler assignment into javascript because it's cleaner)
$('#Send_Chat').on('submit', function(e){
e.preventDefault(); //this prevents the refresh because it cancels the default event bubbling
$.ajax({ //make sure your form data gets to the server ...
type: "POST",
url: <% toDB() %>,
data: $(this).serialize(),
success: function() {
//done - you've submitted your message
}
});
$('#T_Body_FieldID').on("keydown", function() {
if (event.keyCode == 13) {
$('#Send_Chat').submit(); // Submit form code
}
});
and your html
<form name="Send_Chat" id="Send_Chat" action="#" method="post">
<textarea name="T_Body_Field" id="T_Body_FieldID"></textarea>
<input type="submit" value="send">
</form>
I tried all of these suggestions and unfortunately none of them worked for me. I appreciate it though! I finally got it to work by placing the form into an iframe.
Hey can you please try this...
Instead of having
<form name="Send_Chat" id="Send_Chat" action="<% toDB() %>" method="post">
<textarea name="T_Body_Field" id="T_Body_FieldID" onKeyPress="return submitenter(this,event)" ></textarea>
<input type="submit" value="send" onClick="submitform()">
</form>
Have this
<form name="Send_Chat" id="Send_Chat" action="<% toDB() %>" method="post">
<textarea name="T_Body_Field" id="T_Body_FieldID" onKeyPress="return submitenter(this,event)" ></textarea>
<span onClick="submitform()">Send</span>
</form>
This way your button wont do a post back just make sure u style the span with a button look you should be fine after that :) even with your existing code i reckon... give it a crack

Categories

Resources