I have a form with two buttons and some text inputs. By default if you press enter it will "click" the first button. I'd like to make it so that if you type in either of the text boxes, if you press enter the second button will be the one to be clicked.
In the simplified example below, pressing enter will by default "click" the log in using facebook button. This will happen even if something is entered in the email or password text inputs. I'd like it so that if something is entered in either the email or password inputs, then pressing enter will "click" the login with email/password button.
<form>
<button class="login-facebook">Log in with Facebook</button>
<input type="text" class="email" placeholder="email"><br>
<input type="password" class="password" placeholder="password"><br>
<button class="login-password">Log in with email/password</button>
</form>
Goal is something like:
$('.email').add('.password').on('change', function() {
$('.login-password').setToBeNewDefaultClickIfEnterIsPressed();
});
Where setToBeNewDefaultClickIfEnterIsPressed() changes the default enter.
See: Multiple submit buttons on HTML form – designate one button as default
You can also make them separate forms and play with that. See also: preventDefault
Try this.
I threw in a field that let's you select the button you want to be the default, just to show how it works. If that field is empty, I made the default button #2.
jsFiddle here
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
var defaultbutt = 2;
$(document).ready(function() {
$('[id^=txt]').blur(function() {
if ($(this).val() != '') {
defaultbutt = $('#pickabutt').val();
if (defaultbutt=='') defaultbutt = 2;
}
});
$('#pickabutt').blur(function() {
defaultbutt = $('#pickabutt').val();
if (defaultbutt=='') defaultbutt = 2;
});
$(document).keypress(function(e) {
if(e.which == 13) {
$('#mybutt' + defaultbutt).click();
}
});
$('[id^=mybutt]').click(function() {
var num = $(this).val();
alert('You clicked button: ' + num);
});
}); //END $(document).ready()
</script>
</head>
<body>
Login:<br /><input id="txtLogin" type="text" /><br />
PWord:<br /><input id="txtPassword" type="password" /><br />
<input type="button" id="mybutt1" value="One" />
<input type="button" id="mybutt2" value="Two" />
<input type="button" id="mybutt3" value="Three" />
Default button Number:<br /><input id="pickabutt" type="text" /><br />
</body>
</html>
Related
I want to make a submit button which, once clicked on, will run a function I have made: disable() but I want to make it so it only runs the onclick event if the input above had text.
<form id="name">
<p7>Please enter a name for your plan: </p7> <input required>
<input type="submit" onclick="disable()">
</form>
So if the user typed the required input after the tags, and clicked on submit, it will run disable)
But if the user just clicks on submit without typing anything in the required input, disable() doesn't run
Thanks in advance
You can validate the input value at the beginning of the disable function, like so:
function disable() {
var myInput = document.getElementById("myInput");
if (!myInput.value.length) {
alert('empty');
return;
}
alert('fine');
}
<form id="name">
<p7>Please enter a name for your plan: </p7>
<input required id="myInput">
<input type="submit" onclick="disable()">
</form>
If you're want to use HTML5 validation, don't use click event of the button, use submit event of the form, as follows:
function disable(e) {
e.preventDefault() // Not needed, but for the snippet, for the form win't disappear
console.log('Inside disable().');
}
$('#name').submit(disable);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="name">
<p7>Please enter a name for your plan: </p7> <input id="input" required>
<input type="submit">
</form>
I you want to validate it inside JS, use code like the following, that determinates if there is a value inside the input field:
function disable() {
if (!$('#input').val()) {
return;
}
console.log('Inside disable().');
}
$('#button').click(disable);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="name">
<p7>Please enter a name for your plan: </p7> <input id="input" required>
<input type="button" id="button" value="Click Me!">
</form>
You could also disable the button itself as you don't need it when there is no input present.
You need to add disable function on input box field.
Added onkeyup event on inputbox to track changes.
disable()
function disable(){
if($("#input").val()!=""){
$("input[type=submit]").attr("disabled", false);
//your own code here!!
}
else{
$("input[type=submit]").attr("disabled", true);
return; //do nothing and return back.
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<form id="name">
<p7>Please enter a name for your plan: </p7>
<input onkeyup="disable()" value="" id="input" required>
<input onclick="disable()" id="submit" type="submit">
</form>
I have three forms on a page with submit buttons in each, there is a code which is suppose to changes the value of a button in a particular form when clicked but when i click on that submit button all the values in the various forms buttons changes, but i want to change the value based on the form i click
<script language="javascript">
/**
* Disable submit button
*/
$(function(){
$('input:submit').click(function(){
$(this).val('Request Placed...');
$(this).attr('disabled', 'disabled');
$(this).parents('form').submit();
});
});
$(window).load(function(){
$('input:submit').removeAttr('disabled');
});
</script>
Use jQuery selector to select only form that you need, only input from form with id="form_2" will be supported
$(function(){
$('input:submit', '#form_2').click(function(){
$(this).val('Request Placed...');
$(this).attr('disabled', 'disabled');
});
});
jsfiddle: http://jsfiddle.net/krzysztof_safjanowski/sP2Zv/2/
I am not sure about your requirements. However, this demo might give you some ideas to resolve your issues.
HTML:
<form id="form1" action="action1">
<input type="text" id="txt1" />
<input type="submit" value="Submit" />
</form>
<form id="form2" action="action2">
<input type="text" id="txt2" />
<input type="submit" value="Submit" />
</form>
<form id="form3" action="action3">
<input type="text" id="txt3" />
<input type="submit" value="Submit" />
</form>
JavaScript:
(function () {
var $submitBtn,
$form,
submitBtnHandler = function (event) {
event.preventDefault();
var $self = $(this);
$self.val('Request Placed...');
$self.prop('disabled', true);
$self.parents('form').submit();
},
formSubmitHandler = function (event) {
event.preventDefault(); // Added this to stay in the same page when submit form. If you want to redirect to the action URL(action1, action2, action3 etc), please remove it.
alert("Hi, I am " + this.id);
},
resetSubmitBtnState = function () {
$submitBtn.removeAttr('disabled');
},
init = function () {
$submitBtn = $('input:submit');
$form = $('form');
$submitBtn.on('click', submitBtnHandler);
$form.on('submit', formSubmitHandler);
};
$(document).ready(init);
$(window).load(resetSubmitBtnState);
}());
JSFiddle Demo: http://jsfiddle.net/w3devjs/3Byb2/
In JavaScript you could do this,
document.getElementById("BUTTON'S ID").value = "TEXT HERE";
Just make that line an onclick one.
So, when the user clicks the button, an onclick event happens, that will change the button's vaule. Be sure that in the input tag, there is an id for the button as well as a value for it.
So, here's a little example I whipped up,
In HTML,
<form>
<input type="text" id="Input" />
<input type="button" id="BUTTON'S ID" value="TEXT HERE" onclick="Changetxt()" />
</form>
In JavaScript,
<script>
function Changetxt()
{
document.getElementById("BUTTON'S ID").value = "SOME OTHER TEXT";
}
</script>
So, when the user clicks the button, the button's text changes from TEXT HERE to SOME OTHER TEXT.
I have 4 textboxes and a submit button in my web page.
Suppose the user enters data in 2 fields and then clicks the submit button.
I now want to know in which textbox the cursor was located just before the submit button was clicked.
Any idea on how to do this in Javascript?
You're looking for document.activeElement, which returns the currently focused element.
Your question does specifically say in javascript, but FWIW here is another option in jQuery:
Working jsFiddle here
HTML:
<input id="in1" type="text" /><br />
<input id="in2" type="text" /><br />
<input id="in3" type="text" /><br />
<input id="in4" type="text" /><br />
<input type="button" id="mybutt" value="Submit" />
jQuery:
var inFocus = false;
$('input, textarea').focus(function() {
inFocus = $(this).attr('id');
});
$('#mybutt').click(function() {
alert('Cursor was last in element id: ' + inFocus);
});
you can use document.activeElement
here is the simple example for the same.
<head>
<script type="text/javascript">
function GetActive () {
if (document.activeElement) {
var output = document.getElementById ("output");
output.innerHTML = document.activeElement.tagName;
}
}
</script>
</head>
<body onclick="GetActive ();">
Click anywhere on the page to get the active element
<input id="myInput" value="input field" />
<button>Sample button</button>
<div id="output"></div>
</body>
I'll be honest, I don't really know what the best approach here is. I've got no Javascript knowledge, but I don't think should be necessary here...It's stupidly simple.
I have a simple form. I want the user to be able to type a word and press enter or click "submit." When "X" is entered, I want them to be redirected to 'www.MyURL.com/X.html'. The only solution I could find looked like this:
<form>
<input name="solution" type="text" id="solution" maxlength="10" /><br />
<input type="button" value="submit" onclick="window.location='http://www.MYURL.com/' + this.form.solution.value + '.html'"/>
</form>
However, this doesn't allow the user to hit Enter to submit the form. I tried the below to make it a submit input, but I don't know anything about the potential operations of "onsubmit", and this one isn't working.
<form onsubmit="window.location='http://www.MYURL.com/' + this.form.solution.value + '.html'">
<input name="solution" type='text' id="solution" maxlength="10" /><br />
<input type="submit" value="submit" />
Should I be using "action=" for this event? And I don't know if "method=" plays into it.
My issue is that I can't figure out how to make the form submit its text content to a URL and then link to that URL.
You can do this all in javascript without a form. Just check the key code with each keyboard press - if it's the Enter key (13), then do your redirect.
Here's a full working page:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input type="text" id="solution" onkeyup="doSomething(event);">
<input type="button" value="Click Me" onclick="redirect();">
<script type="text/javascript">
function doSomething(e) {
var keyCode = e.keyCode || e.charCode;
if (keyCode === 13) {
redirect();
}
}
function redirect() {
window.location.href = "http://www.MYURL.com/"
+ document.getElementById("solution").value
+ ".html";
}
</script>
</body>
</html>
I'm working on a site that is full of forms to be filled and I it's required that when escape button is pressed focus move to the next input control, just as pressing "tab" do.
I found code to move focus when keypressed is 13 but this need to take the ID of element to focus on
<input id="Text1" type="text" onkeydown="return noNumbers(event)" />
<input id="Text2" type="text" />
<script type="text/javascript">
function noNumbers(e) {
keynum = e.which;
if (keynum == 13)
document.getElementById("Text2").focus();
}
</script>
I need a generalized function that when key pressed code is 13 "that is enter" fire the default event of pressing 9 "that is tab", of course in Javascript
This will handle multiple input fields.
Here is the jQuery version:
http://jsfiddle.net/TnEB5/3/
$('input').keypress(function(e) {
if (e.which == 13) {
$(this).next('input').focus();
e.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="Text1" type="text" />
<input id="Text2" type="text" />
<input id="Text3" type="text" />
Here is the pure javascript version:
http://jsfiddle.net/TnEB5/5/
(you probably want to get the sibling differently)
function tab(e) {
if (e.which == 13) {
e.target.nextSibling.nextSibling.focus();
e.preventDefault();
}
}
var inputs = document.getElementsByTagName('input');
for (var x = 0; x < inputs.length; x++)
{
var input = inputs[x];
input.onkeypress = tab;
}
<input id="Text1" type="text" />
<input id="Text2" type="text" />
<input id="Text3" type="text" />
handle keypress instead and return false back to the browser:
http://jsfiddle.net/EeyTL/
<input id="Text1" type="text" />
<input id="Text2" type="text" />
<script type="text/javascript">
document.getElementById('Text1').onkeypress = function (e) {
if (e.which === 13) {
document.getElementById("Text2").focus();
return false;
}
};
</script>
You'll need to explicitly set the tabindex property of the input fields for a generic solution. Something like
<input id="Text1" type="text" tabindex="1" />
<input id="Text2" type="text" tabindex="2" />
<script type="text/javascript">
$('input').keypress(function(e){
if(e.which==13){
$("[tabindex='"+($(this).attr("tabindex")+1)+"']").focus();
e.preventDefault();
}
});
</script>
this solution uses jquery to assign the event handler for all input type elements on the page, sets focus to the element with the next highest tabindex property, and prevents the form from submitting when enter is pressed using e.preventDefault(). Here's a jfiddle
<input type="text" value="" onkeyup="doNext(this);"> a <br>
<input type="text" value="" onkeyup="doNext(this);"> b <br>
<input type="text" value="" onkeyup="doNext(this);"> c <br>
function doNext(el){
if(event.keyCode=='13'){
var nextEl = el.form.elements[el.tabIndex+1];
if (nextEl && nextEl.focus) nextEl.focus();
}
}
Althought the post is old, I hope my answer can help someone in need. I have a smilar situation:
I have a very large form for an employee scheduler application with different types of input fields. Some of the input fields are hidden sometimes and not other times. I was asked to make the enter key behave as the tab key so the users of the form could use the 10-key when creating thier employees schedule.
Here is how I solved my problem:
$(document).ready(function () {
var allInputs = $(':text:visible'); //(1)collection of all the inputs I want (not all the inputs on my form)
$(":text").on("keydown", function () {//(2)When an input field detects a keydown event
if (event.keyCode == 13) {
event.preventDefault();
var nextInput = allInputs.get(allInputs.index(this) + 1);//(3)The next input in my collection of all inputs
if (nextInput) {
nextInput.focus(); //(4)focus that next input if the input is not null
}
}
});
});
What I had to do was:
Create a collection of all the inputs I want to consider when tabbing. in my case it is text inputs that are visible.
Listen for a keydown event on the inputs in question, in my case all text field inputs
When the enter is pressed on my text input, determine what input is next to be focused.
If that input is valid, bring it into focus.
I am using this code for advancing to next input field. I hate to press TAB key. And this solution works in IE & Firefox:
<script type="text/javascript">
function tabE(obj,e){
var e=(typeof event!='undefined')?window.event:e;// IE : Moz
if(e.keyCode==13){
var ele = document.forms[0].elements;
for(var i=0;i<ele.length;i++){
var q=(i==ele.length-1)?0:i+1;// if last element : if any other
if(obj==ele[i]){ele[q].focus();break}
}
return false;
}
}
</script>
HTML Content
<form id="main">
<input name="" type="text" onkeypress="return tabE(this,event)">
<input type="submit" value="Ok">
</form>
Here is a easy solution for you.
Basically you include the enter2tab.js file and then add the enter2tab class on each object where you want enter to be treated as js.
https://github.com/AndreasGrip/enter2tab
You can obviously look at the code to understand what it does and how..
I believe using e.preventDefault(); is safer than returning false.