Easier way to toggle field descriptions using JavaScript - javascript

I've got a simple form that takes user feedback. Basically I just want to toggle the input values - Name, E-mail, Subject, Comments.
<form name="email_rep" id="email_rep" method="POST">
<input type="text" width="100" name="cust" value="Name" maxlength="100" class="fields" onFocus="toggleLabels(1)" onBlur="toggleLabels(5)">
<input type="text" width="100" name="cust_email" maxlength="100" value="E-mail" class="fields" onFocus="toggleLabels(2)" onBlur="toggleLabels(6)"><br />
<input type="text" width="100" name="cust_subject" value="Subject" maxlength="100" class="fields-alt" onFocus="toggleLabels(3)" onBlur="toggleLabels(7)"><br />
<input type="text" width="100" name="cust_comment" maxlength="500" value="Comments" class="fields-alt" onFocus="toggleLabels(4)" onBlur="toggleLabels(8)"><br />
<input type="submit" value="Send" name="submit_email" id="submit" onClick="sendButton()">
</form>
and the corresponding JS:
function toggleLabels(x) {
switch(x) {
case 1: (document.email_rep.cust.value=="Name") ? (document.email_rep.cust.value="") : (false); break;
case 2: (document.email_rep.cust_email.value=="E-mail") ? (document.email_rep.cust_email.value="") : (false); break;
case 3: (document.email_rep.cust_subject.value=="Subject") ? (document.email_rep.cust_subject.value="") : (false); break;
case 4: (document.email_rep.cust_comment.value=="Comments") ? (document.email_rep.cust_comment.value="") : (false); break;
case 5: (document.email_rep.cust.value=="") ? (document.email_rep.cust.value="Name") : (false); break;
case 6: (document.email_rep.cust_email.value=="") ? (document.email_rep.cust_email.value="E-mail") : (false); break;
case 7: (document.email_rep.cust_subject.value=="") ? (document.email_rep.cust_subject.value="Subject") : (false); break;
case 8: (document.email_rep.cust_comment.value=="") ? (document.email_rep.cust_comment.value="Comments") : (false); break;
}
}
I mean it works, but it's not exactly concise and definitely isn't reusable. I was thinking passing another variable - say "y" where y="email_rep", and possibly another - say "z" where z="Name"/"E-mail"/"Subject"/"Comments", but it's not working for me, I don't know if it's like the strings being passed or what the issue is. Any suggestions for making this simpler?

This seems to work. It uses placeholders, but also uses jQuery to simulate placeholder functionality: http://jsfiddle.net/kmkRV/
$(function() {
$("input:text").each(function() {
$(this).val($(this).attr("placeholder"));
}).focus(function() {
if ($(this).val() == $(this).attr("placeholder")) {
$(this).val("");
}
}).blur(function() {
if ($(this).val() == "") {
$(this).val($(this).attr("placeholder"));
}
});
});
That's the jQuery javascript. Here's the HTML:
<form name="email_rep" id="email_rep" method="POST">
<input type="text" width="100" name="cust" placeholder="Name" maxlength="100">
<input type="text" width="100" name="cust_email" maxlength="100" placeholder="E-mail"><br />
<input type="text" width="100" name="cust_subject" placeholder="Subject"><br />
<input type="text" width="100" name="cust_comment" maxlength="500" placeholder="Comments"><br />
<input type="submit" value="Send" name="submit_email" id="submit" onClick="sendButton()"> </form>

I think this is what you're trying to do:
function toggleLabelValue(obj, val) {
if (obj.value == val) {
obj.value = "";
} else {
obj.value = val;
}
}
// examples:
toggleLabelValue(document.email_rep.cust, "Name");
toggleLabelValue(document.email_rep.cust_email, "E-mail");
Or, since all your objects have the same root, you could build that root into the function like this:
function toggleRepLabelValue(field, val) {
if (document.email_rep[field].value == val) {
document.email_rep[field].value = "";
} else {
document.email_rep[field].value = val;
}
}
// examples:
toggleRepLabelValue("cust", "Name");
toggleRepLabelValue("cust_email", "E-mail");

