Hiding Text inside of an input element - javascript

I have a text input, and I want to hide the text inside, on a given event(I disable the input, when it is not needed). I would like to display the hidden text, when the given event is reversed.
I know I can store the value and retrieve as needed. I'd like to avoid moving data, since this is a purely cosmetic operation.
Can the input text be hidden, or is manipulating the data in the input the only way? I would like the simplest solution.y?
I can use pure JS and jQuery.

I would use "value" attribute of the same input object, since the attribute is the default value. In this case you don't even need any additional variables. The idea of this approach comes from the difference between properties and attributes. It means that if you change value property of the object, the attribute value remains the same as it was before.
var input = document.querySelector('input');
function hide() {
input.value = "";
}
function show() {
input.value = input.getAttribute('value');
}
<input type="text" value="Some text">
<button onclick="hide()">Hide</button>
<button onclick="show()">Show</button>

An example on how to store the value of an input element inside the dataset of the element.
and show/hide it on hover.
var hello = document.getElementById('hello');
hello.dataset.value = hello.value;
hello.value = '';
hello.addEventListener('mouseover', function() {
hello.value = hello.dataset.value;
});
hello.addEventListener('mouseout', function() {
hello.value = '';
});
<input id="hello" value="Hello World" />

Related

How to remove inner HTML content onchange

I created a form where a user selects options from a checkbox list. So when a user selects an option in the checkbox, I use a function to show the value of the input field using onchange within inner HTML. My question is, how do we remove that same inner HTML content if the user un-selects those options? So when the user toggles back and forth, it either appears or when un-selected, the value gets removed. Thanks
function functionOne() {
var x = document.getElementById("wheels").value;
document.getElementById("demo").innerHTML = x;
}
<input type="checkbox" id="wheels" onchange="functionOne()" value="feature 1">
<div id="demo"></div>
Check the state of the checkbox before you read the value.
function functionOne(cb) {
var x = cb.checked ? cb.value : '';
document.getElementById("demo").innerHTML = x;
}
<input type="checkbox" id="wheels" onchange="functionOne(this)" value="feature 1">
<div id="demo"></div>
Inside the change function on deselect do this:
document.getElementById("demo").innerHTML = '';
The element that is changed has a checked property which can be inspected - it will be either true or false. So write an if/else condition to update the content of the demo element depending on its value.
I've adjusted your code slightly to cache the elements outside of the function, and to add an event listener to the checkbox instead of using inline JS which is a bit old-school these days. Also, since the value is just a string textContent is more suitable in this case than innerHTML.
// Cache the elements
const wheels = document.getElementById('wheels');
const demo = document.getElementById('demo');
// Add a listener to the wheels element which calls the
// handler when it changes
wheels.addEventListener('change', handleChange);
// Here `this` refers to the clicked element. If its
// checked property is `true` set the text content of
// `demo` to its value, otherwise use an empty string instead
function handleChange() {
if (this.checked) {
demo.textContent = this.value;
} else {
demo.textContent = '';
}
}
<input type="checkbox" id="wheels" value="feature 1">
<div id="demo"></div>

Can you getContext of text value?

