ASP.NET implementing a search box like stackoverflow search box - javascript

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');
}

Related

Clear input, textarea on blur and default if field is blank

I am trying to clear two input fields with classes assigned, and one textarea with a class assigned of their default values on blur and return it to default only if the field is blank when the field is exited. If the user has included their own text I require that to stay.
This is what I have thus far:
$("input, textarea").focus(function() {
this.value = "";
});
$(".namefield").on("blur", function() {
$(this).val("Name");
});
$(".emailfield").on("blur", function() {
$(this).val("Email");
});
$(".messagefield").on("blur", function() {
$(this).val("Message");
});
First a quick note, the HTML placeholder attribute will do exactly what you describe natively. I'd encourage that as a first choice if possible. The implementation would simply be:
<input type="text" class="namefield" placeholder="Name" />
More reading on it is here: http://www.w3schools.com/tags/att_input_placeholder.asp
If you can't add attributes to the elements, but you have the value set, you can add the attributes dynamically using jQuery. You could use the jQuery method we talked about originally, or you could just add the placeholder attribute.
Here are both examples, I've also updated the JS Fiddle with a working example.
Using Placeholder
$(document).ready(function() {
$("input, textarea").each(function() {
$(this).attr('placeholder',$(this).val());
$(this).val('');
})
})
Using data-default in conjunction with the original answer
$(document).ready(function() {
$("input, textarea").each(function() {
$(this).data('default',$(this).val());
})
})
Original Answer:
If you still need to use jQuery, you can set and check the state and compare it against a default value. Something like this would work:
HTML
<input type="text" class="namefield" data-default="Name" value="Name" />
<input type="text" class="emailfield" data-default="Email" value="Email" />
JavaScript
$(document).ready(function() {
$("input, textarea").focus(function() {
if($(this).data('default') == $(this).val()) {
$(this).val('');
}
});
$("input, textarea").blur(function() {
if($(this).val() == '') {
$(this).val($(this).data('default'));
}
});
})
You can see it working in this JS Fiddle: https://jsfiddle.net/77Lk4kep/1/
Hope that helps!

How to not clear textarea value when searching with Javascript onsearch Event

I'm using this method http://www.w3schools.com/jsref/event_onsearch.asp
What I want is the text that I searched with to stay in the textarea or at least get back to the textarea, not disappear because I click the enter button.
I understand that it clears the text because in the link they describe the function like this: "The onsearch event occurs when a user presses the "ENTER" key or clicks the "x" button in an element with type="search".
So it acts as if I click the x button, although, there must be a way to get the text back there after?
This is my current code html code
<form> <input type="search" name="search" id="searchid" onsearch="OnSearch(this)"/> </form>
This is my javasript/jquery
function OnSearch(input) {
alert("The current value of the search field is " + input.value);
$("#searchid").val(input.value);
}
What happens now is that it correctly alerts the value the textarea is holding, although it wont add back the textarea value.
EDIT: It seems like the page reloads, how can i insert code that runs after page reload?
Well I have an alternative. Since you cannot avoid the clear functionality you can store the text each time keypressed in a global variable and if x is pressed retain the value in textbox. Below is the code:
DEMO HERE
var text="";
function OnSearch(input) {
if(input.value == "") {
$("#searchid").val(text);
}
else {
alert("You searched for " + input.value);
}
}
$(document).on('keyup','#searchid', function (e) {
text=$(this).val();
console.log(text);
});
UPDATE
if your html is inside the form you can do as below:
Check in document.ready if it already had a text and if yes set it!!
$(document).ready(function()
{
if(localStorage.getItem("text")!="")
{
$("#searchid").val(localStorage.getItem("text"));
}
});
function OnSearch(input) {
if(input.value == "") {
$("#searchid").val(localStorage.getItem("text"));
}
else {
alert("You searched for " + input.value);
}
}
$(document).on('keyup','#searchid', function (e) {
localStorage.setItem("text",$(this).val());
});
I think this will help you to display the alert dialog symbol as that:
HTML:
<input type="search" name="search" id="searchid"/>
Javascript:
document.getElementById("searchid").onsearch = function() {yourfunctionname()};
/* Put this before the below function or in the top of the document */
function yourfunctionname(){
var x = document.getElementById("searchid").value;
alert("The current value of the search field is "+x);
/* Or do what ever you wish */
}
/*Remember to replace the yourfunctionname with your function's name */
OR If it is in a form try this:
Your form should look like this:
<form method="/* method */" action="/* action */" onSubmit="yourfunctionname()">
<input type="search" name="search" id="searchid"/>
/* Rest of your form*/
</form>
Javascript:
document.getElementById("searchid").value = localStorage.getItem("saved");
document.getElementById("searchid").onsearch = function() {yourfunctionname()};
/* Put this before the below function or in the top of the document */
function yourfunctionname(){
var x = document.getElementById("searchid").value;
alert("The current value of the search field is "+x);
/* Or do what ever you wish */
/* The below code does the trick*/
localStorage.setItem("saved", x);
location.reload();
return false;
}
/* Remember to replace the yourfunctionname with your function's name */
If you are having a different function to submit the form then replace your form's onsubmit attribute with that function's name and a word "return" before it's name and add the below javascript inside that function.
var x = document.getElementById("searchid").value
localStorage.setItem("saved", x);
location.reload();
return false;
If you wanted something else then please comment.
Please accept as if it solves your problem.
And thanks...
Lastly for more just comment

