How to get the innerHTML of an input control including the values? - javascript

I have a div, its called tab1. Inside the tab1 div are many inputs (fields and radio buttons). I am getting the innerHTML like this:
document.getElementById("tab1").innerHTML;
Example code:
<div id="tab1">
<input type="text" id="text1" />
</div>
That works, but if I entered any value into a text1 input for example, its not in the innerHTML. How would I get the innerHTML including the entered values? Is that possible at all?
Thanks!

<div id="tab1">
<input type="text" id="text1"
onkeyup="javascript:this.setAttribute("value", this.value);"/>
</div>
This will gives the values with div's innerHTML.
document.getElementById("tab1").innerHTML;
You can change the event accordingly, I set it onKeyUp.

If you want to get the values of inputs/radios, you can do it with jQuery:
var Inputs = $("div#tab1 input, div#tab1 radio");
You now have an array of all input and radios in the variable Inputs. You can then access the values like this: Inputs[0].value
If you want to use plain JavaScript that could look like this:
var Inputs = document.getElementById("tab1").getElementsByTagName('input');
You can now access them like:Inputs[0].valueandRadios[0].value`
#edit
Thanks, I corrected these mistakes.

If you type something in the textbox, what does the innerHTML look like? Does it look like
<input type="text" id="text1" value="your_value" />?
If so, here is a simple function that returns what you want:
function getInnerHtml() {
var div = document.getElementById("tab1");
var childNodes = div.childNodes;
var innerHtml = "";
for (var i = 0; i < childNodes.length; i++) {
var node = childNodes[i];
if (node.nodeType == 1) {
if (node.getAttribute("type") == "text") {
if (node.value != "") {
//! This will change the original outerHTML of the textbox
//If you don't want to change it, you can get outerHTML first, and replace it with "value='your_value'"
node.setAttribute("value", node.value);
}
innerHtml += node.outerHTML;
} else if (node.getAttribute("type") == "radio") {
innerHtml += node.outerHTML;
}
}
}
}
Hope it's helpful.

Related

Iterate DOM property x times with JS

I basically have an input of type number
<input type="number" id="no_pi" name="" onkeyup="des()">
<div id="extract"></div>
and function
function des() {
var ext = document.getElementById('extract');
var va = Number(document.getElementById('no_pi').value);
for (var i = 0; i = va; i++) {
ext.innerHTML = "<input type='number' name='' class='form-control'><div class='input-group-text'>cm</div>";
}
}
I just want to instantly generate x number of inputs in div based on user input.
When the user input any number, the page just crashes down. I think the page is going in infinite loop, but I think it is not the case.
Any idea how to achieve this
There's several errors :
In your loop : i = va (this is why it crashes)
You erase the content of the div ext each time you iterate, instead of adding content
By listening on keyup event, you add some content on each key hit. Finally if the user submit 12, it will generate 1 + 12 elements. You should pass the value using a form (by doing this you can also add easily the value control in the input element).
As perfectly mentionned by #Andy in the comments, innerHTML += is a very bad idea. You should generate your elements using document.createElement or insertAdjacentHTML.
Some advices :
Use an event listener instead of the onkeyup attribute
Avoid this kind of variable names, be more explicit
Use const and let instead of var
Here's a version which fixes all that issues :
document.getElementById('elementsNumberForm').addEventListener('submit', event => {
event.preventDefault();
const targetElement = document.getElementById('extract');
const inputValue = document.getElementById('no_pi').value;
for (let i = 0; i < inputValue; i++) {
targetElement.insertAdjacentHTML('beforeEnd', '<input type="number" name="" class="form-control" /><div class="input-group-text">cm</div>');
}
});
<form id="elementsNumberForm">
<input type="number" id="no_pi" min="1" />
<input type="submit" />
</form>
<div id="extract"></div>
Your key issue is how you're using your loop. i = va isn't going to accomplish what you want. It should be a check that the index in the iteration is less than the number represented by the value in your input. It should be i < va.
The other issue is that you're not adding to the HTML, just ensuring that the HTML is just one input.
I've adjusted the code in your question to remove the inline JS and use addEventListener instead, and also to use an array to store the HTML built from the loop which can then be applied to the extract element.
// Cache the elements outside of the loop
// and attach a change listener to the noPi element
const extract = document.getElementById('extract');
const noPi = document.getElementById('no_pi');
noPi.addEventListener('change', des, false);
function des() {
const limit = noPi.value;
// Check that we haven't gone into
// negative numbers
if (limit >= 0) {
// Create an array
const html = [];
// Loop, pushing HTML into the array, until
// we've reached the limit set by the value in noPi
for (let i = 0; i < limit; i++) {
html.push('<input type="number" class="form-control"><div class="input-group-text">cm</div>');
}
// `join` up the array, and add the HTML
// string to the extract element
extract.innerHTML = html.join('');
}
}
<input type="number" id="no_pi" />
<div id="extract"></div>
Additional information
join
I see that you want to use an input field to insert the number of inputs to create.
I see a better way to start learning insert the number of inputs with a prompt, and then scale the project.
You can start like this: (hope it make sense to you)
<div style="height: 300px; background-color: #ccc;" class="container"></div>
we have this div that is going to be filled with the inputs
Then we have the script:
const container = document.querySelector('.container');
const runTimes = prompt("How many inputs wnat to create?");
for(let i = 0; i < runTimes; i++){
let newInput = document.createElement('input');
newInput.innerHTML = "<input type='number' name='' class='form-control'>";
container.appendChild(newInput);
}
In the for loop, we create the element input, then with the .innerHTML we add the HTML we want. to end the loop, we need to append the created input element to the div we have.
hope it makes sense to you, :)
when you get the idea with the prompt , I´ve done this project more pro jaja.
<div style="height: 300px; background-color: #ccc;" class="container"></div>
<input type="text" class="numberTimes" onkeyup="getValue()">
we add an event listener to the input with the function getValuue, and the script like this:
const container = document.querySelector('.container');
function getValue(){
let runTimes = document.querySelector('.numberTimes').value;
document.querySelector('.numberTimes').value= "";
for(let i = 0; i < runTimes; i++){
let newInput = document.createElement('input');
newInput.innerHTML = "<input type='number' name='' class='form-control'>";
container.appendChild(newInput);
}
}
This line document.querySelector('.numberTimes').value= ""; is to reset the input field.
So whenever insert a value on the input it creates that number of inputs in the container and cleans the input field :)

check if text exists in text box jquery

how to check if the text exists in text box jquery
I need to check if the text exists in the input box,if checking text is not exist thend append new data
I have tried with below code
$(document).ready(function(){
$("#item_inv_desc").change(function(){
var item_inv_desc = $('select[name=item_inv_desc]').val();
if (item_inv_desc == 7)
{
var invoice_number = "123456789";
//I need check if text "CRN" exists in text box
var data=$('#invoice_number:contains("CRN")')
if(data)
{
//if text "CRN" exist no need to append data
}
else
{
//if not exist
$("#invoice_number").val(invoice_number+"CRN");
}
}
});
})
//Html
<input type="text" id="invoice_number" value="">
I am having problem when try to insert append value it adds extra CRN number to invoice number,I need to avoid duplicating,
Try includes() with the val() of the text box:
var data = $('#invoice_number').val().includes("CRN")
or, for older browsers, use indexOf():
var data = $('#invoice_number').val().indexOf("CRN") !== -1
Working Demo:
$(document).ready(function() {
$("#invoice_number").change(function() {
var invoice_number = "123456789";
var data = $('#invoice_number').val().includes("CRN");
if (data) {
} else {
$("#invoice_number").val(invoice_number + "CRN");
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="invoice_number" value="">
You can use regex to remove all the digits and get the text only from the value of the input text. If you want that on button click then add that block of code inside the click function:
var data = $('#invoice_number').val();
var res = data.replace(/[0-9]/g, '');
console.log(res);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="invoice_number" value="123456789CRN">
#Manjunath
var data=$('#invoice_numbe:contains("CRN")')
"r" is missing when you are checking below
var data=$('#invoice_numbe:contains("CRN")')
and use
var data=$('#invoice_number').val().indexOf("CRN");
if(data>-1){
// donot add CRN
}

Adding dom elements relative to input value

I have this function which add elements to the dom according to the value inserted into an input element, and if i insert new value in to the input the previous elements are erased and new elements are inserted.
what i want is to keep the old elements and add new ones to it
html:
<input type="text" placeholder="insert the number of div" class="number">
<button>submit</button>
<br>
<div id="wrapper"></div>
jquery:
$('button').click(function(){
var boxes = '';
var i;
var inputValue = $('.number').val();
for(i=0; i < inputValue; i++){
boxes += "<div class='box'></div>";
}
$('#wrapper').html(boxes);
});
Instead of $.html
$('#wrapper').html(boxes);
Use
$('#wrapper').append(boxes);
You can read more about both methods here:
append
html

How do I use window.find to change css style?

Through a combination of AJAX and PHP, I put some text data in a span at the bottom of the page. Now I want to search this text for a string. My page is full of checkboxes, and their values are the strings I will search for.
Goal: Using a loop, cycle through the values of all checkboxes on the page. Search the page for each checkbox's value (ideally, within the text in the AJAX-informed span). If the checkboxes value is found, change that checkboxes CSS style color.
My code so far: I have a form full of checkboxes all named "comment" each with unique IDs:
<input type="checkbox" name="comment" id="hjl1" value="the comment."
onclick="createOrder()"><label for="hjl1" onclick="createOrder()"
title="comment"> onscreen text for this checkbox </label>
When triggered , using Javascript, I go through every checkbox in that form.
var comment=document.forms[0].comment;
var txt="";
var ii;
for (ii=0;ii<comment.length;ii++)
{str=comment[ii].value;}
Now I want to insert window.find in that loop to check if that value is on my page.
if (window.find) {
var found = window.find (str);
if (!found) {
document.getElementById("?????").style["color"] = "red";
}
}
The idea is that when the checkbox is checked, the javascript would search for the value "the comment." on page. If found, the checkbox label will add the CSS style color red.
Somehow, I want to combine these ideas, but there are so many problems. How do I get the element by ID in this loop? Can window.find search the text created by php in my span?
Would it be better to not use window.find at all?
var source = document.getElementsByTagName('html')[0].innerHTML;
var found = source.search("searchString");
I'm so confused and new. Please be patient. Thank you for reading this far.
I misunderstood at first, and wrote code to highlight text within the page.
Yes, window.find is fine to use for this as you only need to know if the value exists or not. It might behave a bit odd (scroll to bottom) when used in frames though.
Also, I added a function for your onClick, but I'm not sure if this is wanted. It will change color of the label if text if found when clicked (also).
Below is a small example:
function checkThis(ele) {
var str = ele.value;
if (window.find) {
var found = window.find(str);
if (found) {
var id = ele.getAttribute('id');
var lbl = document.querySelectorAll('label[for="' + id + '"]');
if (lbl) lbl[0].style.color = "red";
}
}
}
window.onload = function() {
var comment = document.form1.getElementsByTagName('input');
for (var x = 0; x < comment.length; x++) {
if (comment[x].type == 'checkbox') {
var str = comment[x].value;
if (window.find) {
var found = window.find(str);
if (found) {
var id = comment[x].getAttribute('id');
var lbl = document.querySelectorAll('label[for="' + id + '"]');
if (lbl) lbl[0].style.color = "red";
}
}
}
}
}
<form name="form1">
<input type="checkbox" name="comment" id="hjl1" value="the comment." onclick="checkThis(this);" />
<label for="hjl1" onclick="createOrder()" title="comment">onscreen text for this checkbox</label>
<input type="checkbox" name="comment" id="hjl2" value="the comment2." onclick="checkThis(this);" />
<label for="hjl2" onclick="createOrder()" title="comment">onscreen text for this checkbox</label>
<br/>
<b>first comment.</b><br/>
<b>other comment.</b><br/>
<b>some comment.</b><br/>
<b>the comment.</b><br/>
<b>whatever comment.</b><br/>
<b>not this comment.</b><br/>
</form>
try this as your function code
function loopy() {
var comment=document.forms[0].comment;
var txt="";
var ii;
for (ii=0;ii<comment.length;ii++) {
if (comment[ii].checked) {
str=comment[ii].value;
id = comment[ii].id;
nextLabelId = comment[ii].nextSibling.id;
if (window.find) { // Firefox, Google Chrome, Safari
var found = window.find (str);
if (found == true) {
// found string
//comment[ii].style['outline']='1px solid red';
document.getElementById(nextLabelId).className = 'selected';
}
} else {
// this browser does not support find()
alert('not supported');
}
}
}
}
So, in order to get the checkbox id, you just add id = comment[ii].id in your loop.
To change the color, it's best to use class name and use styling in the css file. so if you want to change the label that is after the checkbox to red you will first find the label's id using nextSiblings and then add the .selected class name. Just remember that you need to remove the coloring if the user un-check the box
Regarding the usage of find(), not supported by all browser so this could be an issue and also not sure it will be able to find on the content you injected to the DOM by AJAX so this needs some testing.
I would suggest moving this code to jQuery as some features seems to be easier using their functionality.

Javascript form validation

I'm trying to figure out what would be the simplest way to validate required fields without having to do an if statement for each element's name. Perhaps just with a loop and verify its class.
What I'm trying to accomplish is to check only the ones that have the class name as "required"
<input name="a1" class="required" type="text" />
<input name="a2" class="" type="text" />
<input name="a3" class="required" type="text" />
Thanks
I'm not at all against the libraries suggested by others, but I thought that you may want some samples of how you could do it on your own, I hope it helps.
This should work:
function validate() {
var inputs = document.getElementsByTagName("input");
for (inputName in inputs) {
if (inputs[inputName].className == 'required' && inputs[inputName].value.length == 0) {
inputs[inputName].focus();
return false;
}
}
return true;
}
Also lets say your inputs are in a form named "theForm":
function validate() {
for (var i = 0; i < theForm.elements.length; i++) {
if (theForm.elements[i].className == "required" && theForm.elements[i].value.length == 0) {
theForm.elements[i].focus();
return false;
}
}
return true;
}
Of course you would trim the value and/or add the appropriate validation logic for the application, but I'm sure you can get the idea from the sample.
You can also store arbitrary data on the input itself and read it using the getAttribute() method on the element. For example you could have this element in your html (regex requires a 3 digit number):
<input name="a1" validate="true" regex="[0-9]{3}" type="text" />
you could use this method to run the regex in the validation routine.
function validate() {
for (var i = 0; i < theForm.elements.length; i++) {
var elem = theForm.elements[i];
if (elem.getAttribute("validate") == "true") {
if (!elem.value.match(elem.getAttribute("regex"))) {
elem.select();
return false;
}
}
}
return true;
}
Hope this helps.
I use the jQuery validation plugin. Works really well and fits your stated desire to only need class attributes.
$(document).ready( function() {
$('form').validate();
});
Is all it takes to set up the validation once you have your required fields marked.
I would recommend you to use this javascript based css selector wich will get all elements of a specific class. Validating the form just like the way you mentioned.
A pattern for this that I have been using for a long time and has served me well is wrapping the control with a DIV, or P and marking that as required.
<div class="form-text required">
<label for="fieldId">Your name</label>
<input type="text" name="fieldName" id="fieldId" value="" />
</div>
This means that I can pick out the required fields to validate easily with a CSS selector.
.required input, .required select
In jQuery, you can test input with something like this:
$('form').submit(function(){
var fields = $(this).find('input, textarea, select'); // get all controls
fields.removeClass('invalid'); // remove
var inv = $(this).find('input[value=""], select[value=""]'); // select controls that have no value
if (inv.length > 0) {
inv.addClass('invalid'); // tag wrapper
return false; // stop form from submitting
}
// else we may submit
});
In plain Javascript it would be more than I care to type out, but along the lines of:
var badfields = [];
var fields = theForm.getElementsByTagName('input');
for (var i=0; i< fields.length; i++ ) {
if ( fields[i] && fields[i].parentNode && fields.value == '' &&
/(^| )required( |$)/.test( fields[i].parentNode.className ) ) {
badfields.push( fields[i] );
}
}
// badfields.length > 0 == form is invalid
The most immediate benefit of wrapping the label and input (and optionally: hint text, error...) as a control "set" in this way is that you can apply CSS styles on the input and label together.
.required input, .required select {
border : 1px solid red;
}
.required label {
color : #800;
}
.invalid input, .invalid select {
background-color : #f88;
}
I recommend using a ready made solution for your form validation as things can quickly add on: How will you validate checkboxes? Can checkboxes be required? (EULA?) What about radio buttons, how will you check those?
Most validation solutions will also provide sugar such as verifying correct data (say, email addresses) rather than just checking if it's there.
I'm a little surprised that no one mentioned YUI.
You can easily use getElementsByClassName method of Dom class in the following manner:
var aElements = YAHOO.util.Dom.getElementsByClassName('required', 'input');
for (var i = 0; i < aElements.length; i++)
{
// Validate
}
More method information is available here and more general info is here

Categories

Resources