So I have an input form that needs to be not visible for a certain point. So I use CSS and Javascript to hide the input until it should be visible. I come from a python background and what I would like to do is something like:
name = input("")
I tried to do something like that but it just assigns the change in visibility to the variable. I have tried using .value however I just can't it to work properly.
I was wondering if you can get can getContext (or if there is something similar) that allows me to assign what the user. Or I could just simply append it to a variable for it work as it should.
To give additional context I need the form to get the value the user has inputted when they click submit on the canvas
var gameOver = true;
if (gameOver){
document.getElementById('name').style.visibility = 'visible'
console.log(name)
}
<html>
<body>
<input id = "name" type="text" class="name"
style="visibility: hidden;"></input>
</body>
</html>
You can do that by simply declaring a variable, say var nameInput, and then assigning the DOM node to it:
var nameInput = document.getElementById('name');
Note that you should not be using name, because it is an implementation-dependent reserved keyword in JavaScript.
To access its style object, you can simply use nameInput.style..., e.g. nameInput.style.visibility = 'visible' if you want to update the visibility property.
If you want to retrieve it's value, you can do this:
console.log(nameInput.value);
var gameOver = true;
if (gameOver) {
var nameInput = document.getElementById('name');
nameInput.style.visibility = 'visible';
console.log('DOM node: ' + nameInput);
console.log('Value: ' + nameInput.value);
}
<input id="name" type="text" class="name" style="visibility: hidden;" />
If you want to dynamically retrieve its value as the user inputs it, you will need to read up on event binding using .addEventListener(). JS is not reactive in the sense that you dynamically update variables upon user interaction with the page. The regime is this:
User triggers some kind of event. In this case, you want to listen to the onInput, onChange, onBlur... events
In your JS logic, you will have to listen to this event that is emitted by the element. This is done by binding an event listener to your DOM node.
var gameOver = true;
if (gameOver) {
var nameInput = document.getElementById('name');
nameInput.style.visibility = 'visible';
console.log('DOM node: ' + nameInput);
console.log('Value: ' + nameInput.value);
}
nameInput.addEventListener('input', function() {
console.log('Updated value: ' + this.value);
});
<input id="name" type="text" class="name" style="visibility: hidden;" />
If I properly understand your question, your problem right now is to get the input value because you already have the code to make it visible.
So what you need to do is to add a handler to your input to execute a function in the moment you want to retrieve the value the user types-in, for instance on change:
HTML:
<input id = "name" type="text" class="name"
style="visibility: hidden;" onchange="inputChanged();"></input>
Javascript:
function inputChanged() {
console.log(document.getElementById('name').value);
}
Hope this helps !

Get HTML with current input values