how to add event handler for input text box

My program should contain both name search and ID search functionality, when user clicks the name search button, a name search validation is triggered to make sure that the required text field is not empty, on the other hand, when user clicks the id search button, an id search validation is triggered to make sure that a different required text field is not empty. So on the HTML file, I have the following jQuery and HTML codes.
$(document).ready(function() {
$('#submitIDSearch').bind('click', validateIDSearch);
$('#submitNameSearch').bind('click', validateNameSearch);
$('#searchLastName').bind('click', validateNameSearch);
$('#searchFirstName').bind('click', validateNameSearch);
$('#searchID').bind('click', validateIDSearch);
});
var validateNameSearch = function(event) {
var btnSrchLastName = getRef('searchLastName');
if (null != btnSrchLastName) {
var len = btnSrchLastName.value.length;
if (0 == len) {
alert('Last Name is a required field, please input Last Name.');
$('#searchLastName').focus();
return false;
}
}
return true;
}
var validateIDSearch = function(event) {
var btnSrchID = getRef('searchID');
if (null != btnSrchID) {
var len = btnSrchID.value.length;
if (0 == len) {
alert('ID is a required field, please input ID.');
$('#searchID').focus();
return false;
}
}
return true;
}
And I have the following HTML code:
<form id="infoForm" name="checkAbsenceForm" method="post" action="absenceReport.htm">
<label class="q">ID * <input id="searchID" name="searchID" maxlength="9" /></label>
<input id="submitIDSearch" type="submit" value="Search ID"/>
<hr />
<label class="q">First Name <input id="searchFirstName" name="searchFirstName" maxlength="23"></label>
<br />
<label class="q">Last Name * <input id="searchLastName" name="searchLastName" maxlength="23" /></label>
<input id="submitNameSearch" type="submit" value="Search Name"/>
<hr />
</form>
The code behaves correctly except for one problem, when ever the user clicks on the textbox, a click event is fired, which cause a pre-generation of the alert message box.
I observed that when the user types 'enter' key from a text field, a click event is triggered, instead of 'submit', so I guess my listener can only be bind to the click event.
May I ask if there's a workaround method to avoid event triggering from mouse clicking on the textbox?
Thanks a lot!
In case you still need help... http://jsfiddle.net/jaxkodex/Cphqf/
$(document).ready(function() {
$('#submitNameSearch').click(function(event) {
event.preventDefault();
if (validate($('#searchLastName'), 'Last name field is required.')) {
$('#infoForm').submit();
}
});
$('#submitIDSearch').click(function(event) {
event.preventDefault();
if (validate($('#searchID'), 'ID field is required.')) {
$('#infoForm').submit();
}
});
});
function validate(input, errorMsg) {
if (input.val() == null || input.val().length == 0) {
alert(errorMsg);
return false;
}
return true;
}
Since you are using jQuery, You can submit the form whenever a button is clicked with $('#infoForm').submit(); If you check you'd need to use button inputs and no submit inputs any more, since they will trigger the submit event. This is just one approach. If you are looking for live validation, you could use the blur events instead of click but in the text inbut and the click event to the buttons to make sure it works. I guess that overwritting the submit function would work when you have to do some ajax. Hope it helps.
[Edit] If you want to keep the buttons as submit you can do some thing like: http://jsfiddle.net/jaxkodex/S5HBx/1/
You can use the submit event from the form, so it will check every time someone submits the form. jQuery - Submit
$('#infoForm').submit(function (event){
if (!validateIDSearch() && !validateNameSearch()){
event.preventDefault(); // Prevent the submit event, since didn't validate
}
// Will continue to the dafault action of the form (submit it)
});
You just need to set what button the user has selected and do validation based on that during form submit.
searchLastName searchFirstName submitNameSearch are calling validateNameSearch, and submitIDSearch searchRUID are calling validateIDSearch
$(function () {
var validateFx = null; //none selected;
$('#submitNameSearch, #searchLastName, #searchFirstName')
.bind('click', function () {
validateFx = validateIDSearch;
});
$('#searchIDSearch, #searchRUID')
.bind('click', function () {
validateFx = validateNameSearch;
});
$('#infoForm').submit(function (event){
event.preventDefault();
if (validateFx != null && validateFx ()) {
$(this).submit();
}
});
});

