Hide previoussibling in Javascript - javascript

HTML:
<label>First Name</label>
<input type="text" value="" id="FNAME">
JS:
var FNAME = document.getElementById('FNAME');
FNAME.addEventListener('input', function() {
if (FNAME.value !== ''){
alert('Field not empty! Value: '+ FNAME.value);
document.getElementById('FNAME').previousSibling.style.visibility = "hidden";
}
});
... gives an error:
TypeError: undefined is not an object (evaluating 'FNAME.previousSibling.style')
What am I doing wrong?

Append previousSibling to previousSibling again. It should correctly target the label now.
var FNAME = document.getElementById('FNAME');
if (FNAME.value !== ''){
var label = FNAME.previousSibling.previousSibling.style.visibility = "hidden";
}

To answer your question regarding the error you get, previousSibling of your input is a text node (the white space between the label and input). And text nodes do not have a style property.
Now, as far as I understand your question, you want to hide the label under certain conditions.
I would change your html a bit and use some more modern js api to access the elements.
<label for="FNAME">First Name</label>
<input type="text" value="" id="FNAME">
here I added the for property to the label.
var FNAME = document.querySelector("#FNAME");
var label = document.querySelector("label[for='FNAME']")
FNAME.addEventListener('input', function() {
if (FNAME.value !== ''){
alert('Field not empty! Value: '+ FNAME.value);
label.style.visibility = "hidden";
}
});
hope this help.

The previous sibling of your input element is it's text node.
So, you should call FNAME.previousSibling.previousSibling to access the label.
This question would give you more info.

Related

How do I select the inputted text of a text field?

I'm adding interactivity to a form.
Here is a snippet of the HTML:
<label for="name" id="nameLabel">Name:</label>
<input type="text" id="name" name="user_name">
There is a button at the bottom of the form, 'Register'. If the button is pressed and the Name field is empty, I want to add an alert message, reminding the user to enter their name. I want to do this by amending the label.
I am having trouble trying to select the inputted text of the text-field. Seeing as it's not value or innerHTML? How do I select it?
This is the code I have so far:
// Form validation. Display error messages and don't let the user submit the form if any of these validation errors exist:
document.querySelector("button").addEventListener("click", function() {
// Name field can't be empty
var nameInput = document.getElementById("name");
var nameLabel = document.getElementById("nameLabel");
if(nameInput.value === "") {
nameLabel.innerHTML = "Name: (please provide name)";
nameLabel.style.color = "red";
}
});
Use .value to get the value of input field and put css value red in inverted comma as nameLabel.style.color = "red"; Also since you have a
<button type ="submit">submit</button>
you need to stop you page from refreshing. Use e.preventDefault(); for this in your event handler
The flash of error that you get while in console is that red is not defined which it isn't since its a string and you need to give it in "".
document.querySelector("button").addEventListener("click", function() {
// Name field can't be empty
var nameInput = document.getElementById("name");
var nameLabel = document.getElementById("nameLabel");
if(nameInput.value === "") {
nameLabel.innerHTML = "Name: (please provide name)";
nameLabel.style.color = "red";
}
});
<label for="name" id="nameLabel">Name:</label>
<input type="text" id="name" name="user_name">
<button>Submit</button>
document.querySelector("button").addEventListener("click", function() {
// Name field can't be empty
var nameInput = document.getElementById("name");
var nameLabel = document.getElementById("nameLabel");
console.log("\"" + nameInput.value + "\"");
if(nameInput.value.length == 0) {
nameLabel.innerHTML = "Name: (please provide name)";
nameLabel.style.color = "red";
}
});
<label for="name" id="nameLabel">Name:</label>
<input type="text" id="name" name="user_name">
<button>Submit</button>

If text box value matches then make that specific label text to yes else no

