I am following a class online and the tutor target a <button> document in which I don't really understand how he did it because he used a document.querySelector to target the parent and that's all.
<div class="row">
<form id="task-form" action="index.php">
<div class="input-field col s12">
<input type="text" name="task" id="task" value="">
<label for="task">New Task</label>
</div>
</div>
<button id="add" class="btn">Add</button>
</form>
he then wrote :
document.querySelector('form').addEventListener('submit', function(event) { /* ... */ })
to me what I understand is that the querySelector will only select the firstChild in this case.
The code just targets the <form> and adds a listener for the submit event.
It is not targeting any <button>.
He actually doesn't add listeners to any button. What you confused was the <form> having an onsubmit event listener. Since there is only one button in the form, its type attribute is automatically set to submit, making it trigger the form.onsubmit event every time.
Also, the code is a bit wrong. You open a div, a form, and before closing the form, you close the div. If that was made by the person who runs the course, I would recommend to stop watching that course in general, since it can confuse a lot...
I have the following HTML form:
<form>
<input type="text" id="input1">
<input type="text">
<button>Submit</button>
</form>
I want to set the focus on #input1 when I blur on the Submit button. Here is the JS that I have:
document.querySelector('button').onblur = function() {
console.log('blurred');
document.querySelector('#input1').focus();
};
I can see the console.log happening, but for some reason the focus isn't being set on #input1.
Try it here: https://jsbin.com/gukocuyada/1/edit?html,js,console,output
Thanks in advance!
Since the <button> is the last focusable element on the page, when you out of it, the browser will override the .onblur handler and simply move the focus to the URL bar. This seems to be built in to most browsers (at least Chrome and Firefox).
You can confirm this by adding another <input> field after the <button> and you will see that hitting does indeed focus on the first <input> field.
You can kludge your way around that default browser behavior by adding a fake input field at the end:
<input style="width: 0px; height: 0px; border: none;" onclick="document.querySelector('#input1').focus();">
I would like to have focus on the tokenfield input field when the modal shows up.
Currently it's focused only if I click on the input field in the modal.
https://jsfiddle.net/csisanyi/h19Lzkyr/12/
I tried to add the following code
Mousetrap.bind('w', function() {
document.getElementById("keywordButton").click();
document.getElementById("keyword-input").focus();
});
I also tried to add <input autofocus> but when the tokenfield is initialized it seems like it's overriden.
I have checked the bootstrap-tokenfield documentation but input field focus is not really mentioned there.
Any suggestions?
Do you want the focus on the button or the input field? The ID you specified is for focusing on the button. You mention wanting the field to focus, but it doesn't seem you are calling on it. I can't make comments but will edit this as time goes on.
HTML:
<div class="modal-body">
<p class="modal_text">Add keywords.</p>
<input class="token-input input-group-lg keywordmodalclass" id="keyword-input" type="text" name="keywords" value="" placeholder="Keywords">
</div>
<div class="modal-footer">
<button id="saveKeyword" type="submit" class="btn btn-success" onclick="submitKeywords()">Save Keywords</button>
Jquery:
Mousetrap.bind('w', function() {
document.getElementById("keywordButton").click();
document.getElementById("keyword-input").focus();
});
I found a solution to the problem.
after the tokenfield is initialized, bootstrap-tokenfield.js appends the id of the input with -tokenfield.
So i added the following code.
https://jsfiddle.net/csisanyi/h19Lzkyr/43/
Mousetrap.bind('w', function() {
document.getElementById("keywordButton").click();
setTimeout(() => {
document.getElementById("keyword-input-tokenfield").focus();
}, 400);
});
And it works with setting a minimal timeout on the focus expression.
I'm building a simple 1 page app that allows someone to curate a list of json feeds. I'm running into an issue with trying to bind a mouseenter/mouseleave event to all the inputs on the page with a given class. Simply, put the first works and the second does not.
I have to following jquery:
$(".feed").on("mouseenter", ".publish", function(){
console.log("feed")
}); //this is for test purposes
$(".feed").on("mouseenter", ".keys-input", function(){
console.log($(this));
$(this).siblings(".delete").fadeIn(75);
});
$(".feed").on("mouseleave", ".keys-input", function(){
$(this).siblings(".delete").fadeOut(75);
});
and the following html:
<div class="feed"><!-- sorry for the confusion -->
<div class="feed-header">
<h2>pga-2013.json</h2>
<button class="publish button-white-bg button-save">Publish</button>
</div>
<div class="kvRow collapsed">
<span class="delete icon">x</span>
<input type="text" class="keys-input" value="free" disabled=""/>
<input type="text" class="values-input" value="0" disabled=""/>
</div>
</div>
The reason I ask if there is a max number of elements you can bind to is because the ".feed" event triggers and there are only 11 of them on the dom whereas the ".keys-input" event does not and there are 7266 of them on the dom. Either that or I'm blind and doing something dumb...
here's a fiddle with fewer elements but the same code that works http://jsfiddle.net/khLPc/
this is the issue: Event on a disabled input the inputs are disabled so they won't fire events which is bananas to me...
The event is not triggered on the disabled element.
Enable the input and it will work.
Check here, I've enabled one of the input fields:
http://jsfiddle.net/balintbako/khLPc/1
Apparently I have to include some code too:
<input type="text" class="keys-input" value="free"/>
Can someone please tell me how to submit an HTML form when the return key is pressed and if there are no buttons in the form?
The submit button is not there. I am using a custom div instead of that.
To submit the form when the enter key is pressed create a javascript function along these lines.
function checkSubmit(e) {
if(e && e.keyCode == 13) {
document.forms[0].submit();
}
}
Then add the event to whatever scope you need eg on the div tag:
<div onKeyPress="return checkSubmit(event)"/>
This is also the default behaviour of Internet Explorer 7 anyway though (probably earlier versions as well).
IMO, this is the cleanest answer:
<form action="" method="get">
Name: <input type="text" name="name"/><br/>
Pwd: <input type="password" name="password"/><br/>
<div class="yourCustomDiv"/>
<input type="submit" style="display:none"/>
</form>
Better yet, if you are using javascript to submit the form using the custom div, you should also use javascript to create it, and to set the display:none style on the button. This way users with javascript disabled will still see the submit button and can click on it.
It has been noted that display:none will cause IE to ignore the input. I created a new JSFiddle example that starts as a standard form, and uses progressive enhancement to hide the submit and create the new div. I did use the CSS styling from StriplingWarrior.
I tried various javascript/jQuery-based strategies, but I kept having issues. The latest issue to arise involved accidental submission when the user uses the enter key to select from the browser's built-in auto-complete list. I finally switched to this strategy, which seems to work on all the browsers my company supports:
<div class="hidden-submit"><input type="submit" tabindex="-1"/></div>
.hidden-submit {
border: 0 none;
height: 0;
width: 0;
padding: 0;
margin: 0;
overflow: hidden;
}
This is similar to the currently-accepted answer by Chris Marasti-Georg, but by avoiding display: none, it appears to work correctly on all browsers.
Update
I edited the code above to include a negative tabindex so it doesn't capture the tab key. While this technically won't validate in HTML 4, the HTML5 spec includes language to make it work the way most browsers were already implementing it anyway.
Use the <button> tag. From the W3C standard:
Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content. For example, a BUTTON element that contains an image functions like and may resemble an INPUT element whose type is set to "image", but the BUTTON element type allows content.
Basically there is another tag, <button>, which requires no javascript, that also can submit a form. It can be styled much in the way of a <div> tag (including <img /> inside the button tag). The buttons from the <input /> tag are not nearly as flexible.
<button type="submit">
<img src="my-icon.png" />
Clicking will submit the form
</button>
There are three types to set on the <button>; they map to the <input> button types.
<button type="submit">Will submit the form</button>
<button type="reset">Will reset the form</button>
<button type="button">Will do nothing; add javascript onclick hooks</button>
Standards
W3C wiki about <button>
HTML5 <button>
HTML4 <button>
I use <button> tags with css-sprites and a bit of css styling to get colorful and functional form buttons. Note that it's possible to write css for, for example, <a class="button"> links share to styling with the <button> element.
Here is how I do it with jQuery
j(".textBoxClass").keypress(function(e)
{
// if the key pressed is the enter key
if (e.which == 13)
{
// do work
}
});
Other javascript wouldnt be too different. the catch is checking for keypress argument of "13", which is the enter key
I believe this is what you want.
//<![CDATA[
//Send form if they hit enter.
document.onkeypress = enter;
function enter(e) {
if (e.which == 13) { sendform(); }
}
//Form to send
function sendform() {
document.forms[0].submit();
}
//]]>
Every time a key is pressed, function enter() will be called. If the key pressed matches the enter key (13), then sendform() will be called and the first encountered form will be sent. This is only for Firefox and other standards compliant browsers.
If you find this code useful, please be sure to vote me up!
Use the following script.
<SCRIPT TYPE="text/javascript">
<!--
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;
}
//-->
</SCRIPT>
For each field that should submit the form when the user hits enter, call the submitenter function as follows.
<FORM ACTION="../cgi-bin/formaction.pl">
name: <INPUT NAME=realname SIZE=15><BR>
password: <INPUT NAME=password TYPE=PASSWORD SIZE=10
onKeyPress="return submitenter(this,event)"><BR>
<INPUT TYPE=SUBMIT VALUE="Submit">
</FORM>
I use this method:
<form name='test' method=post action='sendme.php'>
<input type=text name='test1'>
<input type=button value='send' onClick='document.test.submit()'>
<input type=image src='spacer.gif'> <!-- <<<< this is the secret! -->
</form>
Basically, I just add an invisible input of type image (where "spacer.gif" is a 1x1 transparent gif).
In this way, I can submit this form either with the 'send' button or simply by pressing enter on the keyboard.
This is the trick!
Why don't you just apply the div submit styles to a submit button? I'm sure there's a javascript for this but that would be easier.
If you are using asp.net you can use the defaultButton attribute on the form.
I think you should actually have a submit button or a submit image... Do you have a specific reason for using a "submit div"? If you just want custom styles I recommend <input type="image".... http://webdesign.about.com/cs/forms/a/aaformsubmit_2.htm
Extending on the answers, this is what worked for me, maybe someone will find it useful.
Html
<form method="post" action="/url" id="editMeta">
<textarea class="form-control" onkeypress="submitOnEnter(event)"></textarea>
</form>
Js
function submitOnEnter(e) {
if (e.which == 13) {
document.getElementById("editMeta").submit()
}
}
Similar to Chris Marasti-Georg's example, instead using inline javascript.
Essentially add onkeypress to the fields you want the enter key to work with. This example acts on the password field.
<html>
<head><title>title</title></head>
<body>
<form action="" method="get">
Name: <input type="text" name="name"/><br/>
Pwd: <input type="password" name="password" onkeypress="if(event.keyCode==13) {javascript:form.submit();}" /><br/>
<input type="submit" onClick="javascript:form.submit();"/>
</form>
</body>
</html>
Since display: none buttons and inputs won't work in Safari and IE, I found that the easiest way, requiring no extra javascript hacks, is to simply add an absolutely positioned <button /> to the form and place it far off screen.
<form action="" method="get">
<input type="text" name="name" />
<input type="password" name="password" />
<div class="yourCustomDiv"/>
<button style="position:absolute;left:-10000px;right:9990px"/>
</form>
This works in the current version of all major browsers as of September 2016.
Obviously its reccomended (and more semantically correct) to just style the <button/> as desired.
Using the "autofocus" attribute works to give input focus to the button by default. In fact clicking on any control within the form also gives focus to the form, a requirement for the form to react to the RETURN. So, the "autofocus" does that for you in case the user never clicked on any other control within the form.
So, the "autofocus" makes the crucial difference if the user never clicked on any of the form controls before hitting RETURN.
But even then, there are still 2 conditions to be met for this to work without JS:
a) you have to specify a page to go to (if left empty it wont work). In my example it is hello.php
b) the control has to be visible. You could conceivably move it off the page to hide, but you cannot use display:none or visibility:hidden.
What I did, was to use inline style to just move it off the page to the left by 200px. I made the height 0px so that it does not take up space. Because otherwise it can still disrupt other controls above and below. Or you could float the element too.
<form action="hello.php" method="get">
Name: <input type="text" name="name"/><br/>
Pwd: <input type="password" name="password"/><br/>
<div class="yourCustomDiv"/>
<input autofocus type="submit" style="position:relative; left:-200px; height:0px;" />
</form>