How not to grab default value of inputbox - javascript

I am grabbing the value of input box and passing to the URL as querystring. I dont want to grab the default value "Enter Keywords(address....) which is controlled to show or hide by the following:
//**onClick and OnLostFocus (focus and blur) events on textareas and input textboxes**
$('input[type="text"], textarea').focus(function () {
defaultText = $(this).val();
$(this).val('');
});
$('input[type="text"], textarea').blur(function () {
if ($(this).val() == "") {
$(this).val(defaultText);
}
});
<input name="KeywordBox" class="BasicSearchInputBox" type="text" size="300" value="Enter Keywords (address,city and state OR zipcode)"/>
How not to grab the default text but just user input?? in jquery?

I usually add some default class name to the input field, then clear it when the user types. That way I can tell if the default "watermark" text is there, or user data.

The proper way to do this would be to use placeholder and fallback for older browsers.
For your current problem you can just check for that default text when you grab the value. Something like:
$('form').submit(function(){
if (~$('input').val().indexOf(defaultText)) {
// Not found, do your ajax stuff
}
});

The code you have above doesn't really do default values (placeholder). If someone first types 'anything' into the field, then clears the value from the field, your code will reset it to 'anything' instead of 'Enter Keywords...'
You need a plugin like http://archive.plugins.jquery.com/project/defaultvalue
<input placeholder="Enter a username…" type="text">
<input placeholder="…and a password" type="password">
<script>
$(' [placeholder] ').defaultValue();
</script>
If you really want to write it on your own, the simplest steps are
Add a placeholder property in the input field
onfocus: clear input.value if input.value equals input.placeholder
onblur: set input.value to input.placeholder if input.value is empty

You can do it with something like:
function togglePrompt() {
if (this.value == this.defaultValue) {
this.value = '';
} else if (this.value == '') {
this.value = this.defaultValue;
}
}
window.onload = function() {
var el = document.getElementById('inp0');
el.onfocus = togglePrompt;
el.onblur = togglePrompt;
}
<input value="Enter text..." id="inp0">

Related

How to impose a required textbox in javascript

