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" />
Related
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>
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.
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" />
I don't know how to add name from my input into label attr for and same input as ID. They are in same div. Do you guys know how to do it ? Thank you.
Jquery:
$('input[type="text"]').each(function () {
var name = $("input").attr("name");
})
HTML:
<div data-role="fieldcontain">
<label>Name:</label>
<input type="text" name="fname" value="" />
</div>
Just get the previous element of this input field and change its text with this.name:
$('input[type="text"]').each(function() {
$(this).prop('id', this.name) // set 'id' of input field
.prev('label') // get previous sibling element
.attr('for', this.name); // set 'for' attribute
});
Use $(this)
$('input[type="text"]').each(function () {
var name = $(this).attr('name');
$(this).prev('label').text(name);
})
Use .prop() instead of .attr() Since, attr() gives you
the value of element as it was defines in the html on page load. It is
always recommended to use prop() to get values of elements which is
modified via javascript/jquery , as it gives you the original value of
an element's current state dom element
$('input[type="text"]').each(function () {
var name = $("input").prop("name");
$(this).prev('label').text(name);
});
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.