I'm trying to set a default value for a search field. The idea is that the Search-Field has the value "Search" until the user clicks into it, then it should be empty. Also as long as it is "blank" (with "Search" as the value) it should have the class ".blank".
I tried this
<input autocomplete="off" class="" id="searchq" name="searchq" onblur="if (this.value == '') { this.value='Search'; jQuery(this).addClass('blank'); };" onfocus="if (this.value == 'Search') { this.value=''; jQuery(this).removeClass('blank'); };" type="text" value="" />
it works so far, but when I load the site, the field is just empty. I have to click inside the field first and then somewhere on the page to make the effect working.
I guess it has something to do with onBlur. Any ideas?
Thanks!
This is known as a watermark. see http://digitalbush.com/projects/watermark-input-plugin/ for an example
Another idea is to put placeholders in your input types:
(Note this is HTML5.)
<input type=text placeholder="Default text here"/>
this way the textfield will show in a grey text color: Default text here. Once clicked it will remove the text and replace it with your current text and when its empty it comes back.
Just give it the default value 'Search' hardcoded, as in
<input ... type="text" value="Search" />
Sounds like you just need to set the initial value to Search, directly in the input tag, like so:
<input autocomplete="off" class="blank" id="searchq" name="searchq" onblur="if (this.value == '') { this.value='Search'; jQuery(this).addClass('blank'); };" onfocus="if (this.value == 'Search') { this.value=''; jQuery(this).removeClass('blank'); };" type="text" value="Search" />
Note that we also set the initial class to blank as well.
I found the problem, my mistake: onBlur is called, when the user clicks somewhere else. onLoad is only allowed for the tags BODY and FRAMESET. The solution is to set the default value somewhere serverside (for me in the application_controller, if no search term is submitted).
Thanks anyway!
blur is when a field looses focus, it cant loose focus until it has focus to begin with, hence you need to click in the field, then click out to see it working. have you tried setting the class to .blank by default ?
<input autocomplete="off" class="blank" ....
Here's a snippet I use to do this. There may be simpler ways, but this works. Any item with class .cleardefault will have it's value cleared on first mouseover. Any item with class .setcleardefault will clear the default and, if the user has not put anything in the box, reset it to the default value on mouse out.
function ClearDefault(item) {
// clear the default value of a form element
if (item.defaultValue == undefined)
item.defaultValue = item.value;
if (item.defaultValue == item.value)
item.value = '';
} // ClearDefault
function SetDefault(item) {
// if item is empty, restore the default value
if (item.value == '')
item.value = item.defaultValue;
} // SetDefault
$(document).ready(function() {
$(".cleardefault")
.mouseover(function(){
ClearDefault(this);
})
$(".setcleardefault")
.mouseover(function(){
ClearDefault(this);
})
.mouseout(function(){
SetDefault(this);
});
/*
*/
});
Related
I have a form which has input fields that expect numbers only.
I'm using javascript to validate the form when the value of the field changes.
If the value is numeric, do nothing.
If the value is not numeric, set it to zero and put focus in that text field. Essentially, I'm trying to trap the cursor in that field until a numeric value is entered. For some unknown reason, focus is not being placed on that form element. cell.focus() does not work. I've even tried document.getElementById(cel.getAttribute("ID")).focus(); What might I be doing wrong?
<html>
<head>
<script>
function NAN(cell){
if (cell.value != "") {
var re = /^(0|[1-9][0-9]*)$/;
if (re.test(cell.value) == false) {
alert('You must supply a numeric value greater than 0.');
cell.value = "0";
cell.focus();
}
}
}
</script>
</head>
<body>
<input type="text" name="num" value="" onchange="NAN(cell)"/>
</body>
</html>
Your problem is in the onchange attribute:
<input type="text" name="num" value="" onchange="NAN(cell)"/>
The value is executed as JavaScript code directly. You're passing code, not just a generic signature or prototype.
Inside those event handler snippets, there's a special object this defined, referring to the current DOM element (the input tag in this example).
(Just to mention it, there is also a second predefined object event, which most likely caused your confusion.)
As a simple fix for your issue, replace cell with this in the call and it should work:
<input type="text" name="num" value="" onchange="NAN(this)"/>
It's also important to note that you should keep in mind that this verification requires JavaScript to be executed. If it's disabled, the user might still pass any values, so you should check the value server side as well (assuming this isn't just client-only code).
As an alternative to using JavaScript, you could just use HTML5 to force a specific pattern on inputs. In this case this would be trivial to do:
<input type="text" name="num" value="" pattern="(?!0)\d+" title="Quantity">
The user won't be able to submit the form unless the pattern is validated, so there's no need to force the input focus. The pattern always has to match the full value, from beginning to the end. The title attribute is typically used to provide more information in the error popup.
There are two things done:
You have to change cell to this with onchange.
According to this question at least with Firefox setTimeout has to wrap this focus-method so that it works as expected.
And a more user-friendly approach is inserted as well at the second input-field.
Hope this example helps you:
function NAN(cell) {
if (cell.value != '') {
var re = /^(0|[1-9][0-9]*)$/;
cell.value = cell.value[0]=='0'?+cell.value:cell.value;
if (re.test(cell.value) == false) {
alert('You must supply a numeric value greater than 0.');
cell.value = '0';
setTimeout(function () {
cell.select();
cell.focus();
}, 0);
}
}
}
/*
* a more user friendly approach
*/
function NAN2(cell) {
if (cell.value != '') {
var re = /^(0|[1-9][0-9]*)$/;
cell.value = cell.value[0]=='0'?+cell.value:cell.value;
if (re.test(cell.value) == false) {
alert('You must supply a numeric value greater than 0.');
cell.value = '0';
setTimeout(function () {
cell.select();
cell.focus();
markElement(cell);
}, 0);
}
else{
tickElement(cell);
}
}
}
function tickElement(cell){
cell.setAttribute('style','border: 1px solid green');
}
function markElement(cell){
cell.setAttribute('style','border: 1px solid red');
}
<p>
Your approach(onchange):
<input type="text" name="num" value="" onchange="NAN(this)"/>
</p>
<p>
Or you can use a more user friendly approach to notify an user right now when they are tipping something wrong (onkeyup):
<input type="text" name="num" value="" onkeyup="NAN2(this)"/>
</p>
How i can detect when an input value change when i'm filling the input with the path of imagen getting from filemanager.
I dont even know how it's called when the input is getting filled that way. (After select the image, automatically the input get the path as value)
I already tried this:
$('#my-input').on('change', function() {
alert("You changed the value of the input");
})
$('#my-input').on('input', function() { alert('some text') })
But this only works when user get interaction with the input i mean on keyup, keydown, etc.
Is that possible to do?
Thanks and sorry for the bad english.
If I understand correctly, you want to do this
document.getElementById('my-element').onchange();
after you fill the value via code as opposed to user entering a value.
Example here
document.getElementById('my-button').onclick = fillInput;
document.getElementById('my-input').onchange = inputChanged;
function fillInput(){
document.getElementById('my-input').value = "Test value";
document.getElementById('my-input').onchange();
}
function inputChanged(){
document.getElementById('my-input').style.border = "1px solid green";
}
<input id="my-input" type="text" />
<input id="my-button" type="button" value="Fill Input" />
I am trying to implement a search box. The following is the code (both HTML and JS)
HTML
<form>
<input type="text" ng-model="searchVar" class="searchbox">
<input type="button" value="Search" ng-click="Search()" class="button">
</form>
JS
var Search = function() {
/* code to implement the table content loading part */
//The following is what I have to filter out the table contents based on input in the text field
if (($scope.searchVar) && (tableContent[i].indexOf($scope.searchVar) !== -1)) {
ItemsToDisplay.push(tableContent[i])
}
//Call function to load table
}
What is happening is that, if I enter some string into the input text field, the search algorithm works fine and only the relevant items are displayed. However, if I clear the contents of the search box and click on Search button, nothing is displayed in the table. That is, when the text field is cleared and clicked on the search button, it is as if ItemsToDisplay is empty and the if condition fails.
Can someone explain why this is the case? And how I can solve this?
Before your indexOf($searchVar) you should check that searchVar is != ''. Otherwise no item will be displayed afterward. A suggestion, javascript has a really great console.log functionality that will help you a lot when it comes to if branches
If you cleared input, the value of $scope.searchVar willbe undefined and your condition
if (($scope.searchVar) && (tableContent[i].indexOf($scope.searchVar) !== -1)) {...}
will be false, so you didn't push into ItemsToDisplay and nothing append.
I suggest you to write an else statement :
if (($scope.searchVar) && (tableContent[i].indexOf($scope.searchVar) !== -1)) {...}
else {
ItemsToDisplay.push(tableContent[i]);
}
U can try with,
if (($scope.searchVar) != undefined)
or
if (typeof ($scope.searchVar) != 'undefined')
when you do not enter anything in INPUT box then its value become UNDEFINED.
you will have to check in if() condition, if input is undefined then write your logic, if input has some value then write your logic.
<form>
<input type="text" ng-model="searchVar" class="searchbox">
<input type="button" value="Search" ng-click="Search()" class="button">
</form>
var Search = function()
{
if ( $scope.searchVar == undefined){
//Do something, input box is undefined
}
if (($scope.searchVar) && (tableContent[i].indexOf($scope.searchVar) !== -1)) {
ItemsToDisplay.push(tableContent[i]);
}
}
How can I check if a field is a radio button?
I tried if(document.FORMNAME.FIELDNAME.type =='radio') but document.FORMNAME.FIELDNAME.type is returning undefined.
The html on the page is
<input name="FIELDNAME" type="radio" value="1" >
<input name="FIELDNAME" type="radio" value="0" >
Unless I am taking the whole approach wrong. My goal is to get the value of an input field, but sometimes that field is a radio button and sometimes its a hidden or text field.
Thanks.
Your example does not work because document.FORMNAME.FIELDNAME is actually an array with 2 elements (since you have 2 inputs with that name on the form). Writing if(document.FORMNAME.FIELDNAME[0].type =='radio') would work.
EDIT: Note that if you don't know if document.FORMNAME.FIELDNAME is a radio (ie you might have a text/textarea/other) it is a good idea to test if document.FORMNAME.FIELDNAME is an array first, then if the type of it's first element is 'radio'. Something like if((document.FORMNAME.FIELDNAME.length && document.FORMNAME.FIELDNAME[0].type =='radio') || document.FORMNAME.FIELDNAME.type =='radio')
In case you don't have a form then maybe go by attribute is an option.
var elements = document.getElementsByName('nameOfMyRadiobuttons');
elements.forEach(function (item, index) {
if (item.getAttribute("type") == 'radio') {
var message = "Found radiobutton with value " + item.value;
if(item.checked) {
message += " and it is checked!"
}
alert(message);
}
});
Your code should work, but you could try the following:
document.getElementById('idofinput').type == 'radio'
Edit: Your code doesn't work for the reason mihaimm mentions above
I notice that at some websites like http://academia.edu/, the signup form has some "place-holder" in their text input field. Such that in a textbox, there's no label but a rather slight font "First name" word inside the text box.
When using Firebug to investigate, I see the following code:
<input class="standard_text magic-default magic-default-on" id="user_first_name" name="user[first_name]" size="30" type="text" value="First Name">
It looks like there's some "magic" javascript happen behind the scene. But since I'm not familiar with javascript debugging yet, I can't trace out how they do that yet.
Does anyone know how to produce that effect?
For modern browsers you can use the HTML5 placeholder attribute.
This will achieve the result you're after without any Javascript and will scale (won't do anything) in older browsers.
<input placeholder="First Name">
To get this working in older browsers you can include a little bit of jQuery:
$('input:text').focus(function(){
if ( $( this ).val () === $( this ).attr ( 'placeholder' ) ) {
$(this).val('');
}
}).blur(function(){
if($(this).val() == "")
{
$(this).val($(this).attr('placeholder'))
}
}
);
Working Example
You have to create a "onFocus" event handler for the input box, and clear the value of said input box. Off course you only clear the value if it's the default value ("First Name" in your example), so that you don't clear away whatever user entered if he returns to the input later.
You could also attach a "onBlur" event handler, and restore the value of the input box back to the default value (if user didn't enter anything).
<input id="user_first_name" name="user[first_name]" size="30" type="text" value="First Name" onFocus="inputFocus('First Name', this)" onBlur="inputBlur('First Name', this)">
<script type="text/javascriptt">
function inputFocus(ph, el){
if(el.value == ph)
el.value = "";
}
function inputBlur(ph, el){
if(el.value == "")
el.value = ph;
}
</script>
HTML5 placeholder is what you're looking for:
http://diveintohtml5.info/forms.html
In your case it would be:
<input name="firstname" placeholder="First name">
But also you can do it 100% with javascript:
http://lab.dotjay.co.uk/experiments/forms/input-placeholder-text/