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">
Related
I am new at Jquery. My User Story: I have two input form tag. One is hidden and One is Text. I need to take value from input text and set that value into hidden input and then submit the form with both value. Is it possible to do in Jquery. Here is my example code:
if ($_POST) {
$email = $_REQUEST['email'];
$username = $_REQUEST['username'];
echo "Email Value: " . $email ." And Username Value :" .$username;
}
var lap = $("emailId").val();
var test = $("userId");
test.val(test);
<form>
<input id="emailId" name="email" type="text" value="">
<input id="userId" name="username" type="hidden" value="">
<input type="submit" value="Submit" />
</form>
You don't need jQuery for this. I've provide a solution using jQuery as well as vanilla JavaScript.
jQuery Version
$(document).ready(function(){
$email = $('#email')
// Note that we are updating the hidden input value each time the
// text input value changes. We could do this less frequently by
// using the `input` or `change` event instead of the `keyup` event.
$email.on('keyup', function(e){
$('#userId').val($email.val())
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="email" id="email" />
<input type="hidden" name="userId" id="userId" />
<button type="submit" id="submit">Submit</button>
</form>
Vanilla JavaScript Version
document.addEventListener('DOMContentLoaded', function(e) {
var txtEmail = document.querySelector('#email')
var txtUserId = document.querySelector('#userId')
// Note that we are updating the hidden input value each time the
// text input value changes. We could do this less frequently by
// using the `input` or `change` event instead of the `keyup` event.
txtEmail.addEventListener('keyup', function(e) {
txtUserId.value = txtEmail.value
})
})
<form>
<input type="text" name="email" id="email" />
<input type="hidden" name="userId" id="userId" />
<button type="submit" id="submit">Submit</button>
</form>
A brief explanation of my method
Waiting for the HTML to load
Whether you're using jQuery or not, depending on how your JavaScript and HTML code is stitched together, sometimes you're HTML elements are not available when your JavaScript code runs (for example, if your JavaScript code is included in the <head> tag, which I think has become pretty uncommon these days). For this reason, I've gotten into the habit of making sure the document is ready before I reference any HTML elements. Using jQuery, this is done with the following code:
$(document).ready(function(){
// The code here (inside this function) will be executed after the HTML finishes loading.
})
With vanilla JavaScript, the code looks like this:
document.addEventListener('DOMContentLoaded', function(){
// The code here (inside this function) will be executed after the HTML finishes loading.
})
Making Updates As Soon As Possible
In addition, my code updates the hidden input value after the text input value has changed, rather than waiting for the form to be submitted. Either option may be perfectly acceptable for a given situation. I am in the habit of updating things like these as soon as possible; if in the future, I write some JavaScript code that is expecting the value of these to input controls to be equivalent, and that code runs before the form is submitted, I'll probably have a bug in my code. Hence, I find it safer to just update as soon as the change occurs.
As per jquery documentation You forgot to use # in your both selectors. You should use:
var lap = $("#emailId").val();
var test = $("#userId");
test.val(lap);
I'm trying to implement real time search so i have a search for including many input fields
so each and every time when user update input fields search function should be triggered.
i have came up with $watch to track model changes on form field
$scope.$watch('filters.site', function () {
$scope.$broadcast('updateDataTable');
});
$scope.$watch('filters.fname', function () {
$scope.$broadcast('updateDataTable');
});
$scope.$watch('filters.lname', function () {
$scope.$broadcast('updateDataTable');
});
but i'm just wondered is there anyway to get whole form value changes
my form look like
<form name="searchForm">
<label for="">FIRST NAME</label>
<input type="text"
class="form-control"
data-ng-model="filters.fname">
<span></span>
<label for="">LAST NAME</label>
<input type="text"
class="form-control"
data-ng-model="filters.lname">
<span></span>
<label for="">SITE</label>
<input type="text"
class="form-control"
data-ng-model="filters.site">
<span></span>
</form>
thanks
If you pass true as the last argument to $watch, Angular will watch for deep equality instead, and you can watch the entire object at once:
$scope.$watch("filters", function() { ... }, true);
That will incur creating a copy of the object on every digest cycle, but if all your filters object contains is those filters, it's probably not going to be any more inefficient than watching everything separately. If your filters object is expensive to copy for some reason you could also use a $watchGroup for equivalent functionality to your current code except neater:
$scope.$watchGroup(["filters.site", "filters.fname", ...], function() { ... });
$scope.$watch('filters', function () {
$scope.$broadcast('updateDataTable');
});
You can use the ng-change directive that could call your search function just add it on all your input so when one of the input change the search function will be called.
<input type="text" class="form-control" data-ng-change="search()" data-ng-model="filters.fname">
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
I am trying to move text between text boxes, but failed.
what is wrong with this approach.
<html>
<script>
function fill(){
document.getElementById("text2").value = document.test.text1.value
}
</script>
<form name="test" id="test">
<input type="text" name="text1" id="text1"/>
<input type="text" name="text2" id="text2" value=""/>
<button name="b" onclick="fill()">move</button>
</form>
</html>
One reason is the button is submitting the form. That needs to be suppressed. Also, avoid inline (aka DOM zero) event declarations and bind the event more formally:
function fill(evt){
document.getElementById("text2").value = document.test.text1.value;
evt.preventDefault();
}
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('#test button').addEventListener('click', fill, false);
}, false);
I'm using a few modern methods there, so you might need to tweak it if you need to support older IEs, but you get the idea.
Note also that, if the fill function is used only for this button and not elsewhere, instead of defining it with a name and referencing it as I do here, you could reference it as an anonymous function directly in the event binding. Look up "anonymous functions" for more on that.
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.