Iam trying check if the text of label matches with the text box if matches then make that specific label text to yes else no but in my code am not sure what is wrong but that is not happening for all it is showing "no" it self
Demo
HTML
<input class="master" value="1">
<label class="user_label" >1</label>
<label class="user_label" >0</label>
<label class="user_label" >1</label>
JS:
$(function() {
var master = $('input.master').get(0).value; // get the master value
var fn = function() {
return this.text === master ? "yes" : "noo";//if current text-box matches master,then yes else no
};
$('label.user_label').text(fn); // loop and replace text for each user input
});
this.text will be undefined inside fn, because this is a DOM node, and it doesn't have text property.
You can wrap it as a jQuery object and use the text() method:
var fn = function() {
return $(this).text() === master ? "yes" : "noo";
}
http://jsfiddle.net/L6d39f10/5/
You can simplify your code as follows, second parameter in text() callback function refers the old text value. You can use val() for getting value in jQuery.
var val = $('input.master').val();
$('.user_label').text(function(i, text){
return val === text ? 'yes' : 'no';
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input class="master" value="1">
<label class="user_label">1</label>
<label class="user_label">0</label>
<label class="user_label">1</label>
when fn passed into $('label.user_label').text(fn) the context changed but still this.text is undefined. use this.textContent,this.innerHTML,$(this).text()
use text to compare and then modify it that makes logic odd, should it be like this?
$(function() {
$('input.master').keyup(function() {
var master = $(this).val(); // get the master value
var fn = function() {
return $(this).attr('data-val') === master ? "yes" : "noo"; //if current text-box matches master,then yes else no
};
$('label.user_label').text(fn); // loop and replace text for each user input
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<input class="master" value="">
<label class="user_label" data-val="1"></label>
<label class="user_label" data-val="0"></label>
<label class="user_label" data-val="1"></label>
$(function() {
var master = $('input.master').get(0).value; // get the master value
$('label.user_label').each(function(){
if($(this).text() === master){
$(this).text("yes");
}else{
$(this).text("no");
}
});
});

Cannot set property 'nodeValue' of null

I'm going through a book and it seems to be right, but the following code keeps giving me the error: Cannot set property 'nodeValue' of null. The code makes sense to me, but I don't understand why it can't clear the text value when clicking the clear button.
var clear = function(){
$("miles").firstChild.nodeValue = "";
$("gallons").firstChild.nodeValue = "";
$("mpg").firstChild.nodeValue = "";
}
window.onload = function () {
$("calculate").onclick = calculateMpg;
$("miles").focus();
$("clear").onclick = clear;
}
Html
<section>
<h1>Calculate Miles Per Gallon</h1>
<label for="miles">Miles Driven:</label>
<input type="text" id="miles"><br>
<label for="gallons">Gallons of Gas Used:</label>
<input type="text" id="gallons"><br>
<label for="mpg">Miles Per Gallon</label>
<input type="text" id="mpg" disabled><br>
<label> </label>
<input type="button" id="calculate" value="Calculate MPG"><br>
<input type="button" id="clear" value="clear"><br>
</section>
I think what you want is this where you use the .value property on the input fields directly:
var clear = function() {
$("miles").value = "";
$("gallons").value = "";
$("mpg").value = "";
}
Here's an explanation of what was going on. Now that we can see your full page and see that $ is document.getElementById(), the issue is that you are some of those nodes don't have a firstChild.
For example the object with an id="miles" is an input tag and it has no children so .firstChild is null.
In this line:
$("miles").firstChild.nodeValue = "";
$("miles") gets you the DOM object.
$("miles").firstChild returns null because there are no children of that DOM object.
$("miles").firstChild.nodeValue = ""; is an error because $("miles").firstChild is null and null doesn't have a property .nodeValue.
Input elements do not have child nodes so firstChild gives you null, further more if you're trying to clear the value of the input fields use the value property.
var clear = function(){
$("miles").value = "";
$("gallons").value = "";
$("mpg").value = "";
}
Looking at the code you posted in the comments, the problem is that $("miles") and the other elements don't have any children.
It seems like you're trying to do something like this:
var clear = function() {
$("miles").value = "";
$("gallons").value = "";
$("mpg").value = "";
}

Javascript change input type dynamically doesnt work on IE8

i have a input field for entering password in a webpage:
<input name="txtPassword" type="text" class="input2" id="txtPassword" value="Password" onfocus="txtOnFocus2('txtPassword','Password');" onblur="txtOnBlur2('txtPassword','Password');" />
in the initial state the usershould read "password" as the initial value and when he starts typing a password, the field should change to type password. Also when he sets it back to blank or initial value the field should change type to "text" and show password.
I wrote code an got it working on Firefox, Chrome, and safari and its not changing the type to password on IE 8.
this is the js code i made by editing an existing function code:
function txtOnFocus2(elementId, defaultText)
{
if (document.getElementById(elementId).value == defaultText)
{
document.getElementById(elementId).value = "";
document.getElementById(elementId).type = "password";
}
}
function txtOnBlur2(elementId, defaultText)
{
var textValue = document.getElementById(elementId).value;
if (textValue == defaultText || textValue.length == 0)
{
document.getElementById(elementId).type = "text";
document.getElementById(elementId).value = defaultText;
}
}
This is working fine in Firefox,chrome and safari but doesn't change field type on IE 8.
An alternative solution would be to change your approach altogether. The following technique degrades gracefully, is more accessible, and less JavaScript-dependant:
HTML
<div><label for="email">Email</label> <input type="text" name="email" id="email" /></div>
<div><label for="password">Password</label> <input type="password" name="password" id="password" /></div>
JavaScript
$('input')
.focus(function() {
$(this).css('background-color', 'white');
})
.blur(function() {
if($.trim($(this).val()) == '') {
$(this).css('background-color', 'transparent').val('');
}
});
CSS
input {
background-color: transparent;
padding: 2px;
}
label {
color: gray;
padding: 2px 4px;
position: absolute;
z-index: -1;
}
Live demo: http://jsfiddle.net/rjkf4/
I tried that before. There is no way to do this in IE. This is an security thing. But still you can set the value of a password input in IE. So you can remove the text input and replace it with a password input and then set the value of new input.
function replaceInput(input){
var val = input.value,
passwordInput = document.createElement('input');
passwordInput.setAttribute('type', 'password');
passwordInput.value = val;
input.parentElement.appendChild(passwordInput);
input.parentElement.removeChild(input);
};
JSFIDDLE
Instead of:
foo.type = 'password';
try:
foo.setAttribute('type', 'password');
More info: http://www.javascriptkit.com/dhtmltutors/domattribute.shtml
In IE 6 and 7 (at least) you can't change the type of an input that's already in the document. You must create a new input, set its type, then replace the one that's in the document, e.g.
var el = document.createElement('input');
el.type = 'password'
var oEl = document.getElementById(elementId);
el.id = oEl.id;
// and so on for other properties that should be copied
oEl.parentNode.replaceChild(el, oEl);
Something ugly that however should work (I don't have IE8 handy to test it) would be placing your field in a div and replacing the whole thing with container.innerHTML = "<input ...>" when needed.
try this
http://www.electrictoolbox.com/jquery-toggle-between-password-text-field/
As an option you could just fake having a visible text in the password field by using a background image with that text on it.
$(".password").focus(function(){
$(this).css("background-image", 'url(regular_bg.png)')
})
$(".password").blur(function(){
if ($(this).val() == ""){
$(this).css("background-image", 'url(bg_with_password_label_on_it.png)')
}
})

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>

Categories