event prevent default not working within VueJS instance - javascript

I'm trying to disable a form submission when the enter key is pressed. The approaches I've tried are listed below with the code and example demo.
EXAMPLE OF PROBLEM HERE
Desired outcome:
Focus on the input, press down -> down -> enter and it should log the index of the record you have selected and stop there.
What's actually happening:
It logs as expected, but then reloads the page immediately as the form submits.
HTML
<form action="/some-action" #submit.stop.prevent="prevent">
<div class="auto-complete" v-cloak>
<div class="ico-input">
<input type="text" name="search" placeholder="Enter text" #keyup.prevent="handleKeypress">
</div>
<ul class="raw auto-complete-results">
<li v-for="r in results" #click="loadSelection($index)" v-bind:class="{'selected': selectedIndex == $index}"><span>{{ r.name }}</span></li>
</ul>
</div>
</form>
JS
var autocomplete = new Vue({
el: '.auto-complete',
data: {
results: [{name: 'swimming1'}, {name: 'swimming2'}, {name: 'swimming3'}, {name: 'swimming4'}, {name: 'swimming5'}, ],
selectedIndex: -1,
},
methods: {
handleKeypress: function(event) {
event.preventDefault();
event.stopPropagation();
var key = event.which;
if ([38, 40].indexOf(key) > -1) //handle up down arrows.
this.arrowNavigation(key);
else if (key == 13) //handle enter keypress
this.loadSelection(this.selectedIndex);
return false;
},
arrowNavigation: function(key, target) {
if (key == 38) //up
this.selectedIndex = this.selectedIndex - 1 < 0 ? 0 : this.selectedIndex - 1;
if (key == 40) //down
this.selectedIndex = (this.selectedIndex + 1) > (this.results.length - 1) ? 0 : this.selectedIndex + 1;
},
loadSelection: function(index) {
if (index < 0 || index > this.results.length)
return false;
var selection = this.results[index];
console.log("loading selection", index,selection);
},
prevent: function(event) {
event.preventDefault();
event.stopPropagation();
return false;
},
}
})
I've tried various syntax approaches on both form/input (switching submit for keyup on the input)
v-on:submit="prevent"
#submit
#submit.stop
#submit.prevent
#submit.stop.prevent="prevent"
I've also tried calling the following from with in the 2 event handlers aswell as returning false from them both.
event.preventDefault()
event.stopPropagation()
The form still triggers a page reload no matter what I try. I can't see anything obviously wrong so I turn to stackoverflow to guide my eyes.
Thanks

This Answer to another question suggests that forms with a single input element always get submitted, not matter what you do.
And indeed adding another input (and hiding it) helped.
https://jsfiddle.net/Linusborg/Lbq7hf1v/1/
<div class="ico-input">
<input type="text" name="search" placeholder="Enter text" #keyup.prevent="handleKeypress">
<input type="text" hidden style="display:none;">
</div>
Browsers are stupid.

