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
Related
As title. I have a page with several inputs with type="text", and set them with clear buttons generated by the js code:
function SetClearButtonInTextBox(Callback) {
if (!window.document.documentMode) {
$("input").each(function () {
var im = $(this);
if (!$(this).parent().hasClass("text-input-wrapper") && !$(this).hasClass("btn")) {
$(this).wrap("<div class='text-input-wrapper'></div>");
$(this).after("<button class=\"Covered\" type=\"button\">×</button>");
}
$(this).closest("div.text-input-wrapper").find("button").mousedown(function () {
im.val("");
im.change();
//return false;
});
});
}
}
And my inputs like this:
<input name="ModelA" ng-model="dl.ModelA" ng-change="ClearText(this,dl.ModelA);" value=""/>
<input name="ModelB" ng-model="dl.ModelB" ng-change="ClearText(this,dl.ModelB);" value=""/>
And I made the "ClearText" function as:
$scope.ClearText=function(target, ngModelTo){
if (target.target.value == "") {
ngModelTo = "";
}
}
I want when I click the clear button inside input, the binded value and the textbox will also be cleared, but I found that only my textbox is cleared but the binded value isn't.
Could someone guide me to make it?
How to call javascript function when value in textarea was change ?
When fill data into textarea id="yyyy", textarea id="xxxx" will change value too. This function are work good.
When textarea id="xxxx" change value, i want to call function check2 , how can i do ?
please do not change code in function check and id="yyyy"
https://jsfiddle.net/9b6h897d/3/
<textarea id="yyyy" onkeyup="check(this.value)"></textarea>
<textarea id="xxxx" onchange="check2(this.value)" ></textarea>
<script>
function check(value){
document.getElementById("xxxx").value = value;
}
function check2(value){
alert(value);
}
</script>
The standard events for <textarea> are keypress, keydown, or keyup. To do what you want you'll have to trigger the onchange in one of the functions. This makes most sense inside the first function called check.
document.getElementById("textarea2").addEventListener("change", function(event) {
console.log("Textarea two was changed.");
});
function check(element) {
var textarea2 = document.getElementById("textarea2"),
event = new Event('change');
textarea2.value = element.value;
textarea2.dispatchEvent(event);
};
<textarea id="textarea1" onkeyup="check(this);"></textarea>
<textarea id="textarea2" onkeyup="check(this);"></textarea>
Updated fiddle : https://jsfiddle.net/9b6h897d/6/
When you change the value in check call the check2 method like :
function check(value){
document.getElementById("xxxx").value = value;
check2(value).
}
i think it's better to use oninput if you want to track the user changes.
if you don't want to change the content of check() you have to call the both function in the oninput :
<textarea id="yyyy" oninput="check(this.value);check2(this.value)"></textarea>
New fiddle : https://jsfiddle.net/9b6h897d/9/
Hope this will help you.
Create just one function that both use, within the function check to see what textarea called the function and then write your separate code for each.
This is just sudo code that I'm writing off my phone, so it may have minor errors you need to fix.
var userEdit = true;
function(ta) {
if (ta.Id == 'xxx')
{
// Do code for xxx text area
userEdit = false;
// update yyy via code
userEdit = true;
} else if (ta.Id == 'yyy' && userEdit) {
// Do code for yyy text area change only when a user edits it
} else if (ta.Id == 'yyy' && !userEdit) {
// Do code for yyy text area change only when your code edits it
}
}
You could also use onblur instead of onchange, onblur gets called when a user changes the focus out of a object. Like after they type in a input and then tab or click into another input or button it will get fired.
I didnt know how to properly name my question, but here goes.
In my html i have a "form" but not
<form></form>
.It is just a couple of selects, radio buttons and text inputs.
I enter, check and select values and according to these values, some computation is done. This "form" is computing on every keydown, blur, change. So when I change one value it will immediately recalculate the results with new value.
I would like to alert the user, when he didnt fill any of the necessary inputs. Here is how it works now (this is in a separate .js file)
function calculator() {
// Here is code that gathers the data from html
// and here are also some computations (many if-s)
// The code is too long to be putted here
}
$(function () {
$('select, input').on('keydown blur change', calculator);
});
I tried to put a if statement inside of my calculator function:
function calculator() {
// Here is code that gathers the data from html
// and here are also some computations (many if-s)
// The code is too long to be putted here
if (val1 == '' && sadzba == '' && viem == '' && ...) {
alert('You have to fill all necessary fields!')
}
}
This obviously caused, that the alert was popped every time I enter / choose new value, because at the beginning all variables are empty / with no value.
So how can I achieve, this situation: User fills in the "form" except of (for example)one value and only then will the alert pop up.
Than you.
I suggest to do the check on submit and return false if one of the fields is empty, preventing the form to be submitted.
$('form').on('submit', function () {
if (val1 == '' || sadzba == '' || viem == '') {
alert('You have to fill all necessary fields!');
return false;
} else { return true; }
});
Use a different event handler for the onblur event since that's when the cursor has left the input box. (It also prevents the event handler from firing all the time. That's a pretty expensive process and it can slow your page down)
$('select, input').on('blur', didTheyLeaveTheFieldEmpty);
Hope I understood you right, you can try this:
function calculator(event) {
if ( $(event.target).val().length == 0 ) {
alert('fill the field');
}
}
$('select, input').on('keyup', calculator);
even if you don't want a form with a submit buton you can create a button
and trigger your code on it's click
<input type="button" class="calculate">
$(function () {
$('.calculate').on('click', calculator);
});
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');
}
I have a form that has default values describing what should go into the field (replacing a label). When the user focuses a field this function is called:
function clear_input(element)
{
element.value = "";
element.onfocus = null;
}
The onfocus is set to null so that if the user puts something in the field and decides to change it, their input is not erased (so it is only erased once). Now, if the user moves on to the next field without entering any data, then the default value is restored with this function (called onblur):
function restore_default(element)
{
if(element.value == '')
{
element.value = element.name.substring(0, 1).toUpperCase()
+ element.name.substring(1, element.name.length);
}
}
It just so happened that the default values were the names of the elements so instead of adding an ID, I just manipulated the name property. The problem is that if they do skip over the element then the onfocus event is nullified with clear_input but then never restored.
I added
element.onfocus = "javascript:clear_input(this);";
In restore_default function but that doesn't work. How do I do this?
Use
element.onfocus = clear_input;
or (with parameters)
element.onfocus = function () {
clear_input( param, param2 );
};
with
function clear_input () {
this.value = "";
this.onfocus = null;
}
The "javascript:" bit is unnecessary.
It looks like you don't allow the fields to be empty, but what if the user puts a single or more spaces in the field? If you want to prevent this, you need to trim it. (See Steven Levithans blog for different ways to trim).
function trim(str) {
return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
If you really want to capitalize the strings you could use:
function capitalize(str) {
return str.substr(0, 1).toUpperCase() + str.substr(1).toLowerCase();
}
By clearing the onfocus event you have created a problem that should not have been there. An easier solution is to just add an if-statement to the onfocus event, so it only clears if it is your default value (but I prefer to select it like tvanfosson suggested).
I assume that you on your input-elements have set the value-property so that a value is shown in the input-elements when the page is displayed even if javascript is disabled. That value is available as element.defaultValue. Bonuses by using this approach:
You only define the default value in one place.
You no longer need to capitalize any value in your handlers.
The default value can have any case (like "John Y McMain")
The default value no longer needs to be the same as the name of the element.
.
function clear_default(element) {
if (trim(element.value) == element.defaultValue ) { element.value = ""; }
}
function restore_default(element) {
if (!trim(element.value).length) { element.value = element.defaultValue;}
}
I would suggest that you handle it a little differently. Instead of clearing the value, why not just highlight it all so that the user can just start typing to overwrite it. Then you don't need to restore the default value (although you could still do so and in the same way if the value is empty). You also can leave the handler in place since the text is not cleared, just highlighted. Use validation to make sure the value is not the original value of the input.
function hightlight_input(element) {
element.select();
}
function restore_default(element) // optional, do we restore if the user deletes?
{
if(element.value == '')
{
element.value = element.name.substring(0, 1).toUpperCase()
+ element.name.substring(1, element.name.length);
}
}
<!-- JavaScript
function checkClear(A,B){if(arguments[2]){A=arguments[1];B=arguments[2]} if(A.value==B){A.value=""} else if(A.value==""){A.value="Search"}}
//-->
<form method="post" action="search.php">
<input type="submit" name="1">
<input type="text" name="srh" Value="Search" onfocus="checkClear(this,'Search')" onblur="checkClear(this,' ')">
</form>