Javascript: select the text in the currently focussed input field

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.

how to set focus to first editable input element in form

Dynamically created form contains input elements. First elements may be disabled or readonly.
I tired code below to set focus to first elemnt which accepts data to enable fast data enttry form keyboard.
However if form fist element is disable or readonly, focus is not set.
How to set focus to first element which accepts data ?
<form style='margin: 30px' id="Form" class='form-fields' method='post' target='_blank'
action='Report/Render'>
...
<input id='_submit' type='submit' value='Show report' class='button blue bigrounded' />
</form>
<script type="text/javascript">
$(function () {
var elements = $('#Form').find(':text,:radio,:checkbox,select,textarea');
elements[0].focus();
elements[0].select();
});
</script>
Update
There are also hidden input fields, sorry. Answers provided set focus to hidden element. Answr containing function does not find any element.ˇ
Here is the update testcase:
$(function () {
$("#form :input:not([readonly='readonly']):not([disabled='disabled'])").first()
.focus();
});
How to set focus to vist visible, enabled and not readonly element ?
Update 3
I tried Row W code where input element was added.
Now it sets focus to second element. Testcase is shown at Revision 5 of Rob W's answer
Use the following code:
var elements = $('#Form').find(':text,:radio,:checkbox,select,textarea').filter(function(){
return !this.readOnly &&
!this.disabled &&
$(this).parentsUntil('form', 'div').css('display') != "none";
});
elements.focus().select();
If you only want to select the first element, the following code is more efficient:
$('#Form').find(':text,:radio,:checkbox,select,textarea').each(function(){
if(!this.readOnly && !this.disabled &&
$(this).parentsUntil('form', 'div').css('display') != "none") {
this.focus(); //Dom method
this.select(); //Dom method
return false;
}
});
Update: if you want to have the elements in the same order, use:
var elements = $("#form").find("*").filter(function(){
if(/^select|textarea|input$/i.test(this.tagName)) { //not-null
//Optionally, filter the same elements as above
if(/^input$/i.test(this.tagName) && !/^checkbox|radio|text$/i.test(this.type)){
// Not the right input element
return false;
}
return !this.readOnly &&
!this.disabled &&
$(this).parentsUntil('form', 'div').css('display') != "none";
}
return false;
});
Use jQuery's :not() selector:
$("#myForm :input:not([readonly='readonly']):not([disabled='disabled']):reallyvisible").first()
.focus();
Here's a working fiddle.
EDIT:
To meet the new requirement you posted in the comments, you'll have to extend the :visible selector to check for parent visibility (untested):
jQuery.extend(
jQuery.expr[ ":" ],
{ reallyvisible : function (a) { return !(jQuery(a).is(':hidden') || jQuery(a).parents(':hidden').length); }}
);

Categories

Resources