Using jQuery, I've come up with possibly the most re-usable solution. Yes, it uses jQuery, however it's a very powerful, useful tool.
I've done some magic with .data() to store the original value. Take a look at this JSFiddle.
Code:
$(document).ready(function() {
$("input").each(function() {
$(this).data("placeholder", $(this).val());
});
$("input").live("focus", function() {
if($(this).val() == $(this).data("placeholder"))
{
$(this).val('');
}
});
$("input").live("blur", function() {
if(!$(this).val().length)
{
$(this).val($(this).data("placeholder"));
}
});
});
You could probably shrink it by a few lines, but I wanted it to be clear. Also, this will affect any new elements added dynamically to the DOM, due to using .live().
EDIT
To make for cleaner markup, have a look at THIS JSFiddle; it grabs the placeholder attribute and puts it into value as a fallback.
$(document).ready(function() {
$("input").each(function() {
$(this).data("placeholder", $(this).attr("placeholder"));
$(this).val($(this).data("placeholder"));
});
$("input").live("focus", function() {
if($(this).val() == $(this).data("placeholder"))
{
$(this).val('');
}
});
$("input").live("blur", function() {
if(!$(this).val().length)
{
$(this).val($(this).data("placeholder"));
}
});
} );

HTML5 has a lovely new attribute for input fields called placeholder.
Although this isn't supported by some browsers yet, I thought it worth pointing out as an answer for future readers.
You basically use it like:
<input type="text" placeholder="Your name">
http://jsfiddle.net/ZP9z3/
In Firefox, placing focus on the input removed the placeholder text, and on blur, if a new value isn't entered, the placeholder text is restored.
UPDATE
Using jQuery you can also mimick the behaviour of the placeholder with a small bit of code:
$('input:text').focus(function(){
$(this).val('');
}).blur(function(){
if($(this).val() == "")
{
$(this).val($(this).attr('placeholder'))
}
}
);
http://jsfiddle.net/ZP9z3/3/
This basically sets up each input so that it's placeholder text is used if it is empty.

Related

jQuery - How do I use AND with Selector?