I have a problem with my chat.
Indeed, I have a text input with the required value.
When I click on Send, it returns empty instead of stopped sending...
Can you help me please ?
<script>
$("#submitmsg").click(function() {
var clientmsg = $("#usermsg").val();
$.post("chat-post.php", {
text: clientmsg
});
$("#usermsg").attr('required', true);
loadLog;
return false;
});
</script>
you could validate the input string like this if(clientmsg.trim()) .Better add the required=true in your html code
<input type='text' required="true">
And use with trim() they will remove the unwanted space from string
<script>
$("#submitmsg").click(function() {
var clientmsg = $("#usermsg").val();
if(clientmsg.trim()){
$.post("chat-post.php", {
text: clientmsg
});
loadLog;
}
return false;
});
</script>
Basically you need to add a condition before sending post request if the value of that message input is empty. Please check below :
<script>
$("#submitmsg").click(function() {
var clientmsg = $("#usermsg").val();
// This is the additional condition
if(clientmsg != '' || clientmsg != null){
$.post("chat-post.php", {
text: clientmsg
});
}
else{
alert('Please enter the message!');
}
$("#usermsg").attr('required', true);
loadLog;
return false;
});
</script>
In order for the required attribute to work, you need to have the input inside a form.
<form>
<input required type="text" />
</form>
I think there is simply no need to set the required attribute every time you click the button. You only need to do it once, so why not simply add the required attribute in the html?
Even if you don't want to add it in the HTML, just add it once.
<script>
$("#usermsg").attr('required', true); // Add the attribute required to the input
// Do the AJAX function after you submit the form.
// Before submitting, it will have to be validated, so you don't even have to validate it in JS. Just native HTML5
$("form").submit(function() {
// do the rest here
}
</script>

Input field - remove value when onClick events and restore the value if not set

In the input field I set a default value. The default value must be removed when click inside the field, but if the value insert is blank and the mouse cursor leave the field, must be restored the default value. The default value must be writing in the database.
For example:
Default value: 0
When I leave the input field and the value is blank,the default value is restored .
<input type="text" onclick="if(this.value == 'value') { this.value = ''; }" value="value" />
How to restore the default value if any value is set to input after click?
Thanks
Just attach listener to your input on the focus and blur events like bellow example ;
var inputToCheck = document.getElementById("inputNum");
inputToCheck.initialValue = inputToCheck.value || '';
inputToCheck.addEventListener("focus",function(e) {
this.value == this.initialValue ? this.value = "" : "";
});
inputToCheck.addEventListener("blur",function(e) {
this.value == "" ? this.value = this.initialValue : "";
})
<input type="text" id="inputNum" value="0" />
Another with jQuery :
var inputToCheck = $("#inputNum");
inputToCheck.data("initialValue", inputToCheck.val());
inputToCheck.on("focus",function(e) {
this.value == $(this).data("initialValue") ? this.value = "" : "";
}).on("blur",function(e) {
this.value == "" ? this.value = $(this).data("initialValue") : "";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="inputNum" value="0" />
Does using placeholder attribute serve your requirement
?
This will show default value if the field is left blank., But won't send it to server when form is submitted with field value is blank.If you want to save the default value when user submits the form with blank input, write an obsubmit handler for the form that sets the value to default, or implement it in the server side to save default value in db if value is blank.

HTML Form: How to remember text values of button click?

If you have a form, type some text into it, and press the Enter key, whenever revisiting that form you can double-click on the input box and see the past text submissions.
I have a site that when you press Enter OR click a button, it should take whatever is in the text box and use it for data processing.
This works totally fine when not surrounded by a form but when surrounded by a form an you press the Enter key, it does not act as an enter button push, I believe it's being overridden by the form.
My goal is to have the user be able to press the Enter key as well as click the button to submit the data, but to also remember the text values that were in the text box regardless of which way you submitted the data.
What I have:
<input type="text" id="username-field" class="form-control" placeholder="username">
<input class="btn btn-default" type="button" id="get-name" value="Get Name">
Javascript
$("#get-name").click(function() {
var name = $("#username-field").val();
// ... call other function with name ...
});
$("#get-name").keydown(function(e) {
if (e.which == 13) {
var name = $("#username-field").val();
// ... call other function with name ...
}
");
What I would like to use:
<form>
<input type="text" id="username-field" class="form-control" placeholder="username">
</form>
I tried doing e.preventDefault() when the Enter key is pressed, but this does not remember the text in the input field.
I also considered doing a small cache type thing but am unsure of how I'd go about this.
Any help would be much appreciated!
Thanks!
Doesn't use form at all. Just, why you added it, if you don't use it as intended?
You either mistyped provided code copy-paste, or have errors in yours script (the $("#get-name").val() mistake).
If you want to prevent form from submission, you should e.preventDefault()-it in submission handler, and return false from it:
$('#form-id').submit(function (e) {
e.preventDefault();
// do smth. else here
...
return false;
})
Saving/retriving data with localStorage for HTML5-supporting browsers:
$(function () {
$('form input[type=text]').doubleclick(function () {
var id = $(this).attr("id");
value = localStorage.getItem("form_xxx_" + id);
// do smth. with cached value, ie:
if (value != "")
$(this).val(value); // put in textfield
});
});
$('form').submit(function (e) {
$('form input[type=text]').each(function () {
var id = $(this).attr("id");
localStorage.setItem("form_xxx_" + id, $(this).val());
});
...
// all other work
});
Note: make sure you don't put some user's personal data in browser's local storage -_-

Edit placeholder html after entering username

To save space (and keep things more compact) I added a input box with a placeholder stating
<input id="username-search" placeholder="view another users work">
after adding the username, I'd like to change the text of the placeholder to something like
<input id="username-search" placeholder="viewing -theuser-'s work">
as well as remove the text added to the input box by the user, as when text is entered, the placeholder disappears.
Any ideas?
You can change the placeholder attribute dinamically as you need in an onchange event handler for the <input type="text"> :
<input id="username-search" placeholder="view another users work"
onchange="changePlaceholder(this)">
<script>
function changePlaceholder(input){
if (input.value == '') {
input.placeholder = "view another users work";
}
else {
input.placeholder="viewing " + input.value + "'s work";
input.value="";
}
}
</script>
JSFiddle.
Take into account that the <input>'s value will be cleared after onchange(), so you might want to keep an <input type='hidden'> with the last inputted value if there's something you wish to do with it outside onchange.
Pretty simple really. Try this:
var input = document.getElementById('username-search');
input.onclick = function() {
input.setAttribute('placeholder', "viewing " + input.value + "'s work");
input.value = '';
}
Type something in the box, and then click on the box. The value will be removed, but the placeholder will update with "viewing Adam's work".

Cursor appear on search box click

Just want some direction really.
Want my search box to have text inside, but when it is clicked, it clears it and allows the user to start typing.
How is this achieved?
jQuery?
Anyone got any useful links or tips to do this?
Thanks :)
Update for 'jQuery'
<form action="process.php" method="POST">
<input type="text" name="keyword" value="Keyword or code" id="textBox"/>
<?php echo $form->error("keyword"); ?>
<input type="submit" value="Search" name="search" />
</form>
<script type="text/javascript">
$('#textBox').focus(function() {
if ($(this).val()==='Keyword or code') {
$(this).val('');
}
});
$('#textBox').blur(function() {
if($(this).val()==='') {
$(this).val('Keyword or code');
}
});
</script>
A more generic approach (we do not need to have the watermark text in the JS):
Given the HTML element <input class="watermark" type="text" value="Text Here" />
And the following Javascript:
<script type="text/javascript">
$(document).ready( function () {
$('input.watermark').focus( function () {
var $this = $(this);
if( !$this.data('watermark_value') || $this.data('watermark_value') === $this.val() ) {
$this.data( 'watermark_value', $this.val() ).val( '' );
}
});
$('input.watermark').blur( function () {
var $this = $(this);
if( $this.val() === '' ) {
$this.val( $this.data('watermark_value') );
}
});
});
</script>
Then you can give any input the class watermark to get the effect.
This will store the original value of the input and make the input blank when first entered, if the field is left blank when focus is removed it'll put the original value back, if the user enters a value into the input then nothing will happen when they leave. If they later revisit the input and make it blank, then again the original value will be inserted.
jQuery isn't necessary - here's a simple plain Javascript solution.
You need to bind to the inputs onfocus event and restore your default with the onblur if it was left empty:
function initSearchBox() {
var theInput = document.getElementById('idOfYourInputElement');
// Clear out the input if it holds your default text
if (theInput.value = "Your default text") {
theInput.value = "";
}
}
function blurSearchBox() {
var theInput = document.getElementById('idOfYourInputElement');
// Restore default text if it's empty
if (theInput.value == "") {
theInput.value = "Your default text";
}
}
<input type='text' value="Your default text" onfocus="initSearchBox();" onblur="blurSearchBox();" />
Actually by this method, it's not really even necessary to getElementById(). You can probably just use this.
try this:
HTML:
<input id="searchBox" value=""/>
JQUERY:
var pre = $('#searchBox').val();
$('#searchBox').focus(function() {
if($(this).val() != pre)
$(this).val($(this).val());
else
$(this).val('');
}).blur(function() {
if ($(this).val() != null && $(this).val() != '')
$(this).val($(this).val());
else
$(this).val(pre);
}).keyup(function() {
if ($(this).val() == null || $(this).val() == '' || $(this).val() == undefined)
$(this).val(pre).blur(); // here the input box will lost cursor blink until you click again due to `blur()` function
});
This can be done with jQuery using the following method;
HTML;
<input id="textBox" name="" type="text" value="text here" />
The jQuery;
$('#textBox').focus(function() {
if ($(this).val()==='text here') {
$(this).val('');
}
});
$('#textBox').blur(function() {
if($(this).val()==='') {
$(this).val('text here');
}
});
This will remove the value of the text box if it is current "text here", then if the user clicks off the box and leaves it empty, it'll add the placeholder text back in.
You could change the .focus to simply be a click function to remove any content, regardless of what's in there.
$('#textBox').click(function() {
$(this).val('');
});
Or you can just use some Javascript in the Input field in HTML like so;
<input type="text" value="Text here" onfocus="if(this.value=='Text here')this.value='';" onblur="if(this.value=='')this.value='Text here';" />
Again, this will only remove text on click if the value is "text here" and it'll add "Text here" back in if the user leaves the box empty.
But you could adjust the onfocus to remove any content with;
<input type="text" value="Text here" onfocus="this.value='';" onblur="if(this.value=='')this.value='Text here';" />
Ensure you've got jQuery included, add this in the ....
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
You can do this in html5 like this:
<imput type="search" value="" placeholder="search here">
But support in IE is limited.
Or, you can do it with jquery very easily:
$(function() {
$("#search").click(function() {
$(this).val("");
});
});
You can just add placeholder="" into your input tag
<input type="text" placeholder="Keyword or code">
This will generate a watermark which goes away when you focus on it

Categories