I would like to select the text of the input field which currently has focus, so when the user starts typing, the text which is currently in the input field is gone. Can I do this with javascript (or jquery)?
In case the field which currently has focus is not an input field, nothing has to happen.
thanks!
EDIT:
To all the answerers: you all misunderstood (so probably my question was not clear).
I don't want to select the text on the moment the input field gets the focus. I would like to have a javascript function which selects the text of the input field which has the focus at that moment.
Sorry I misunderstood what you were looking for I think that I have a better understanding of it now. Does this do more of what you were looking to acheive?
//If not using 1.7 for jquery you can use bind
$('input, textarea').on({
focusin: function(){
$(this).addClass("focused");
},
focusout: function(){
$(this).removeClass("focused");
}
});
function highlightText()
{
var focused = $('input.focused,textarea.focused');
if (focused.size()) {
focused.get(0).select();
}
}
http://jsfiddle.net/GXFpR/1/
This should work:
<html>
<head>
</head>
<body>
<input type="text" id="theTextBox" onfocus="selectText()" value="some value"></input>
<script type="text/javascript">
function selectText() {
document.getElementById("theTextBox").select();
};
</script>
</body>
</html>
You can check with onfocus and then use this.select() as inline
<input name="" type="text" value="test test" onfocus="this.select()" />
UPDATE: a more universal approach, will add focus to inputs of the text type also input text's that are not readonly
window.onload = setFocus();
or call beneth the last form input field
setFocus();
main
setFocus = function(){
var i = [];
i = document.getElementsByTagName("input");
for(var t=0; t < i.length; t++){
if(i.item(t).type == "text" && i.item(t).readOnly == false){
i.item(t).onfocus = function (){this.select()};
}
}
}
You can try something like this? http://jsfiddle.net/z55UZ/
$("input, textarea").focus(
function()
{
this.select();
}
)
EDIT:
here is an updated fiddle: http://jsfiddle.net/IrvinDominin/z55UZ/2/
In the example is selected the last focused element; but if you look at the code the var childInputHasFocus and whoHasFocus are never setted to false...when you want to stop the selecting feature?
Where you wanna call the function? Because the click event sets the active/focused element as is caller.
Related
I am trying to build a jQuery function that creates seven input fields when a button is clicked. This should be allowed only once, and not every time the button is pressed.
At the moment I have the below code that creates one text field, but the problem is that every time the button is pressed more text fields are added. By creating these text fields I can use them to add records in my database. For example by clicking the addbutton, the text fields will be created and the user could enter the information.
$("#addbutton").bind("click", function() {
var textarea = $('<input type="text" name="firstname">',);
$('#textfields').append(textarea);
});
Thanks
You can fire the event handler only once with one(), and just append the buttons you want, I'm using an array of names and $.map to create them
$("#addbutton").one("click", function() {
var buttons = [
'firstname',
'lastname',
..... etc
];
$('#textfields').append(
$.map(buttons, function(_name) {
return $('<input />', { name : _name })
})
);
});
FIDDLE
According to our chat in your comments, you want a button that:
On click, it creates seven input fields and appends them to your #textfields element.
After the fields are created, the button is not allowed to create any more input fields.
I devised the following solution based upon this interpretation:
$("#addbutton").click(function(){
for(var i = 0; i < 7; ++i){
$('#textfields').append('<input type="text" name="firstname">');
}
$(this).prop("disabled", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="addbutton">Click Me</button>
<div id="textfields"></div>
Long story short, the button is disabled after the first click. This prevents you or anyone from doing anything else with the button.
Alternatively you could create a global variable which will act as a flag, to help prevent further input fields from being created, by wrapping the input creation code with an if statement like so:
var inputFieldsCreated = false;
$("#addbutton").click(function(){
if(inputFieldsCreated === false){
for(var i = 0; i < 7; ++i){
$('#textfields').append('<input type="text" name="firstname">');
}
inputFieldsCreated = true;
}
});
Let me know if this does the job for you in the comments below.
Just because I don't like using JQuery for such easy/simple/short thing, here's the code with pure JavaScript :
document.getElementById("btn").addEventListener("click", onClick, false);
function onClick() {
var textfield, br;
for(var i=0 ; i<7 ; i++) {
textfield = document.createElement("input");
br = document.createElement("br");
textfield.id = "txt_"+i;
document.getElementById("textFields").appendChild(textfield);
document.getElementById("textFields").appendChild(br);
}
this.parentElement.removeChild(this);
}
cou can test it here :
https://jsfiddle.net/v91v7afa/
Of course, instead of deleting the button, you can disable it, but it would be really easy to re-enable it. Or you can remove the listener.
var numText=1;
$("#addbutton").on("click",function(e){
e.preventDefault();
numText++;
$('#textfields').append('<input type="text" name="firstname" />');
if (numText==7)
$(this).off('click')
});
I want a functionality that i will type some text on the textbox and the value will be picked up by the jquery and will be stored in some variable ,how to achieve that? i am using jquery bind function but it is not suiting my purpose .
This is my textbox
<aui:input inlineField="true" label="" name="interviewCC" id="interviewCC" size="45" value=""></aui:input>
and i am using this jQuery function
$("#interviewCC").bind("click", function () {
value = $("#interviewCC").val();
alert(value)
});
but it is not picking the value i want that when i will type something on the textbox that value will be picked up.Please somebody help.
The problem is that you listen to the 'click' event and not the 'keypress' event.
Try this:
$('#interviewCC').keypress( function(e) {
var value = $("#interviewCC").val();
alert(value)
});
Use
$("#interviewCC").keypress(function () {
value = $("#interviewCC").val();
alert(value);
});
You can use the jQuery function .keyup() which will figure out when a key has been pressed and then the press has finished.
$(document).ready(function() {
$('input#text').keyup(function() {
$('.output').text($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="text" type="text" />
<div class="output"></div>
.keyup() Documentation
I have a simple problem (hopefully), but I am unable to find a clear solution.
I have a datatable, which has a text input field. The user enters text into the text field, and hits the enter key. This automatically filters from the text entered.
I was hoping to use the onkeyup event to trigger so when a user enters a value in the text field, the datatable automatically updates, rather than the user having to press enter.
<input type="text" name="input" class="filter" id="input" onkeyup="functionName(this)" value="">
<script>
function functionName(e) {
alert(e.value);
}
</script>
This code works, so when I enter a value, it pops an alert up displaying the entered value.
Is it possible i can change the alert, to do a submit, or replicate what the "enter" key does.
From trying to find a solution, it is more difficult because it is not a form, as it uses ajax so the .submit methods will not work.
I was also hoping a solution like this could work
<script>
var e = jQuery.Event("keyup");
e.which = 13; // Enter
$("#input").trigger(e);
</script>
I know there are many similar topics, and I have looked, but none of them seem to be the right solution for me.
Thanks for the help.
//
Edit
//
Based on the keyup issue, how can I refocus cursor after filtering. Is this done at the same time as filtering?
$obj.find('input.filter').on('keyup',function(e){
e.preventDefault();
ajax($obj);
});
You're using jQuery, so there's no real need to use onclick="", Secondly try to avoid to use reserved names for IDs & Classes (e.g. #input). Lastly, you can mimic the form submission by using $.post() on each .keyup event like below:
<input type="text" name="input" class="filter" id="searchinput" value="" />
<script>
$(document).ready(function() {
$(document).on('keyup', '.filter', function( event ) {
$.post( 'yourapi.php', { input: $(this).val() }, function( data ) {
//Refocus the <input />
$('#searchinput').focus();
});
});
});
</script>
As you can code in jquery too. Then you can go with this code......
$(document).ready(function(){
$(".filter").keyup(function(){
var text_input_text = $(this).val();
//here is your ajax post request
$.post('url for post', {filter_text: text_input_text}, function(response){
console.log(response);
});
});
});
Here we have covered the keyup event and ajax post.
Hope this will help you.
$(document).ready(function(){
$("input").keyup(function(event)
{
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode != '13')
{
var e = jQuery.Event("keyup");
e.which = 13; // Enter
$("input").trigger(e);
}
else {alert("Enter triggered");
}
});
});
DEMO JSFiddle
I use VS2010,C# to develop an ASP.NET web app, I'm going to implement a search box like the one used in Stackoverflow (or other sites), initially there is a phrase (for instance "search") in the search text box, when user click in text box, its text is emptied and user can type his phrase, but if he leaves the text box (lost focus) empty, again the phrase "search" is displayed, how can I implement this nice effect?
thanks
This is the textbox watermark plugin which I use:
http://code.google.com/p/jquery-watermark/
I then created the following code which uses the title attribute for the watermark text for all elements with the .textbox_watermark class
var Textbox_Watermark =
{
init: function () {
var textboxWatermarks = $(".textbox_watermark");
for (var i = 0, ii = textboxWatermarks.length; i < ii; i++) {
$(textboxWatermarks[i]).watermark(textboxWatermarks[i].title);
}
}
}
Textbox_Watermark.init();
Then when focus is on the textbox, the watermark is removed.
You will need the jQuery framework for this to work
Here is a little script I use for just this purpose. It does required JQuery though, but if that is an option for you then give it a try. (there is probably a javascript alternative for this too, but I dont know it)
function addInputBlur(selector, text) {
var element = $(selector);
element.blur(function () {
if ($(this).val() == "") {
$(this).val(text);
$(this).addClass("InputBlur");
}
else {
$(this).removeClass("InputBlur");
}
});
element.focus(function () {
if ($(this).val() == text) {
$(this).removeClass("InputBlur");
$(this).val("");
}
});
element.blur();
}
Note: the "selector" param should be a JQuery selector value (i.e. "#MyTextbox")
Also, the "InputBlur" CSS class is just the style I use for the grey/italic font
I have seen the view source for stack overflow and what i notice is that they have a attribute named placeholder
<div id="hsearch">
<form id="search" action="/search" method="get" autocomplete="off">
<div>
<input autocomplete="off" name="q" class="textbox" **placeholder="search"** tabindex="1" type="text" maxlength="140" size="28" value="">
</div>
</form>
</div>
try this it works for mozilla ,, check for others
hope it helps
<input type="text"
onblur="javascript:if(this.value=='') this.value= this.defaultValue;"
onfocus="javascript:if(this.value==this.defaultValue) this.value='';"
id="txtSearch"
value="search"
name="txtSearch" />
You can do this in JavaScript using a function similar to this one:
/*
* applyDefaultValue() - Takes a DOM object and it's string value as paramters, when the element
* is focussed, the 'value' is blanked out, ready for user entry. When the item is blurred, if nothing was typed
* then the original value is restored.
*/
function applyDefaultValue(elem, val) {
elem.value = val;
elem.onfocus = function() {
if (this.value === val) {
this.value = ''; //On focus, make blank
}
}
elem.onblur = function() {
if (this.value === '') {
this.value = val; //If it's not in focus, use declared value
}
}
}
You can then apply this to items like this:
/*
* Onload function to set the default 'email address'/'search' value and blank out the password field
*/
window.onload = function() {
applyDefaultValue(document.getElementById('email'), 'Email Address');
}
It may be a correct behavior of change event, but the below behavior is bit annoying. When the value is updated from the field history (see explanation below), the event is not triggered.
Please see example code below. the result input field is updated with the change in input field 'input1'. The form and submit button is not fully relevant, but needed to submit a form to make the browser keep the history of field values.
To test:
enter any input in the field (say ABC)
Submit the form
enter first character of input from 1 (A)
use the down arrow to select the previous value + Enter
or use the mouse to select the previous value from the history
No input change is detected.
Which event/ how should this code should modify so that an event is generated whenever the input value is changed.
thanks.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body>
Result:<input type="text" id="result" readonly></input>
<form method="post" action="">
<input type="text" id="input1" />
<button type=submit>Submit</button>
</form>
<script >
$(document).ready(function() {
$('#input1').change(
function(){
$('#result').val($('#input1').val());
});
});
</script>
</body>
</html>
I think this has nothing to do with jQuery.
A change event should be dispatched when the content of a control has changed and the control loses focus. In practice, the implementation of the change event is inconsistent in browsers, e.g. Firefox dispatches a change event when radio buttons are clicked on rather then when they lose focus. Also in IE, selecting a value from a list of previous values then causing a blur event doesn't fire a change event.
Note that for form controls to be successful, they must have a name attribute with a value. A simple test case is:
<form action="#">
<input type="text" name="input1" onchange="alert('changed');">
<input type="submit">
</form>
One solution is to use the blur event instead and compare the control's current value to its defaultValue - if they're different, perform whatever it is you were going to do for the change event. If the value may be changed a number of times, after the first time you need to compare with the last value onblur rather than the defaultValue.
Anyhow, here's a function that can be called onblur to see if a text input has changed. It needs a bit of work if you want to use it with other types of form control, but I don't think that's necessary.
<form action="#">
<input type="text" name="input1" onblur="
var changed = checkChanged(this);
if (changed[0]) {
alert('changed to: ' + changed[1]);
}
">
<input type="submit">
</form>
<script type="text/javascript">
// For text inputs only
var checkChanged = (function() {
var dataStore = [];
return function (el) {
var value = el.value,
oValue;
for (var i=0, iLen=dataStore.length; i<iLen; i+=2) {
// If element is in dataStore, compare current value to
// previous value
if (dataStore[i] == el) {
oValue = dataStore[++i];
// If value has changed...
if (value !== oValue) {
dataStore[i] = value;
return [true, value];
// Otherwise, return false
} else {
return [false, value];
}
}
}
// Otherwise, compare value to defaultValue and
// add it to dataStore
dataStore.push(el, value);
return [(el.defaultValue != value), value];
}
}());
</script>
Try the keyup event:
$(document).ready(function() {
$('#input1').keyup(
function(){
$('#result').val($('#input1').val());
});
});
http://jsfiddle.net/kaptZ/7/
It seems like it's definitely a browser bug. Not much you can do besides implement your own change handler with focus and blur. This example is not very reusable, but it solved the problem and can be used as inspiration for something reusable.
http://jsfiddle.net/kaptZ/9/
var startValue;
var input1 = $('#input1');
input1.focus(function(){
startValue = this.value;
});
input1.blur(function(){
if (this.value != startValue) {
$('#result').val(this.value);
}
});
A dirty alternative is to use autocomplete="off"
It looks like this bug which was supposed to be fixed in November 2009.
In modern browsers you can use the input event and update as you type. It can be bound either to the text input:
$('#input1').bind('input', function(){
$('#result').val($('#input1').val());
});
Or to the form:
$('#input1').closest('form').bind('input', function(){
$('#result').val($('#input1').val());
});