I have 1000 text boxes. I'm trying to put name for all the 1000 text boxes programmatically in 5 minutes using string replace function or any method.
<html>
<form id="exp">
<input type="text" value="A1">
<input type="text" value="A2">
<input type="text" value="A3">
.
.
.
<input type="text" value="A1000">
</form>
</html>
var element = document.getElementById("exp");
var html = element.outerHTML;
html = html.replace("input type="text"","input type="text" name="name"");
I would like to show my expected result as 'var html' as follows
<html>
<form id="exp">
<input type="text" name="textbox1" value="A1">
<input type="text" name="textbox2" value="A2">
<input type="text" name="textbox3" value="A3">
.
.
.
<input type="text" name="textbox1000" value="A1000">
</form>
</html>
Matching html with a regular expression is a bad idea. Not sure why you would be doing it with a regular expression. Select the elements and set it in a loop.
document.querySelectorAll("#exp input").forEach(function (inp, index) {
inp.name = 'textbox' + (index + 1);
// inp.name = `textbox${index + 1}`;
})
<form id="exp">
<input type="text" value="A1">
<input type="text" value="A2">
<input type="text" value="A3">
</form>
Use document.getElementsByTagName
var inputs = document.getElementsByTagName("input");
for(i=0; i<inputs.length; i++)
inputs[i].name = "text" + (i + 1);
Related
I'm in the process of trying to create a simple input form web page using both HTML and JavaScript but I am stuck. What I am trying to do is to ask for the following and display them in the textarea:
-First Name
-Last Name
-CRN
-Professor Name
So far I am only able to get the First Name to show on the Results box but no luck with the other. Could use some help, thanks in advance.
My CODE looks like this:
// initialize the counter and the array
var numbernames=0;
var names = new Array();
function SortNames() {
// Get the name from the text field
thename=document.theform["firstn"].value
// Add the name to the array
names[numbernames]=thename;
// Increment the counter
numbernames++;
document.theform.sorted.value=names.join("\n");
}
<form name="theform">
First Name:
<input type="text" name="firstn" size="10" /><p>
Last Name:
<input type="text" name="lastn" size="10" /><p>
CRN:
<input type="text" name="crn" size="10" /><p>
Professor:
<input type="text" name="prof" size="10" />
<input type="button" name="addname" value="Submit"
onclick="SortNames();">
<h2>Results:</h2>
<textarea cols="50" rows="10" name="sorted">
</textarea>
</form>
Here's a complete different, but more readable approach.
I get all inputs of type text.
I get the textarea that is the target.
loop throug all inputs getting it's value.
inside loop, after getting the value, set it to the textarea
Take a look running the snippet below
// initialize the counter and the array
function SortNames() {
var inputs = document.querySelectorAll('input[type="text"]');
var txtArea = document.querySelector('[name="sorted"]');
//loop the text inputs
inputs.forEach(function(elem){
var valueOf = elem.value;
txtArea.value += valueOf + '\n'; //concat the value
});
}
<form name="theform">
First Name:
<input type="text" name="firstn" size="10" /><p>
Last Name:
<input type="text" name="lastn" size="10" /><p>
CRN:
<input type="text" name="crn" size="10" /><p>
Professor:
<input type="text" name="prof" size="10" />
<input type="button" name="addname" value="Submit" onclick="SortNames();">
<h2>Results:</h2>
<textarea cols="50" rows="10" name="sorted"></textarea>
</form>
EDIT
If you REALLY want to keep the way you were doing, here's a solution:
1. Push the values from the inputs directly to the array, then set the value inside the textarea.
// initialize the counter and the array
var names = new Array();
function SortNames() {
names.push(document.theform["firstn"].value);
names.push(thename=document.theform["lastn"].value);
names.push(thename=document.theform["crn"].value);
names.push(thename=document.theform["prof"].value);
document.theform.sorted.value=names.join("\n");
}
<form name="theform">
First Name:
<input type="text" name="firstn" size="10" /><p>
Last Name:
<input type="text" name="lastn" size="10" /><p>
CRN:
<input type="text" name="crn" size="10" /><p>
Professor:
<input type="text" name="prof" size="10" />
<input type="button" name="addname" value="Submit"
onclick="SortNames();">
<h2>Results:</h2>
<textarea cols="50" rows="10" name="sorted">
</textarea>
</form>
Changed the tags to more semantic and functional tags. Used the HTMLFormControlsCollection API to set/get form controls. The output is a Template Literal.
Details Commented in Demo
Demo
// Reference the top form
const reg = document.forms.registration;
// Reference the bottom form
const dis = document.forms.display;
// Collect all inputs from top form
const f = reg.elements;
// When top form is clicked...
reg.onclick = function(event) {
// Collect the data from each input and store it in an Object
const student = {
First: f.first.value,
Last: f.last.value,
CRN: f.crn.value,
Prof: f.prof.value
};
// Call function
displayData(event, student);
}
function displayData(event, student) {
// Reference the textarea
const view = dis.elements.sorted;
// if the element that was clicked had [name=add]...
if (event.target.name === 'add') {
/* Set the textarea's value to a Template Literal with
|| interpolated values from the student Object.
*/
view.value += `
First: ${student.First}
Last.: ${student.Last}
CRN..: ${student.CRN}
Prof.: ${student.Prof}
~~~~~~~~~~~~~~~~~~~`;
// Otherwise quit
} else {
return false;
}
}
input,
label {
font: inherit;
display: inline-block;
}
label {
width: 20%
}
[type=text] {
width: 75%;
}
[type=reset] {
margin: 5px 0 0 85%;
}
<!DOCTYPE html>
<html lang=”en”>
<head>
<title></title>
</head>
<body>
<form id="registration">
<fieldset id='set0'>
<legend>Registration</legend>
<label>First Name: </label>
<input type="text" name="first" size="10" /><br>
<label>Last Name: </label>
<input type="text" name="last" size="10" /><br>
<label>CRN: </label>
<input type="text" name="crn" size="10" /><br>
<label>Professor: </label>
<input type="text" name="prof" size="10" /><br>
<input type="reset" name="add" value="Submit">
</fieldset>
</form>
<form id='display'>
<fieldset id='set1'>
<legend>View Data</legend>
<textarea cols="50" rows="10" name="sorted">
</textarea>
</fieldset>
</form>
</body>
</html>
What im trying to do is create a webform that will take the information put into the fields to add to a predefined text. the code I have so far is as follows:
<form action="" method="post">
<input type="reset" value="Clear">
<p>
<input type="text" name="casenumber" value="Case Number" onclick="this.select()" size="25"/>
</p>
<p>
<input type="text" name="name" value="Name" onclick="this.select()" size="25" />
</p>
<p>
<input type="text" name="dealer code" value="Dealer Code" onclick="this.select()" size="25" />
</p>
<p>
<input type="text" name="cid" value="CID" onclick="this.select()" size="25" />
</p>
<p>
<input type="text" name="callback" value="Callback#" onclick="this.select()" size="25" />
</p>
<p>
<input type="text" name="authentication" value="Dealer Authentication" onclick="this.select()" size="25" />
</p>
<p>
<input type="text" name="email" value="Email" onclick="this.select()" size="25" />
</p>
<p>
<input type="text" name="ptn" value="PTN" onclick="this.select()" size="25" />
</p>
<p>
<input type="text" name="ban" value="BAN" onclick="this.select()" size="25" />
</p>
<p>
<input type="text" name="banauth" value="Ban Authentication" onclick="this.select()" size="25" />
</p>
<p>
<input type="text" name="type" value="Type of Request" onclick="this.select()" size="25" />
</p>
<p>
Actions Taken:<br/>
<textarea name="actions" rows="5" cols="50"></textarea>
</p>
<p>
<input type="submit" value="Submit" />
</p>
Now I want all of the information entered into these fields to be added to this
SFDC - TSO Case number: input inserted here
Dealer Name: input inserted here
Dealer code: input inserted here
CID: input inserted here
Callback#: input inserted here
Dealer Authentication: input inserted here
Email: input inserted here
PTN#: input inserted here
BAN: input inserted here
BAN Authentication: input inserted here
Type of Request: input inserted here
Actions Taken: input inserted here
Have not been able to find how to do this so any help is appreciated.
Try the following javascript function which is using the placeholder attribute to generate the titles of values for the text generated:
/**
* fId: the form id
* dId: the div id which want to add the text to it
**/
function printToDiv(fId, dId){
f = document.getElementById(fId);
i = f.getElementsByTagName('input');
iTxt = Array();
k = 0;
out = '';
for (j = 0; j < i.length; j++){
if (i[j].type == 'text'){
iTxt[k] = i[j];
k++;
}
}
for (n =0; n < iTxt.length; n++){
out += "<b>"+iTxt[n].placeholder+":</b> "+iTxt[n].value+"<br />\n";
}
div = document.getElementById(dId);
div.innerHTML = out;
}
A generalized DEMO could be found here or here. Ofcourse you can apply any validation for the data by calling any other function inside the regarded function and you can call it by any way you want, for example, from onsubmit event.
I think that you have to use a placeholder.
Look:
http://www.w3schools.com/tags/att_input_placeholder.asp
Exercise:
<form action="" method="POST">
<input type="text" name="X" placeholder="Some text..." />
</form>
If you don't care about language this could be easily done with JavaScript. Just add the class to all your inputs and add a span next to your defined text
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<input id='txtCaseNumber' class="copyValue" placeholder="case number"/>
<input id='txtDealer' class="copyValue" placeholder="Dealer Name"/>
Case Number: <span data-inputId="txtCaseNumber"></span>
Dealer Name: <span data-inputId="txtDealer"></span>
<script>
$(document).ready(function(){
$(".copyValue").blur(function(){
var inputId = $(this).attr('id');
var ident = "span[data-inputId='" + inputId + "']";
$(ident).html($(this).val());
});
});
</script>
</body>
</html>
If I am understanding your question correctly. You could do something like this. But this is not the only way, it is just a way.
Sample HTML:
<div class="container">
<input type="text" value="something"/>
<input type="text" value="something"/>
<input type="submit" value="submit" id="submit"/>
</div>
<div id="output"></div>
JS:
var a = [
"SFDC - TSO Case number:",
"Dealer Name:",
"Dealer code:",
"CID:",
"Callback#:",
"Dealer Authentication:",
"Email:",
"PTN#:",
"BAN:",
"BAN Authentication:",
"Type of Request:",
"Actions Taken:"
];
var values = [];
$("#submit").on('click', function()
{
var form = $('.container');
var inputs = form.find('input').not('.exclude'); // add this class to the inputs you don't want to collect the values of, IE clear and submit
var l = inputs.length;
var html = '';
for(var i = 0; i < l; i++)
{
var value = inputs.eq(i).val();
values.push(value);
}
for(var i = 0, ln = a.length; i < ln; i++)
{
html += '<p>' + a[i] + ' ' + values[i] + '</p>';
}
$('#output').append(html);
});
Note: I used jQuery for this example and cleaned up / changed the HTML a bit.
Demo:
http://jsfiddle.net/prb75qvt/4/
If I understand you correctly, you want to take an text fron an input box and paste it somewhere else. Use this code template :
HTML CODE
(The onchange is optional, I just like to use it because it activates a function when the text changes)
<input id="newText" type="text" onchange="myFunction()">
<p>Your text</p><p id="oldText"></p>
JS CODE
("oldText" is used as a placeholder)
function myFunction() {
var inputText = document.getElementById("newText").value;
document.getElementById("oldText").innerHTML = inputText
}
I have a variable "count" in javascript and a radio button that I want to depend on that variable. There is a button to generate more radio buttons, which is why I need their name attributes to differ.
My code:
var count = 1;
function newForm(){
...<input name=count type="radio" value="Website" />...
}
But it's just setting the name of each additional radio button to "count" rather than the number "count" represents.
Here's the whole code:
var count = 1;
function newForm(){
var newdiv = document.createElement('div');
newdiv.innerHTML = '<div class="line"></div><br><input type="text" name="Name"
class="field" placeholder="Full Event Name" /><br><input type="text" name="Location"
placeholder="Event Location" class="field" /><br> <input type="text" name="Date"
placeholder="Event Date" class="field" /> <br> <input type="text" name="End"
placeholder="Event End Date (If Applicable)" class="field" /> <br> <input type="text"
name="Time" placeholder="Event Time" class="field" /> <br> <input type="text"
name="Tags"
placeholder="Relevant Tags" class="field" /> <br> The info is from: <input name=count
type="radio" value="Tweet" checked="" />Tweet <input name=count type="radio"
value="Website"
/>Website <input name=count type="radio" value="Tweet and Website" /> Tweet and
Website';
if(count < 10) {
document.getElementById('formSpace').appendChild(newdiv);
count++;
}
}
That newdiv.innerHTML string above is all on one line in the code, by the way.
If you're trying to create an element, use createElement() :
var count = 1;
function newForm(){
var input = document.createElement('input');
input.name = count;
input.type = 'radio';
input.value = 'Website';
}
in your long string of innerHTML you need to escape your "count" variable... otherwise it's just a string... i.e.
'<input name='+count+' type="radio" value="Tweet and Website" />';
That will make it work but as everyone else is mentioning - you really shouldn't embed long html strings like this.
I have two javascript text boxes.
<input type="text" name="test" value="300" />
<input type="text" name="test" value="500" />
How can I use javascript to alert the total price of the items in the text box?
Would something like this work?
var price = document.getElementById("test");
alert(price)
This will take all input elements into account (useful if you have many). Filter them by type and get their values in loop:
var inputs = document.getElementsByTagName("input");
var total = 0;
for (var i = 0; i < inputs.length; i++){
if (inputs[i].type = "text"){
total += parseInt(inputs[i].value, 10);
}
}
alert(total);
<input id="test1" type="text" name="test" value="300" />
<input id="test2" type="text" name="test" value="500" />
JS:
var price = parseInt(document.getElementById("test1").value, 10) + parseInt(document.getElementById("test2").value, 10);
<input id="price1" type="text" name="test" value="300" />
<input id="price2" type="text" name="test" value="500" />
This will work:
var price = document.getElementById("price1").value+document.getElementById("price2").value;
alert(price)
Note Do not have other tags with id="price1" or id="price2"
What you have written will not work, for several reasons. Firstly, as the name suggests, getElementById gets an element based on the value of the id attribute. You haven't given your input elements an id attribute, so that's not going to work.
Secondly, document.getElementById('someId') returns an element, but you want the value. You can use the value property to get it:
var price1 = parseInt(document.getElementById("test1").value, 10);
var price2 = parseInt(document.getElementById("test2").value, 10);
alert(price1 + price2);
This will work with the following HTML:
<input type="text" name="test" id="test1" value="300" />
<input type="text" name="test" id="test2" value="500" />
Note the use of parseInt. The value property returns a String, so we use parseInt to attempt to parse that into a Number. If you don't use it, price1 + price2 will simply concatenate the strings.
I'm trying to set the value of three different input text fields with an onclick function.
I have an image that has this code...
<img src="images/delete_row.png" width="25" onClick="clearRow(0);" />
And I have three input text fields that all have the id of "0".
When I click my image I want to set the value of all three fields to empty.
Can someone please help me write a function that can do this?
Thanks!
First, you need your id values to be different. You should never have the same ID twice on the same page. So lets use this as the example HTML:
<input type="text" id="name_0" name="name" />
<input type="text" id="phone_0" name="phone" />
<input type="text" id="email_0" name="email" />
You could use this JavaScript function:
<script type='text/javascript'>
function clearRow(id){
var name = document.getElementById('name_' + id),
phone = document.getElementById('phone_' + id),
email = document.getElementById('email_' + id);
// Clear values
name.value = phone.value = email.value = "";
}
</script>
And your img tag would remain unchanged:
<img src="images/delete_row.png" width="25" onClick="clearRow(0);" />
I have three input text fields that
all have the id of "0".
This is entirely wrong. In a document you can't have element with the same id. Either use a name or a classname for these textfields and make their ids different.
<script type="text/javascript">
function Change()
{
var elems = document.getElementsByName ( "myfields");
for ( var i = 0;i < elems.length; i++)
{
elems[i].value = "";
}
}
</script>
<input name="myfields" type="text" id="txt1" />
<input name="myfields" type="text" id="txt2" />
<input name="myfields" type="text" id="txt3" />
<img onclick="Change();" alt="test" src="yourimagpath" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#pic').click(function() {
alert('Clicked on pic - resetting fields')
$('.field').val('')
})
}
</script>
<img id="pic" src="image.png">
<input class="field" value="1">
<input class="field" value="2">
<input class="field" value="4">
<input class="field" value="5">
<input class="field" value="6">
<input class="field" value="7">
<input class="field" value="8">
<input class="field" value="9">
<input class="field" value="10">