I need to get the HTML of the whole page, with the current values of all inputs in their value="...".
I've tried this:
document.getElementById("htmlId").innerHTML;
and this:
$('html').html();
but the both return the HTML page but without the input values.
I know that this looks like this other question, but it is not the same. I really need get the HTML with the value attributes.
An input has a value attribute that determines the initial value of the input. It also has a value property that holds the current value of the input.
It appears that you want to export the HTML markup of the page, where the value attributes of all inputs are set to the value of the value property.
You can do so as follows:
// first, set `value` attribute to value of property for all inputs
$('input').attr('value', function() {
return $(this).val();
});
// export HTML with correct `value` attributes
$('html').html();
And here is a little demo of that in action.
$('#export').on('click', () => {
$('input').attr('value', function() {
return $(this).val();
});
console.log($('html').html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Some paragraph.</p>
<input type="text" value="initial value" />
<h1>Header</h1>
<p>Another paragraph</p>
<button id="export">Export page</button>
for input value inside html use this code may got some help
$("#html input[type=text]").each(function(index,value) {
val = $("#"+value.id).val();
alert(val)
});
Assuming "html" itself is an id of an element, you can try cloneNode.
var clonedElem = document.getElementById("html").cloneNode(true);
This clonedElem is a DOM object which contains both html as well as values ( and all other attributes). You can now use this DOM for all your purposes.
For Eg. If you wish to insert it into another element, you can do like
document.getElementById('newElement').appendChild(clonedElem)
This will put the entire node with its values
As commented before,
.html() or innerHTML will return the markup. value is a property associated with input elements. Yes you have a tag, but eventually you end you initiating this property. So when you change value dynamically, it updates property and not attribute
You will have to loop over all the inputs and set value attribute.
function updateAttribute() {
var parent = document.querySelector(".content");
var inputs = parent.querySelectorAll("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].setAttribute("value", inputs[i].value);
}
}
Working Demo
If you want to get input values I will do with .attr to change dynamically element value !
$("ButtonToCatchInputValue").click(function(){
$("input").each(function(){
$(this).attr("value",this.value);
});
console.log($("html").html());
});
Use document.cloneNode to clone the whole document with retaining the state of the html.
cloneNode has a boolean parameter that denotes the following
true - Clone the node, its attributes, and its descendants
false - Default. Clone only the node and its attributes
For more details check this document
function cloneMe() {
var newelement = document.cloneNode(true);
console.log(newelement.getElementsByTagName("input")[0].value)
}
<input type="text" value="Change My Value" style="width:100%" />
<input type="submit" onclick="cloneMe()" value="Clone Now" />

Unable to get value of input field, even through text() and val() methods

I want to get the value of an input field that a user will type into, then do things with it. I've tried the two ways to get value , text() and val(), on the input fields, but neither work.
Kindly advise on what it could be that I'm missing here.
What happens exactly in the code below is that after hovering a button, the value of an input field would be shown through an alert() function. But the alert is constantly blank.
HTML
<div id="collection_name">
collection name
</div>
<input type="text" id="collection_title" placeholder="Midnight in New York">
<div id="collection_button"></div>
jQuery
var collection_title = $('#collection_title').text();
var collection_button = $('#collection_button');
collection_button.on({
mouseover: function() {
alert(collection_title); // the alert comes out blank
}
});
You need to call the text()/val() methods within the handler itself
var collection_title = $('#collection_title');
var collection_button = $('#collection_button');
collection_button.on({
mouseover: function() {
alert(collection_title.val()); //or .text() depending on the element type
}
});
The reason it was blank before is at the time of initializing
var collection_title = $('#collection_title').text();
it had no text value
Demo Fiddle
var collection_title = $('#collection_name').text();
var collection_button = $('#collection_button');
collection_button.on({
mouseover: function () {
alert(collection_title); // the alert comes out blank
}
});

How to append Span to input field dynamically using native javascript

I have 5 input box in my page. I want to check if any field is blank, i will show the error message using a span tag appending to that input field.
Here is my code:
function validateForm() {
// Declare all the local variable
var inputElements, inputId, inputType, i, inputLength, inputNode;
// Get all the input tags
inputElements = document.getElementsByTagName("input");
for(i = 0, inputLength = inputElements.length; i < inputLength; i++) {
inputId = inputElements[i].id; // Get the input field ID
inputType = inputElements[i].type; // Get the input field type
// We will ONLY look for input[type=text]
if(inputType === "text") {
inputNode = document.getElementById(inputId);
if(inputNode.value === "") {
var spanTag = document.createElement("span");
spanTag.innerHTML = inputFieldBlankErrorMessage;
console.log(inputNode.appendChild(spanTag));
}
}
}
return false; // Do Nothing
}
This is what i am getting
It should append after the input tag. I am getting a weird tag which i don't need. Please help!!!
You can't .appendChild() anything to an input node, since an input can have no descendants.
Instead, you should insert the new node after it, or something similar.
inputNode.parentNode.insertBefore(spanTag, inputNode.nextSibling);
DEMO: http://jsfiddle.net/hMBHT/
Simply put you are not supposed to append any elements to input elements.
What you probably want is something like this:
<div class="field">
<input type="text" name="bla"/>
<span class="error">This field can't be blank!</span>
</div>
So you need to insert the span before or after the input element.
Here is an answer that shows you how.
I believe that your issue is that you are trying to append the span as a child of the input, not a sibling (which, I believe, is what you really want).
I can't to be sure without seeing your actual HTML, because I don't know how your inputs are situated in the DOM, but if they have separate parent elements, then you would replace:
inputNode.appendChild(spanTag);
. . . with
inputNode.parentNode.appendChild(spanTag);
Edit: FYI, the code that squint gave below (inputNode.parentNode.insertBefore(spanTag, inputNode.nextSibling);) would be how you could do it if all of the inputs are under the same parent element. It all depends on how the DOM structure is set up.

Categories