Note that, anything outside of the el that you use to reference your Vue instance will not be recognized by vue no matter how correctly you define your event modifiers on your elements.
In your example you are referring to your Vue instance through the .auto-complete element which is a child of the form element which the submit event is bound to by default. Any event modifiers added to your form will never take effect. Try wrapping all your HTML in a div and reference vue through that, like so:
HTML
<div id="app">
<!-- HTML/Vue Directives/Mustache here -->
<form action="/some-action" #submit.stop.prevent="prevent">
... rest of your code ...
</form>
</div>
JS:
var autocomplete = new Vue({
el: '#app',
data: {
... rest of your js code ...
})
Also Vue devtools can be very useful when debugging such situations.

Try this!
<form #submit.prevent>
Works for Vue2

Try #keydown.enter.prevent
I was having the same problem but I was using keyup
<input type="text" #keydown.enter.prevent="doSomething" />
You don't have to have a method either if you just want to stop the form from submitting just put #keydown.enter.prevent without a method.
<input type="text" #keydown.enter.prevent />

Related

How to pass clicked button value to javascript on form submit [duplicate]

I have a .submit() event set up for form submission. I also have multiple forms on the page, but just one here for this example. I'd like to know which submit button was clicked without applying a .click() event to each one.
Here's the setup:
<html>
<head>
<title>jQuery research: forms</title>
<script type='text/javascript' src='../jquery-1.5.2.min.js'></script>
<script type='text/javascript' language='javascript'>
$(document).ready(function(){
$('form[name="testform"]').submit( function(event){ process_form_submission(event); } );
});
function process_form_submission( event ) {
event.preventDefault();
//var target = $(event.target);
var me = event.currentTarget;
var data = me.data.value;
var which_button = '?'; // <-- this is what I want to know
alert( 'data: ' + data + ', button: ' + which_button );
}
</script>
</head>
<body>
<h2>Here's my form:</h2>
<form action='nothing' method='post' name='testform'>
<input type='hidden' name='data' value='blahdatayadda' />
<input type='submit' name='name1' value='value1' />
<input type='submit' name='name2' value='value2' />
</form>
</body>
</html>
Live example on jsfiddle
Besides applying a .click() event on each button, is there a way to determine which submit button was clicked?
I asked this same question: How can I get the button that caused the submit from the form submit event?
I ended up coming up with this solution and it worked pretty well:
$(document).ready(function() {
$("form").submit(function() {
var val = $("input[type=submit][clicked=true]").val();
// DO WORK
});
$("form input[type=submit]").click(function() {
$("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
});
In your case with multiple forms you may need to tweak this a bit but it should still apply
I found that this worked.
$(document).ready(function() {
$( "form" ).submit(function () {
// Get the submit button element
var btn = $(this).find("input[type=submit]:focus" );
});
}
This works for me:
$("form").submit(function() {
// Print the value of the button that was clicked
console.log($(document.activeElement).val());
}
When the form is submitted:
document.activeElement will give you the submit button that was clicked.
document.activeElement.getAttribute('value') will give you that button's value.
Note that if the form is submitted by hitting the Enter key, then document.activeElement will be whichever form input that was focused at the time. If this wasn't a submit button then in this case it may be that there is no "button that was clicked."
There is a native property, submitter, on the SubmitEvent interface.
Standard Web API:
var btnClicked = event.submitter;
jQuery:
var btnClicked = event.originalEvent.submitter;
Here's the approach that seems cleaner for my purposes.
First, for any and all forms:
$('form').click(function(event) {
$(this).data('clicked',$(event.target))
});
When this click event is fired for a form, it simply records the originating target (available in the event object) to be accessed later. This is a pretty broad stroke, as it will fire for any click anywhere on the form. Optimization comments are welcome, but I suspect it will never cause noticeable issues.
Then, in $('form').submit(), you can inquire what was last clicked, with something like
if ($(this).data('clicked').is('[name=no_ajax]')) xhr.abort();
Wow, some solutions can get complicated! If you don't mind using a simple global, just take advantage of the fact that the input button click event fires first. One could further filter the $('input') selector for one of many forms by using $('#myForm input').
$(document).ready(function(){
var clkBtn = "";
$('input[type="submit"]').click(function(evt) {
clkBtn = evt.target.id;
});
$("#myForm").submit(function(evt) {
var btnID = clkBtn;
alert("form submitted; button id=" + btnID);
});
});
I have found the best solution is
$(document.activeElement).attr('id')
This not only works on inputs, but it also works on button tags.
Also it gets the id of the button.
Another possible solution is to add a hidden field in your form:
<input type="hidden" id="btaction"/>
Then in the ready function add functions to record what key was pressed:
$('form#myForm #btnSubmit').click(function() {
$('form#myForm #btaction').val(0);
});
$('form#myForm #btnSubmitAndSend').click(function() {
$('form#myForm #btaction').val(1);
});
$('form#myForm #btnDelete').click(function() {
$('form#myForm #btaction').val(2);
});
Now in the form submition handler read the hidden variable and decide based on it:
var act = $('form#myForm #btaction').val();
Building on what Stan and yann-h did but this one defaults to the first button. The beauty of this overall approach is that it picks up both the click and the enter key (even if the focus was not on the button. If you need to allow enter in the form, then just respond to this when a button is focused (i.e. Stan's answer). In my case, I wanted to allow enter to submit the form even if the user's current focus was on the text box.
I was also using a 'name' attribute rather than 'id' but this is the same approach.
var pressedButtonName =
typeof $(":input[type=submit]:focus")[0] === "undefined" ?
$(":input[type=submit]:first")[0].name :
$(":input[type=submit]:focus")[0].name;
This one worked for me
$('#Form').submit(function(){
var btn= $(this).find("input[type=submit]:focus").val();
alert('you have clicked '+ btn);
}
Here is my solution:
$('#form').submit(function(e){
console.log($('#'+e.originalEvent.submitter.id));
e.preventDefault();
});
If what you mean by not adding a .click event is that you don't want to have separate handlers for those events, you could handle all clicks (submits) in one function:
$(document).ready(function(){
$('input[type="submit"]').click( function(event){ process_form_submission(event); } );
});
function process_form_submission( event ) {
event.preventDefault();
//var target = $(event.target);
var input = $(event.currentTarget);
var which_button = event.currentTarget.value;
var data = input.parents("form")[0].data.value;
// var which_button = '?'; // <-- this is what I want to know
alert( 'data: ' + data + ', button: ' + which_button );
}
As I can't comment on the accepted answer, I bring here a modified version that should take into account elements that are outside the form (ie: attached to the form using the form attribute). This is for modern browser: http://caniuse.com/#feat=form-attribute . The closest('form') is used as a fallback for unsupported form attribute
$(document).on('click', '[type=submit]', function() {
var form = $(this).prop('form') || $(this).closest('form')[0];
$(form.elements).filter('[type=submit]').removeAttr('clicked')
$(this).attr('clicked', true);
});
$('form').on('submit', function() {
var submitter = $(this.elements).filter('[clicked]');
})
You can simply get the event object when you submit the form. From that, get the submitter object. As below:
$(".review-form").submit(function (e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
let submitter_btn = $(e.originalEvent.submitter);
console.log(submitter_btn.attr("name"));
}
In case you want to send this form to the backend, you can create a new form element by new FormData() and set the key-value pair for which button was pressed, then access it in the backend. Something like this -
$(".review-form").submit(function (e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
let form = $(this);
let newForm = new FormData($(form)[0]);
let submitter_btn = $(e.originalEvent.submitter);
console.log(submitter_btn.attr("name"));
if (submitter_btn.attr("name") == "approve_btn") {
newForm.set("action_for", submitter_btn.attr("name"));
} else if (submitter_btn.attr("name") == "reject_btn") {
newForm.set("action_for", submitter_btn.attr("name"));
} else {
console.log("there is some error!");
return;
}
}
I was basically trying to have a form where user can either approve or disapprove/ reject a product for further processes in a task.
My HTML form is something like this -
<form method="POST" action="{% url 'tasks:review-task' taskid=product.task_id.id %}"
class="review-form">
{% csrf_token %}
<input type="hidden" name="product_id" value="{{product.product_id}}" />
<input type="hidden" name="task_id" value="{{product.task_id_id}}" />
<button type="submit" name="approve_btn" class="btn btn-link" id="approve-btn">
<i class="fa fa-check" style="color: rgb(63, 245, 63);"></i>
</button>
<button type="submit" name="reject_btn" class="btn btn-link" id="reject-btn">
<i class="fa fa-times" style="color: red;"></i>
</button>
</form>
Let me know if you have any doubts.
Try this:
$(document).ready(function(){
$('form[name="testform"]').submit( function(event){
// This is the ID of the clicked button
var clicked_button_id = event.originalEvent.submitter.id;
});
});
$("form input[type=submit]").click(function() {
$("<input />")
.attr('type', 'hidden')
.attr('name', $(this).attr('name'))
.attr('value', $(this).attr('value'))
.appendTo(this)
});
add hidden field
For me, the best solutions was this:
$(form).submit(function(e){
// Get the button that was clicked
var submit = $(this.id).context.activeElement;
// You can get its name like this
alert(submit.name)
// You can get its attributes like this too
alert($(submit).attr('class'))
});
Working with this excellent answer, you can check the active element (the button), append a hidden input to the form, and optionally remove it at the end of the submit handler.
$('form.form-js').submit(function(event){
var frm = $(this);
var btn = $(document.activeElement);
if(
btn.length &&
frm.has(btn) &&
btn.is('button[type="submit"], input[type="submit"], input[type="image"]') &&
btn.is('[name]')
){
frm.append('<input type="hidden" id="form-js-temp" name="' + btn.attr('name') + '" value="' + btn.val() + '">');
}
// Handle the form submit here
$('#form-js-temp').remove();
});
Side note: I personally add the class form-js on all forms that are submitted via JavaScript.
Similar to Stan answer but :
if you have more than one button, you have to get only the
first button => [0]
if the form can be submitted with the enter key, you have to manage a default => myDefaultButtonId
$(document).on('submit', function(event) {
event.preventDefault();
var pressedButtonId =
typeof $(":input[type=submit]:focus")[0] === "undefined" ?
"myDefaultButtonId" :
$(":input[type=submit]:focus")[0].id;
...
}
This is the solution used by me and work very well:
// prevent enter key on some elements to prevent to submit the form
function stopRKey(evt) {
evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
var alloved_enter_on_type = ['textarea'];
if ((evt.keyCode == 13) && ((node.id == "") || ($.inArray(node.type, alloved_enter_on_type) < 0))) {
return false;
}
}
$(document).ready(function() {
document.onkeypress = stopRKey;
// catch the id of submit button and store-it to the form
$("form").each(function() {
var that = $(this);
// define context and reference
/* for each of the submit-inputs - in each of the forms on
the page - assign click and keypress event */
$("input:submit,button", that).bind("click keypress", function(e) {
// store the id of the submit-input on it's enclosing form
that.data("callerid", this.id);
});
});
$("#form1").submit(function(e) {
var origin_id = $(e.target).data("callerid");
alert(origin_id);
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id="form1" name="form1" action="" method="post">
<input type="text" name="text1" />
<input type="submit" id="button1" value="Submit1" name="button1" />
<button type="submit" id="button2" name="button2">
Submit2
</button>
<input type="submit" id="button3" value="Submit3" name="button3" />
</form>
This works for me to get the active button
var val = document.activeElement.textContent;
It helped me https://stackoverflow.com/a/17805011/1029257
Form submited only after submit button was clicked.
var theBtn = $(':focus');
if(theBtn.is(':submit'))
{
// ....
return true;
}
return false;
I was able to use jQuery originalEvent.submitter on Chrome with an ASP.Net Core web app:
My .cshtml form:
<div class="form-group" id="buttons_grp">
<button type="submit" name="submitButton" value="Approve" class="btn btn-success">Approve</button>
<button type="submit" name="submitButton" value="Reject" class="btn btn-danger">Reject</button>
<button type="submit" name="submitButton" value="Save" class="btn btn-primary">Save</button>
...
The jQuery submit handler:
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
$(document).ready(function() {
...
// Ensure that we log an explanatory comment if "Reject"
$('#update_task_form').on('submit', function (e) {
let text = e.originalEvent.submitter.textContent;
if (text == "Reject") {
// Do stuff...
}
});
...
The jQuery Microsoft bundled with my ASP.Net Core environment is v3.3.1.
Let's say I have these "submit" buttons:
<button type="submit" name="submitButton" id="update" value="UpdateRecord" class="btn btn-primary">Update Record</button>
<button type="submit" name="submitButton" id="review_info" value="ReviewInfo" class="btn btn-warning sme_only">Review Info</button>
<button type="submit" name="submitButton" id="need_more_info" value="NeedMoreInfo" class="btn btn-warning sme_only">Need More Info</button>
And this "submit" event handler:
$('#my_form').on('submit', function (e) {
let x1 = $(this).find("input[type=submit]:focus");
let x2 = e.originalEvent.submitter.textContent;
Either expression works. If I click the first button, both "x1" and "x2" return Update Record.
I also made a solution, and it works quite well:
It uses jQuery and CSS
First, I made a quick CSS class, this can be embedded or in a seperate file.
<style type='text/css'>
.Clicked {
/*No Attributes*/
}
</style>
Next, On the click event of a button within the form,add the CSS class to the button. If the button already has the CSS class, remove it. (We don't want two CSS classes [Just in case]).
// Adds a CSS Class to the Button That Has Been Clicked.
$("form :input[type='submit']").click(function ()
{
if ($(this).hasClass("Clicked"))
{
$(this).removeClass("Clicked");
}
$(this).addClass("Clicked");
});
Now, test the button to see it has the CSS class, if the tested button doesn't have the CSS, then the other button will.
// On Form Submit
$("form").submit(function ()
{
// Test Which Button Has the Class
if ($("input[name='name1']").hasClass("Clicked"))
{
// Button 'name1' has been clicked.
}
else
{
// Button 'name2' has been clicked.
}
});
Hope this helps!
Cheers!
You can create input type="hidden" as holder for a button id information.
<input type="hidden" name="button" id="button">
<input type="submit" onClick="document.form_name.button.value = 1;" value="Do something" name="do_something">
In this case form passes value "1" (id of your button) on submit. This works if onClick occurs before submit (?), what I am not sure if it is always true.
A simple way to distinguish which <button> or <input type="button"...> is pressed, is by checking their 'id':
$("button").click(function() {
var id = $(this).attr('id');
...
});
Here is a sample, that uses this.form to get the correct form the submit is into, and data fields to store the last clicked/focused element. I also wrapped submit code inside a timeout to be sure click events happen before it is executed (some users reported in comments that on Chrome sometimes a click event is fired after a submit).
Works when navigating both with keys and with mouse/fingers without counting on browsers to send a click event on RETURN key (doesn't hurt though), I added an event handler for focus events for buttons and fields.
You might add buttons of type="submit" to the items that save themselves when clicked.
In the demo I set a red border to show the selected item and an alert that shows name and value/label.
Here is the FIDDLE
And here is the (same) code:
Javascript:
$("form").submit(function(e) {
e.preventDefault();
// Use this for rare/buggy cases when click event is sent after submit
setTimeout(function() {
var $this=$(this);
var lastFocus = $this.data("lastFocus");
var $defaultSubmit=null;
if(lastFocus) $defaultSubmit=$(lastFocus);
if(!$defaultSubmit || !$defaultSubmit.is("input[type=submit]")) {
// If for some reason we don't have a submit, find one (the first)
$defaultSubmit=$(this).find("input[type=submit]").first();
}
if($defaultSubmit) {
var submitName=$defaultSubmit.attr("name");
var submitLabel=$defaultSubmit.val();
// Just a demo, set hilite and alert
doSomethingWith($defaultSubmit);
setTimeout(function() {alert("Submitted "+submitName+": '"+submitLabel+"'")},1000);
} else {
// There were no submit in the form
}
}.bind(this),0);
});
$("form input").focus(function() {
$(this.form).data("lastFocus", this);
});
$("form input").click(function() {
$(this.form).data("lastFocus", this);
});
// Just a demo, setting hilite
function doSomethingWith($aSelectedEl) {
$aSelectedEl.css({"border":"4px solid red"});
setTimeout(function() { $aSelectedEl.removeAttr("style"); },1000);
}
DUMMY HTML:
<form>
<input type="text" name="testtextortexttest" value="Whatever you write, sir."/>
<input type="text" name="moretesttextormoretexttest" value="Whatever you write, again, sir."/>
<input type="submit" name="test1" value="Action 1"/>
<input type="submit" name="test2" value="Action 2"/>
<input type="submit" name="test3" value="Action 3"/>
<input type="submit" name="test4" value="Action 4"/>
<input type="submit" name="test5" value="Action 5"/>
</form>
DUMB CSS:
input {display:block}
I write this function that helps me
var PupulateFormData= function (elem) {
var arr = {};
$(elem).find("input[name],select[name],button[name]:focus,input[type='submit']:focus").each(function () {
arr[$(this).attr("name")] = $(this).val();
});
return arr;
};
and then Use
var data= PupulateFormData($("form"));

Vue JS focus next input on enter

I have 2 inputs and want switch focus from first to second when user press Enter.
I tried mix jQuery with Vue becouse I can't find any function to focus on something in Vue documentation:
<input v-on:keyup.enter="$(':focus').next('input').focus()"
...>
<input ...>
But on enter I see error in console:
build.js:11079 [Vue warn]: Property or method "$" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. (found in anonymous component - use the "name" option for better debugging messages.)warn # build.js:11079has # build.js:9011keyup # build.js:15333(anonymous function) # build.js:10111
build.js:15333 Uncaught TypeError: $ is not a function
You can try something like this:
<input v-on:keyup.enter="$event.target.nextElementSibling.focus()" type="text">
JSfiddle Example
Update
In case if the target element is inside form element and next form element is not a real sibling then you can do the following:
html
<form id="app">
<p>{{ message }}</p>
<input v-on:keyup.enter="goNext($event.target)" type="text">
<div>
<input type="text">
</div>
</form>
js
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!',
focusNext(elem) {
const currentIndex = Array.from(elem.form.elements).indexOf(elem);
elem.form.elements.item(
currentIndex < elem.form.elements.length - 1 ?
currentIndex + 1 :
0
).focus();
}
}
})
JSFiddle Example
Following up from #zurzui here is in my opinion a cleaner alternative using the $refs API (https://v2.vuejs.org/v2/api/#vm-refs).
Using the $refs API, can allow you to target element in a simpler fashion without traversing the DOM.
Example: https://jsfiddle.net/xjdujke7/1/
After some tests, it's working
new Vue({
el:'#app',
methods: {
nextPlease: function (event) {
document.getElementById('input2').focus();
}
}
});
<script src="https://vuejs.org/js/vue.js"></script>
<div id='app'>
<input type="text" v-on:keyup.enter="nextPlease">
<input id="input2" type="text">
</div>
directives: {
focusNextOnEnter: {
inserted: function (el,binding,vnode) {
let length = vnode.elm.length;
vnode.elm[0].focus();
let index = 0;
el.addEventListener("keyup",(ev) => {
if (ev.keyCode === 13 && index<length-1) {
index++;
vnode.elm[index].focus();
}
});
for (let i = 0;i<length-1;i++) {
vnode.elm[i].onfocus = (function(i) {
return function () {
index = i;
}
})(i);
}
}
}
}
// use it
<el-form v-focusNextOnEnter>
...
</el-form>
Try this:
<input ref="email" />
this.$refs.email.focus()
Whilst I liked the directives answer due to it working with inputs inside other elements (style wrappers and so on), I found it was a little inflexible for elements that come and go, especially if they come and go according to other fields. It also did something more.
Instead, I've put together the following two different directives. Use them in your HTML as per:
<form v-forcusNextOnEnter v-focusFirstOnLoad>
...
</form>
Define them on your Vue object (or in a mixin) with:
directives: {
focusFirstOnLoad: {
inserted(el, binding, vnode) {
vnode.elm[0].focus();
},
},
focusNextOnEnter: {
inserted(el, binding, vnode) {
el.addEventListener('keyup', (ev) => {
let index = [...vnode.elm.elements].indexOf(ev.target);
if (ev.keyCode === 13 && index < vnode.elm.length - 1) {
vnode.elm[index + 1].focus();
}
});
},
},
},
On an enter key pressed, it looks for the index of the current input in the list of inputs, verifies it can be upped, and focuses the next element.
Key differences: length and index are calculated at the time of the click, making it more suitable for field addition/removal; no extra events are needed to change a cached variable.
Downside, this will be a little slower/more intensive to run, but given it's based off UI interaction...
Vue.js's directive is good practice for this requirement.
Define a global directive:
Vue.directive('focusNextOnEnter', {
inserted: function (el, binding, vnode) {
el.addEventListener('keyup', (ev) => {
if (ev.keyCode === 13) {
if (binding.value) {
vnode.context.$refs[binding.value].focus()
return
}
if (!el.form) {
return
}
const inputElements = Array.from(el.form.querySelectorAll('input:not([disabled]):not([readonly])'))
const currentIndex = inputElements.indexOf(el)
inputElements[currentIndex < inputElements.length - 1 ? currentIndex + 1 : 0].focus()
}
})
}
})
Note: We should exclude the disabled and readonly inputs.
Usage:
<form>
<input type="text" v-focus-next-on-enter></input>
<!-- readonly or disabled inputs would be skipped -->
<input type="text" v-focus-next-on-enter readonly></input>
<input type="text" v-focus-next-on-enter disabled></input>
<!-- skip the next and focus on the specified input -->
<input type="text" v-focus-next-on-enter='`theLastInput`'></input>
<input type="text" v-focus-next-on-enter></input>
<input type="text" v-focus-next-on-enter ref="theLastInput"></input>
</form>
<input type="text" #keyup.enter="$event.target.nextElementSibling.focus() />

Making the enter key function like tab key

Friends ,I know there are already many solutions to this question and i have used one but for some unknown reason it is not working in my application.So please help me out and let me know where am i going wrong.Please don't mark this question as duplicate.I seriously need your help.
Thanks in advance.
here is what i have tried.
// Catch the keydown for the entire document
$(document).keydown(function(e) {
// Set self as the current item in focus
var self = $(':focus'),
// Set the form by the current item in focus
form = self.parents('form:eq(0)'),
focusable;
// Array of Indexable/Tab-able items
focusable = form.find('input,a,select,button,textarea,div[contenteditable=true]').filter(':visible');
function enterKey(){
if (e.which === 13 && !self.is('textarea,div[contenteditable=true]')) { // [Enter] key
// If not a regular hyperlink/button/textarea
if ($.inArray(self, focusable) && (!self.is('a,button'))){
// Then prevent the default [Enter] key behaviour from submitting the form
e.preventDefault();
} // Otherwise follow the link/button as by design, or put new line in textarea
// Focus on the next item (either previous or next depending on shift)
focusable.eq(focusable.index(self) + (e.shiftKey ? -1 : 1)).focus();
return false;
}
}
// We need to capture the [Shift] key and check the [Enter] key either way.
if (e.shiftKey) { enterKey() } else { enterKey() }
});
html code-
<form id="purchase" action="p_senddata.php" method="POST" >
Bill_no:<input type="text" name="p_billno" id="pbillno" /><br />
Date:<input type="text" name="p_date" id="pdate" /><br />
Name of party:<input type="text" name="p_nameofparty" id="pnameofparty" /><br /><br />
<input type="submit">
</form>

Is it possible to make input act like a link (Chrome)

I want an input type="button" act like a link to the browser (so, it is possible to right click on the input and see context menu for the links(open link in a new tab, open link in a new window etc).
I have a form with a submit button:
<input type="submit" value="Run Query"/>
In order to create a link and have this context-menu, I replaced input with:
Run Query
But this way "open link in a new tab" opens the same page(due to the href attribute).
I know that you can just ctrl+click on the <input type="submit"/> to open it in a new tab, but if the input tag is present, there is no context menu for it in Chrome.
Is it possible to create an input that would have the same context menu as a link? Or any trick to tell the browser to add this functionality to the input tag?
If I understand your problem correctly, you want to submit the form to a new tab?
Then you could use target="_blank" on the form element.
<form action="" method="POST" target="_blank" >
<input type="submit" />
</form>
This will use the query string to pass the value of each input field to a new window or tab and submit it. It won't work if you're posting files (a workaround would be to immediately upload the file when selected, give it an id and store that in a hidden field, so the file id is the one being posted).
Note that this is an example and you should use something better for dealing with query strings and browser compatibility (it's only tested on Chrome). You should test it thoroughly in other browsers before shipping this! I also have no clue how it's going to work in browsers for iOS/Android/Windows Phones etc. What I'm trying to say is that you probably shouldn't use this.
<body>
<form action="http://google.com">
<input type="text" name="stuff" value="" />
<input type="text" name="q" value="" />
Submit
</form>
<script>
!function () {
var form = document.querySelector("form")
var submitButton = document.querySelector("a")
var queryString = location.search.slice(1).split("&").reduce(function (seed, str) {
var pair = str.split("=")
seed[pair[0]] = decodeURIComponent(pair[1])
return seed
}, {})
Object.keys(queryString).forEach(function (qsKey) {
var formEl = form.querySelector("[name='" + qsKey + "']")
if(formEl)
formEl.value = queryString[qsKey]
})
if(queryString.submit)
form.submit()
submitButton.addEventListener("contextmenu", updateHref) // Update on right click
submitButton.addEventListener("click", function (e) {
if(e.altKey || e.ctrlKey || e.shiftKey || e.which === 2 /* middle mouse button */) {
updateHref()
} else {
e.preventDefault()
form.submit()
}
})
function updateHref() {
var values = [].slice.call(form.elements).map(function (el) {
return el.name + "=" + encodeURIComponent(el.value)
})
submitButton.href = location.pathname + "?submit=1&" + values.join("&")
}
}()
</script>
</body>

Pressing 'enter' on a input type="text", how?

I am facing a problem I can not solve JQuery Javascript. Can you help me and help me understand.First here is my code :
(...)
<script type="text/javascript">
// Autocomplete suggestions
$(function () {
$("#autoCompInput").autocomplete({
source: "/Suggestions",
minLength: 3,
select: function (event, ui) {
if (ui.item) {
$("#autoCompInput").val(ui.item.value);
$("form").submit();
}
}
});
});
// Provide search results
$(function () {
$("#autoCompSearch").click(function () {
var searchParameters = $("#autoCompInput").val();
var jsonData = JSON.stringify(searchParameters, null, 2);
window.location = "/Search?criteria=" + searchParameters;
});
});
</script>
(...)
<input class="ui-autocomplete-input" id="autoCompInput" role="textbox" aria-haspopup="true" size="50" autocomplete="off" aria-autocomplete="list" value = "#ViewBag.SearchInfo"/>
<a id= "autoCompSearch" href = "#" ><img src="#Url.Content("~/Content/Menu/Images/magnifier.png")" alt="Search" /></a>
(...)
With this code I can't use the 'Enter' key to execute my search. When the user is in the input autoCompInput I would like to be able to detect if he press 'enter' and launch the submit. I read I must add a onkeyup="onKeyPressed(event)" event but I don't understand how to write the javascipt associated with the command. I tried but without success... Do you have a solution for me?
Thank you,
You should bind the keypress event to your input
$("#autoCompInput").bind("keypress", {}, keypressInBox);
function keypressInBox(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) { //Enter keycode
e.preventDefault();
$("yourFormId").submit();
}
};
With similar HTML:
<input type="text" id="myTxt" />
<input type="submit" id="mySubmit" />
This script (which uses the latest jQuery 1.7.2) should do it:
$('#mySubmit').click(function() {
alert('Submitted!');
return false;
});
$('#myTxt').on('keyup', function(e) {
if (e.keyCode === 13) {
$('#mySubmit').click();
}
});
Here's a working example.
To assign a keyup event in jquery
$("#autoCompInput").keyup(function(event) {
if (event.keyCode==13) {
alert('enter key');
}
});
I think there is a better and more standard solution to this type of problem.
you can have a GET form around those inputs and whenever you press enter on any input inside that form, it will be submitted to whatever is in the action attribute of the form. This is how it would look like (I took your code but I am removing the bits irrelevant for my answer):
<form id="idForJqueryOnly" action="/Search" method="GET">
<input type="text" name="criteria" value="someuserinput"/>
<button type="submit"><img src="...")" alt="Search" /></button>
</form>
This is standard browser behaviour. So, what the form does? when submitted the browser creates a URL like this:
http://yourserverguesedfromthecurrenturl/Search?criteria=someuserinput
What happened is that the browser took all the inputs with name and value (and not disabled) from the form and serialized them into url form.
Now, the submit event can be triggered by pressing enter on any of the inputs inside, including buttons as long as the buttons don't have the attribute type="button".
If you wanted to do more things with the data with javascript before going to the search page, you can do this with jquery:
$("#idForJqueryOnly").submit(function(){
// here you can do stuff like serialize the form, or sanitize the input of tue user.
var data = $("#idForJqueryOnly").serialize();
$("[name=criteria]").val($("[name=criteria]").val().customSanitizeMethod());
// if you return false, the form will not submit, say, for validation errors:
return customValidator.isFormValid("#idForJqueryOnly");
})

Categories