Hi I am creating jquery plugin. I stuck on when i focus on input box then it triggered twice.
$(document).ready(function(){
$('#searchText').typefast();
$('#searchText1').typefast();
})
$.fn.typefast=function(){
$('input').focus(function(){
console.log($(this).attr('id'));
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" name="" value="" id="searchText">
<input type="text" class="form-control" name="" value="" id="searchText1">
`
It's running twice because you are explicitly calling typefast() twice in your document.ready function. Even though your selectors were both missing the # in them, typefast() still gets called on the empty jQuery wrappers. And, since typefast() doesn't actually do anything with the contents of the wrapped set it gets called on, it goes ahead and processes on all input elements. So, the end result is that all input elements get typefast registered into their focus event twice.
If (and this is a big if) you were going to use a plug-in for this, you should just call it once because the plug-in finds all input elements and sets their event handler. Also, plug-ins have a certain pattern that is recommended to be followed to ensure that the $ will, in fact, point to the jQuery object and to ensure that method chaining will work. That would look like this:
$(function(){
// You would want this to be a jQuery utility method (not a wrapped set method)
// so you would set it up directly on jQuery, not jQuery.fn. This way, you can
// just call it whenever you want without a wrapped set.
$.typefast();
});
// By wrapping the plugin in an Immediately Invoked Function Expression
// that passes itself the jQuery object, we guarantee the $ will work
(function($){
$.typefast = function(){
$('input').focus(function(){
console.log($(this).attr('id'));
});
}
}(jQuery));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" name="" value="" id="searchText">
<input type="text" class="form-control" name="" value="" id="searchText1">
But, there is no need for a jQuery plug-in here. This is not what plug-ins are for and you are not even writing it according to best practices. This is not the way to set up event handlers. All you need to do is set up an event handler for the focus event of the textboxes:
// Just passing a function directly to the jQuery object is the same
// thing as explicitly setting a callback for document.ready
$(function(){
// This is the function that will be called when any input gets the focus
function typeFast(){
console.log($(this).attr('id'));
}
// Set all input elements to call typeFast when they receive the focus
$('input').on("focus", typeFast);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" name="" value="" id="searchText">
<input type="text" class="form-control" name="" value="" id="searchText1">
I have the following form which is getting pre populated with values on load. I want to have empty input boxes on load using Javascript. However I do not have access to the <body> tag so <body onload="" will not work here. Is there any other way to clear the form fields on load?
<form method="POST" action="">
<input name="username" id="user" value="" /><br />
<input name="pwd" id="pass" value="" />
<input type="submit" value="Go" />
</form>
You can use window.onload instead.
function init() {
// Clear forms here
document.getElementById("user").value = "";
}
window.onload = init;
You could also use one of the nice wrappers for doing this in JQuery, Dojo, or you favorite Javascript library. In JQuery it would be,
$(document).ready(init)
Try something like:
window.onload = function(){
document.getElementById("user").value = "";
}
Here's an example
You can run a timeout that will clear the field values. like this:
var t=setTimeout(function(){CLEARVALUES},3000)
Maybe you can add a script tag just after the form.
<script type="text/javascript">document.getElementById("user").value = "";</script>
You can also use jQuery to subscribe to both an individual element's ready (or load) event or the document.
onload=()=>{
document.getElementById('user').value='';
}
or
onload=()=>{
document.getElementById('user').setAttribute('value','');
}
I am using a three part code below:
First part of the code: Basically a javascript function changeSearchEngine will be triggered when user select Google.
<p id="searchbox">This paragraph will change once javascript is triggered</p>
<form align=right>
<select name="searchengine" onchange="changeSearchEngine(this.form)">
<option value="google">Google</option>
</select>
</form>
This is my changeSearchEngine function in javascript.
function changeSearchEngine(form)
{
var searchEngine=form.searchengine.value;
if (searchEngine=="google")
{
var url_google='<form method="get" action="http://www.google.com/search" onsubmit="submitGoogle(this.form)" target="_blank"><input type="text" name="q" size="31" maxlength="255" value="" /><input type="submit" value="Google Search"/></form>';
document.getElementById("searchbox").innerHTML=url_google;
}
}
At this point of time, all is working well. When I select Google, the searchbox for google appears. I can search and everything.
Notice there is a onsubmit="submitGoogle(this.form)" right? I need to save what the user search terms into SQL table. So I have this javascript function below to capture what user have type:
function submitGoogle(form)
{
alert("Inside submitGoogle function");
var searchterm=form.q.value;
alert(searchterm); //to test. this part didnt capture the value.
}
I managed to invoke the submitGoogle function BUT however I can't retrieve the value of q despite using searchterm=form.q.value. What did I do wrong here?
In your onsubmit handler, you are passing this.form. But, this already refers to the form since it is the form itself that triggers the submit event. Form fields have a form property, but the form itself does not have a form property. So, just change your handler to pass this instead of this.form.
http://jsfiddle.net/fmqNj/
onsubmit="submitGoogle(this)"
Okay I found one possible solution. Let me answer my own question.
In changeSearchEngine(form) function, i change to this:
var url_google='<form method="get" name="googleform" action="http://www.google.com/search" onsubmit="submitGoogle(this.form)" target="_blank"><input type="text" name="q" size="31" maxlength="255" value="hello" /><input type="submit" value="Google Search"/></form>';
In submitGoogle(form) function, i change to this:
var searchterm=document.googleform.q.value;
But I still like others to comment on my solution whether it is not elegant or not within the practice. :D
with similar question. :)
<input type="text" name="npcolor" id="npcolor" size="9" maxlength="9" value="<?=$userinfo->npcolor?>" onchange="change_npcolor()" readonly />
<input type="text" ID="np_sample" size="2" value="" readonly style="background-color:<?=$userinfo->npcolor?>" />
<input type="button" onclick="pickerPopup202('npcolor','np_sample');" value="Change" />
function pickerPopup202 is changing npcolor, but when npcolor is changed it don't call change_npcolor(). When I put extra button that call change_npcolor it works. I tried also:
document.getElementById("npcolor").onchange='change_npcolor()';
without success.
P.S. JS that changes npcolor (pickerPopup202) isnt mine, and ALL code is at one line, so i cant really mod it.
When you change the value dynamically, the onchange event doen't fire. You need to call the change_npcolor() method yourself. You could also call document.getElementById("npcolor").onchange(). (This is less efficient, but more flexible when the event handler may change eventually.)
You cannot change the event listener by just adding a string with javascript code to the onchange property. You can do it like this, however:
document.getElementById("npcolor").onchange = function(){
change_npcolor();
}
document.getElementById("npcolor").onchange='change_npcolor()';
here you have change_color() as a string but this is not correct syntax.
Instead of that you can use
document.getElementById("npcolor").onchange=change_ncolor;
Because the change_ncolor works as an object.
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>