My code's function is to alert user if the ptype textfield is empty.
$("input[name*='ptype']").each(function() {
if ($(this).val() == "") {
$(this).css({'background-color' : '#feffe3'});
e.preventDefault();
alert("Enter Value!");
}
});
However, I need to add another criteria where another field amount is not 0. So that the function get triggered when ptype="" && amount!=0. I'm very new in jQuery, and I'm not sure how to use AND operator in here. I've tried to do some based on other questions but it seems not working.
$("input[name*='ptype'][amount!='0']").each(function() {
$("input[name*='ptype'] , [amount!='0']").each(function() {
What am I missing ?
You can do it with && sign. Code depends on where your amount field is located and what it is. If I guess right it should be something like this:
$("input[name*='ptype']").each(function() {
if ($(this).val() == "" && $(this).parent().find(input[name='amount']).val() != 0) {
$(this).css({'background-color' : '#feffe3'});
e.preventDefault();
alert("Enter Value!");
}
});
That code $("input[name*='ptype'][amount!='0']").each(function() { is valid. You have to check the CSS selectors list.
The problem maybe in your *= selection. input[name*="ptype"] means Selects every element whose name attribute value contains the substring "ptype".
$('input[name*="ptype"][amount!="0"]').each(function() {
if ($(this).val() == "") {
$(this).css({'background-color' : '#feffe3'});
e.preventDefault();
alert("Enter Value!");
}
});
Take a look at this test https://jsfiddle.net/xpvt214o/211871/
« where another field» is the key in question.
So you need a selector to check if a selected element is empty and another element is not zero.
Holà!
Logic problem here.
with $(selector) you can look up for some elements.
There is no AND / OR in selectors for many sets of matching element.
A selector is ONE set of matching elements.
No way this selector can check for an attribute value of another set.
So you have to know your markup and navigate a bit... And take care of variable types.
$("input[name*='ptype']").each(function() {
if ( parseInt( $(this).next("input").val() ) != 0) {
$(this).css({"background-color" : "red"});
alert("Enter Value!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
ptype: <input type="text" name="ptype"><br>
amount: <input type="text" name="amount" value="1">
You have to look for another element's value here, from my understanding. So you have to know what is that "other" element and the methods to use may vary a lot depending on your HTML...
You can use this function in your button.
function check(e){
var verror = false;
$("input[name*='ptype']").each(function(index, value) {
var amount = $($("input[name='amount[]']").get(index)).val();
var ptype = $(this).val();
if(ptype.length <= 0 && amount.length > 0 ){
verror = true;
$(this).focus();
return false;
}
});
if(verror){
e.preventDefault();
alert("Enter Value!");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
ptype: <input type="text" name="ptype[]">
amount: <input type="text" name="amount[]" value="1"> <br>
ptype: <input type="text" name="ptype[]">
amount: <input type="text" name="amount[]" value="2"> <br>
<button type="button" onclick="check(event)">Click</button>
</form>

Function with input not working

I have written a function for placeholder functionality of an input field. It works if I write the on/off functions separately, but it's not working when keeping an input variable and if construct. Please help regarding what's wrong in syntax or logic.
function placeholder(x) {
if (x=="1") {
if (document.getElementById("search_field").value=="") {
document.getElementById("placeholder").style.display="inline";
}
}
else {
document.getElementById("placeholder").style.display="none";
document.getElementById("search_field").focus();
}
}
<input id="search_field" type="text" value="" onfocus="placeholder(0);" onblur="placeholder(1);">
<span id="field_def" onclick="placeholder(0);" >
<img src="mag.jpg">
<p id="placeholder">Search</p>
</span>
You can just use the placeholder attribute. It is accepted by all major modern browsers and will save you from adding extra HTML tags and JavaScript code.
<input type="text" name="someName" placeholder="Some Text">
Following is the alternative for old browsers where placeholder is not recognized:
DEMO
HTML:
<input id="search_field" type="text" value="Enter keywords..." onfocus="ph(1);" onblur="ph(0);" onclick="ph(1);">
JavaScript:
function ph(x) {
var txtSearch = document.getElementById("search_field");
if (x == 1) {
if (txtSearch.value == "Enter keywords...") {
txtSearch.value = '';
}
}
else {
if (txtSearch.value == "") {
txtSearch.value = 'Enter keywords...';
}
}
}
Try without the quotes on 1 when evaluating x:
function placeholder(x){
if(x==1){
if(document.getElementById("search_field").value==""){
document.getElementById("placeholder").style.display="inline";
}
}
else{
document.getElementById("placeholder").style.display="none";
document.getElementById("search_field").focus();
}
}
Also, remove the ";" when calling the function:
<span id="field_def" onclick="placeholder(0)">
Check if the function was called or not.
If not then change it:
<input id="search_field" type="text" value="" onfocus="javascript:placeholder(0)" onblur="javascript:placeholder(1)">

How to validate if textbox value is empty in a series of textboxes?

There are a series of textboxes like:
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
User can fill up the textbox values from top to bottom order. Only first textbox is required and all other textboxes are optional.
Allowed order to fill textbox values:
1st
1st & 2nd
1st, 2nd & 3rd
and likewise in sequence order
Dis-allowed order:
2nd
1st & 3rd
1st, 2nd & 4th
This means that user needs to fill up the first textbox only or can fill up the other textboxes in sequential order. User can NOT skip one textbox and then fillup the next one.
How to validate this in javascript/jQuery?
Any help is highly appreciated!
I would personaly use the disabled html attribute.
See this jsFiddle Demo
html
<form>
<input type="text" class="jq-textBox" required="required" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="submit" />
</form>
(Note the required attribute for HTML5)
jquery
$('input.jq-textBox').on('keyup', function(){
var next = $(this).next('input.jq-textBox');
if (next.length) {
if ($.trim($(this).val()) != '') next.removeAttr('disabled');
else {
var nextAll = $(this).nextAll('input.jq-textBox');
nextAll.attr('disabled', 'disbaled');
nextAll.val('');
}
}
})
Also see nextAll() jquery Method
Edit :
If you want to hide the disabled inputs in order to show them only when the previous input is filled, just add this css :
input[disabled] {
display: none;
}
Demo
You can iterate over the list backwards to quickly figure out whether there is a gap.
var last = false,
list = $(".jq-textBox").get().reverse();
$.each(list, function (idx) {
if ($(this).val() !== "") {
last = true;
}
else if (last) {
alert("you skipped one");
}
else if (list.length === idx + 1) {
alert("must enter 1");
}
});
http://jsfiddle.net/rnRPA/1/
Try
var flag = false, valid = true;
$('.jq-textBox').each(function(){
var value = $.trim(this.value);
if(flag && value.length !=0){
valid = false;
return false;
}
if(value.length == 0){
flag = true;
}
});
if(!valid){
console.log('invalid')
}
Demo: Fiddle
You can find all inputs that are invalid (filled in before the previous input) this way:
function invalidFields() {
return $('.jq-textBox')
.filter(function(){ return !$(this).val(); })
.next('.jq-textBox')
.filter(function(){ return $(this).val(); });
}
You can then test for validity:
if (invalidFields().length) {
// invalid
}
You can modify invalid fields:
invalidFields().addClass('invalid');
To make the first field required, just add the HTML attribute required to it.
I think a more elegant solution would be to only display the first textbox, and then reveal the second once there is some input in the first, and then so on (when they type in the second, reveal the third). You could combine this with other solutions for testing the textboxes.
To ensure the data is entered into the input elements in the correct order, you can set up a system which modifies the disabled and readonly states accordingly:
/* Disable all but the first textbox. */
$('input.jq-textBox').not(':first').prop('disabled', true);
/* Detect when the textbox content changes. */
$('body').on('blur', 'input.jq-textBox', function() {
var
$this = $(this)
;
/* If the content of the textbox has been cleared, disable this text
* box and enable the previous one. */
if (this.value === '') {
$this.prop('disabled', true);
$this.prev().prop('readonly', false);
return;
}
/* If this isn't the last text box, set it to readonly. */
if(!$this.is(':last'))
$this.prop('readonly', true);
/* Enable the next text box. */
$this.next().prop('disabled', false);
});
JSFiddle demo.
With this a user is forced to enter more than an empty string into an input field before the next input is essentially "unlocked". They can't then go back and clear the content of a previous input field as this will now be set to readonly, and can only be accessed if all following inputs are also cleared.
JS
var prevEmpty = false;
var validated = true;
$(".jq-textBox").each(function(){
if($(this).val() == ""){
prevEmpty = true;
}else if($(this).val() != "" && !prevEmpty){
console.log("nextOne");
}else{
validated = false;
return false;
}
});
if(validated)
alert("ok");
else
alert("ERROR");
FIDDLE
http://jsfiddle.net/Wdjzb/1/
Perhaps something like this:
var $all = $('.jq-textBox'),
$empty = $all.filter(function() { return 0 === $.trim(this.value).length; }),
valid = $empty.length === 0
|| $empty.length != $all.length
&& $all.index($empty.first()) + $empty.length === $all.length;
// do something depending on whether valid is true or false
Demo: http://jsfiddle.net/3UzHf/ (thanks to Arun P Johny for the starting fiddle).
That is, if the index of the first empty item plus the total number of empties adds up to the total number of items then all the empties must be at the end.
This is what you need :
http://jsfiddle.net/crew1251/jCMhx/
html:
<input type="text" class="jq-textBox" /><br />
<input type="text" class="jq-textBox" disabled/><br />
<input type="text" class="jq-textBox" disabled/><br />
<input type="text" class="jq-textBox" disabled/><br />
<input type="text" class="jq-textBox" disabled/>
js:
$(document).on('keyup', '.jq-textBox:first', function () {
$input = $(this);
if ($input.val()!='')
{
$('input').prop('disabled',false);
}
else {
$('input:not(:first)').prop('disabled',true);
}
});
var checkEmpty = function ()
{
var formInvalid = false;
$('#MyForm').each(function () {
if ($(this).val() === '') {
formInvalid = true;
}
});
if (formInvalid) {
alert('One or more fields are empty. Please fill up all fields');
return false;
}
else
return true;
}

Delete default value of an input text on click

I have an input text:
<input name="Email" type="text" id="Email" value="email#abc.example" />
I want to put a default value like "What's your programming question? be specific." in Stack Overflow, and when the user click on it the default value disapear.
For future reference, I have to include the HTML5 way to do this.
<input name="Email" type="text" id="Email" value="email#abc.example" placeholder="What's your programming question ? be specific." />
If you have a HTML5 doctype and a HTML5-compliant browser, this will work. However, many browsers do not currently support this, so at least Internet Explorer users will not be able to see your placeholder. However, see JQuery HTML5 placeholder fix « Kamikazemusic.com for a solution. Using that, you'll be very modern and standards-compliant, while also providing the functionality to most users.
Also, the provided link is a well-tested and well-developed solution, which should work out of the box.
Although, this solution works, I would recommend you try MvanGeest's solution below which uses the placeholder-attribute and a JavaScript fallback for browsers which don't support it yet.
If you are looking for a Mootools equivalent to the jQuery fallback in MvanGeest's reply, here is one.
--
You should probably use onfocus and onblur events in order to support keyboard users who tab through forms.
Here's an example:
<input type="text" value="email#abc.example" name="Email" id="Email"
onblur="if (this.value == '') {this.value = 'email#abc.example';}"
onfocus="if (this.value == 'email#abc.example') {this.value = '';}" />
This is somewhat cleaner, i think. Note the usage of the "defaultValue" property of the input:
<script>
function onBlur(el) {
if (el.value == '') {
el.value = el.defaultValue;
}
}
function onFocus(el) {
if (el.value == el.defaultValue) {
el.value = '';
}
}
</script>
<form>
<input type="text" value="[some default value]" onblur="onBlur(this)" onfocus="onFocus(this)" />
</form>
Using jQuery, you can do:
$("input:text").each(function ()
{
// store default value
var v = this.value;
$(this).blur(function ()
{
// if input is empty, reset value to default
if (this.value.length == 0) this.value = v;
}).focus(function ()
{
// when input is focused, clear its contents
this.value = "";
});
});
And you could stuff all this into a custom plug-in, like so:
jQuery.fn.hideObtrusiveText = function ()
{
return this.each(function ()
{
var v = this.value;
$(this).blur(function ()
{
if (this.value.length == 0) this.value = v;
}).focus(function ()
{
this.value = "";
});
});
};
Here's how you would use the plug-in:
$("input:text").hideObtrusiveText();
Advantages to using this code is:
Its unobtrusive and doesn't pollute the DOM
Code re-use: it works on multiple fields
It figures out the default value of inputs by itself
Non-jQuery approach:
function hideObtrusiveText(id)
{
var e = document.getElementById(id);
var v = e.value;
e.onfocus = function ()
{
e.value = "";
};
e.onblur = function ()
{
if (e.value.length == 0) e.value = v;
};
}
Enter the following
inside the tag, just add onFocus="value=''" so that your final code looks like this:
<input type="email" id="Email" onFocus="value=''">
This makes use of the javascript onFocus() event holder.
Just use a placeholder tag in your input instead of value
we can do it without using js in the following way using the "placeholder" attribute of HTML5
( the default text disappears when the user starts to type in, but not on just clicking )
<input type="email" id="email" placeholder="xyz#abc.example">
see this: http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_input_placeholder
<input name="Email" type="text" id="Email" placeholder="enter your question" />
The placeholder attribute specifies a short hint that describes the expected value of an input field (e.g. a sample value or a short description of the expected format).
The short hint is displayed in the input field before the user enters a value.
Note: The placeholder attribute works with the following input types: text, search, url, tel, email, and password.
I think this will help.
Why remove value? its useful, but why not try CSS
input[submit] {
font-size: 0 !important;
}
Value is important to check & validate ur PHP
Here is a jQuery solution. I always let the default value reappear when a user clears the input field.
<input name="Email" value="What's your programming question ? be specific." type="text" id="Email" value="email#abc.com" />
<script>
$("#Email").blur(
function (){
if ($(this).val() == "")
$(this).val($(this).prop("defaultValue"));
}
).focus(
function (){
if ($(this).val() == $(this).prop("defaultValue"))
$(this).val("");
}
);
</script>
I didn't see any really simple answers like this one, so maybe it will help someone out.
var inputText = document.getElementById("inputText");
inputText.onfocus = function(){ if (inputText.value != ""){ inputText.value = "";}; }
inputText.onblur = function(){ if (inputText.value != "default value"){ inputText.value = "default value";}; }
Here is an easy way.
#animal represents any buttons from the DOM.
#animal-value is the input id that being targeted.
$("#animal").on('click', function(){
var userVal = $("#animal-value").val(); // storing that value
console.log(userVal); // logging the stored value to the console
$("#animal-value").val('') // reseting it to empty
});
Here is very simple javascript. It works fine for me :
// JavaScript:
function sFocus (field) {
if(field.value == 'Enter your search') {
field.value = '';
}
field.className = "darkinput";
}
function sBlur (field) {
if (field.value == '') {
field.value = 'Enter your search';
field.className = "lightinput";
}
else {
field.className = "darkinput";
}
}
// HTML
<form>
<label class="screen-reader-text" for="s">Search for</label>
<input
type="text"
class="lightinput"
onfocus="sFocus(this)"
onblur="sBlur(this)"
value="Enter your search" name="s" id="s"
/>
</form>

Change text color in text field

I have an input text field, which has a value "something" by default, but when I start to type, I want that the default value changes color, and the text i'll type, another one.
How can i do that?
<input type="text" value="something" onclick="this.value=''" />
To keep it simple like your example:
<input type="text" value="something" onclick="this.value='';this.style.color='red';" />
And that should pretty much do it.
You may want to try the following:
<input type="text" value="something"
onFocus="if (this.value == 'something') this.style.color = '#ccc';"
onKeyDown="if (this.value == 'something') {
this.value = ''; this.style.color = '#000'; }">
Going off #chibu's answer, this is how you would do it using jQuery and unobtrusive Javascript
$(document).ready(
function() {
$("#mytext").bind(
"click",
function() {
$(this).val("");
$(this).css("color", "red");
}
);
}
)
// 'run' is an id for button and 'color' is for input tag
// code starts here
(function () {
const button = document.getElementById("run");
button.addEventListener("click", colorChange);
function colorChange() {
document.body.style.backgroundColor = document.getElementById("color").value;
}
})();
Here we go:
<input type="text" value="something" onclick="this.value='';this.style.color='red';" />
Best of luck!
Keep coding!

Categories