How to remove inner HTML content onchange - javascript

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>

Related

Enter information in input and shows the information on the div's textContent simultaneously

I'm a HTML JS beginner.
Right now I'm doing a Meme generator project and I encounter a problem
this is my HTML code
//this is input tag
<div>
<input type="text" placeholder = 'text' class="mtext">
<input type="text" placeholder = 'text' class="mtext">
</div>
//this is my div block.
<div id = "meme">
<div class="mtext1" style = 'left: 5px; top: 5px; width: 400px; height: 25px'></div>
<div class="mtext1" style = 'left: 5px; top: 5px; width: 400px; height: 25px'></div>
</div>
and my thought is wanting to use "addEventListener" to solve this problem.
const inputText = document.querySelectorAll('.mtext')
const showTextBox = document.querySelectorAll('.mtext1')
inputText.addEventListener('????' , function(){
showtextbox.textContent +=
})
the first problem is what addEventListener parameter is proper to meet my expectation? That I can type into the text box and shows the result on div box at the same time.
the second problem is my inputText and showTextBox are array-like value, how can I extract the value for each of inputText and represent to the right showTextBox?
Thank you
First of all, you are looking for the change event. Check this website
// this code is wrong, read below.
inputText.addEventListener('change' , function(){
// code
});
second, inputText and showTextBox are not what you think they are.
document.querySelectorAll gives you a NodeList which is just a list of html elements (for example - [elem1, elem2...] ). See this website. So inputText and showTextBox are lists.
You need to put an eventListener to every one of those elements in the list:
inputText.forEach(element => {
// add eventListener to every element in the list:
element.addEventListener('change', function () {
// element.value gives the value inside your input elements.
// your code
})
});
The code above puts change eventListener to every mtext class.
Here is how you do it:
const inputText = document.querySelectorAll('.mtext');
const showTextBox = document.querySelectorAll('.mtext1');
//element is current element, index is the current element's index
inputText.forEach((element, index) => {
// add eventListener to every element in the list:
element.addEventListener('change', function (e) {
// element.value gives the value inside your input elements.
showTextBox[index].innerText = element.value
})
});
Here is the demo
you can also use keyup, but as this post discusses:
The reason you should not use keyup() is because if a user inputs a value using autofill, it will not fire the keyup() event. However, autofill does fire the change() event, and your verification script will run, and the input will be verified.

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" />

How to get another html tag value using this property

I have a buttton inside a table.
<input type="button" onclick="I_Have('IS-12-78',this)" class="i_have_it" value="Yes, I have">
When I click the button I need to get the value of select box in the same row.
I haven't maintained separate class or id for this select box.
function I_Have(itm_id,obj)
{
xmlReq=new XMLHttpRequest();
xmlReq.open("POST","./requests/store.jsp",false);
xmlReq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlReq.send("item="+itm_id+"&wt=1");
if(xmlReq.responseText.trim()!="")
{
alert(xmlReq.responseText)
obj.style.display="none"
return false
}
//obj.innerHTML("Used")
obj.setAttribute('onclick','I_Dont_Have("'+itm_id+'",this)')
obj.setAttribute('value','No, I dont have')
obj.setAttribute('class','i_dont_have_it')
}
Using "this"(passed into the function) property can I get the value of select box in javascript.
You can use Dom object's previousElementSibling property:
this.previousElementSibling.value
Have a look on this fiddle.
But this will only work if select is immediate sibling of your button element.
If that's not your case then first get the parent element then reach to your required element:
window.callback = function(obj){
var parent = obj.parentElement;
// Uncomment following to get value from nearest <TD> if your htmls is structured in table
//parent = parent.parentElement;
var select = parent.getElementsByTagName('select')[0];
alert(select.value);
}
Here is updated fiddle.

Hiding Text inside of an input element

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" />

How can I get the value from a series of textbox with same id

I have a series of textboxes with the same name
<%for(i=0;i<=nooftasks;i++){%>
<input type="text" id="duration"
name="duration" class="td4" onkeyup="durationFormat()">
}%>
In Javascript I have to add a colon after two digits
function durationFormat()
{
var duration = document.getElementsByName("duration").value;
if(duration.length==2){
duration=duration+":";
}
}
But I could not get the desired result as I could not get the string from the textbox of that particular text box.
Any ideas?
<input type="text" id="duration" name="duration" class="td4" onkeyup="durationFormat(this)">
<script>
function durationFormat(obj) {
if ((obj.value.length)== 2) {
obj.value+=":";
}
}
</script>
getElementsByName returns a NodeList not an Element. A NodeList is like an Array. You need to loop over it and apply your changes to each value in turn.
Even if you have used getElementById(which returns an Element) and had unique IDs for your inputs (you don't, this is invalid, fix it) then it still wouldn't modify the value. Copying the value property into a variable and then modifying it won't change the value property of the input. You would need to go back and then input.value = duration after you made your modification.
If you want to get the specific input that invoked the function, then:
stop using intrinsic event attributes. They are a pain
use addEventListener instead
use event delegation to simplify the attaching of the handler
examine the target property to determine which input was invoked
such:
<fieldset id="durations">
<legend>Durations</legend>
<%for(i=0;i<=nooftasks;i++){%>
<input type="text" name="duration" class="td4">
}%>
</fieldset>
<script>
function durationFormat(ev) {
var input = ev.target;
if (input.value.length === 2) {
input.value += ":";
}
}
document.getElementById('durations').addEventListener('keyup', durationFormat);
</script>
You have to loop into your elements with name duration.
function durationFormat() {
var duration = document.getElementsByName("duration");
for (var i = 0; i < duration.length; i++) {
if(duration[i].value == 2){
duration[i].value += ":";
}
}
}
The logic for this is:
Firstly, get all elements that have an attribute name with duration value in that property.
Secondly, you have to loop inside the array of elements you got when called .getElementsByName method.
To finish, you have to set the value of each element with a : at the end of the value if his value is 2.
For those that don't understand what duration[i].value += ":"; does, automatically gets the value of the input element at i position of the array and adds the value : at the end. It's exactly the same that if you do duration[i].value = duration[i].value + ":";. I prefer to use +=, because it's sorter. I never tested, but I think that it's also the fastest way for browsers to add some content at the end. It can also be used for string variables.

Categories