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.
Related
Requirements:
A new text box should appear with a delete button at closing after clicking '+Add Stop'.
If a delete(x) button is clicked, the respective text box should be removed and Stop #(sequence numbering) should be changed as well.
Need help on:
I have tried to achieve the both above requirements. I get results for #1. But for #2, After adding more items, the delete button works/removes only the last added item only but it should work the same for all items.
Stop # sequence number should be maintained after the removal of an item(s). I need help with this logic also.
HTML:
<form action="https://www.example.com" method="POST">
<label for="stype">Service Type:</label>
<select id="stype" name="service-type">
<option disabled="disabled" selected="selected">Choose Service</option>
<option value="From Airport">From Airport</option>
<option value="To Airport">To Airport</option>
</select><br/><br/>
<label for="fullname">Name: </label><input id="fullname" name="name" size="20" type="text" maxlength="20" placeholder="John Doe" required /><br/><br/>
<label for="phone">Phone: </label><input id="phone" name="phone" maxlength="12" type="tel" placeholder="012-345-6789" required /><br/><br/>
<label for="email">Email: </label><input id="email" name="email" size="30" type="email" maxlength="30" placeholder="contact#example.com" required /><br/><br/>
<label for="ptime">Pickup time </label><input id="ptime" name="pickup-time" type="time" required /><br/><br/>
<label for="pdate">Pickup Date </label><input id="pdate" name="pickup-date" type="date" required /><br/><br/>
<div id="add_stop_here">
</div>
<input type="button" id="add" value="+Add Stop" onclick="test();" />
</form>
JavaScript:
var counter = 0;
function test () {
counter += 1;
var addHtml = '\
<div class="input-box">\
<label for="stop'+counter+'">Stop '+counter+':</label>\
<input type="text" id="stop'+counter+'" name="stop"/ > <a id="rmv'+counter+'" class="remove_stop" href="#">x</a>\
</div>';
var add_hre = document.getElementById("add_stop_here");
add_hre.innerHTML += addHtml;
document.querySelector("#rmv"+counter)
.addEventListener('click', function(){
var removeEl = this.parentNode;
add_hre.removeChild(removeEl);
});
}
Some issues to take care of:
To make this work, I would refrain from using id attributes that have a sequential number. It is not best practice.
Instead, in order to link a label element with its input element, make the input element a child of the corresponding label element. Now the id and for attributes are no longer needed.
Don't use innerHTML += as that will reset the values of the inputs that are already in the document, and will remove the event listeners. Instead use insertAdjacentHTML.
To keep the numbering in pace, use a span element that only has that number, and renumber all those span elements after every change. You can also use it after an insert, just to keep the code clean, and avoid that you need to maintain a counter.
To avoid that you need to attach a new event handler for every new element, listen to click events on the container element, and then check in that single handler which element was clicked. This is called event delegation.
Don't name your function test. Give it a useful name, like insertBusStop.
Instead of binding that handler via HTML attribute, bind it via code.
For multi-line strings you can use back tick delimiters (template literals)
I'd suggest that after clicking the Add button, the focus is put on the newly created input element. This facilitates the input procedure for the user.
Here is how that would work:
var add_hre = document.getElementById("add_stop_here");
document.getElementById("add").addEventListener("click", addBusStop);
function addBusStop() {
var addHtml = `
<div class="input-box">
<label>
Stop <span class="stop_number"></span>
<input type="text" name="stop"/> <a class="remove_stop" href="#">x</a>
</label>
</div>`;
add_hre.insertAdjacentHTML("beforeend", addHtml);
renumber();
add_hre.querySelector(".input-box:last-child input").focus();
}
function renumber() {
let i = 1;
for (let labelSpan of add_hre.querySelectorAll(".stop_number")) {
labelSpan.textContent = i++;
}
}
// Use event delegation
add_hre.addEventListener('click', function(e) {
if (!e.target.classList.contains("remove_stop")) return;
var removeEl = e.target.parentNode.parentNode; // need one more level now
add_hre.removeChild(removeEl);
renumber();
});
<div id="add_stop_here"></div>
<input type="button" id="add" value="+Add Stop"/>
You can do this with each() and find() function easily.
var counter = 0;
$("#add").click(function () {
counter++;
$("#add_stop_here").append(
'<div class="input-box"><label for="stop' +
counter +
'">Stop' +
counter +
': <input type="text" id="stop' +
counter +
'" name="stop"/ ></label> <a id="rmv' +
counter +
'" class="remove_stop" href="#">X</a></div>'
);
});
$(document).on("click", ".remove_stop", function () {
$(this).closest("div").remove(); //use closest here
$("#add_stop_here .input-box").each(function (index) {
$(this)
.find("label:eq(0)")
.attr("id", "stop" + (index + 1));
$(this)
.find("label:eq(0)")
.html("Stop" + (index + 1) + '<input type="text" name="stop" />');
});
counter--;
});
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<form action="https://www.example.com" method="POST">
<label for="stype">Service Type:</label>
<select id="stype" name="service-type">
<option disabled="disabled" selected="selected">Choose Service</option>
<option value="From Airport">From Airport</option>
<option value="To Airport">To Airport</option></select
><br /><br />
<label for="fullname">Name: </label
><input
id="fullname"
name="name"
size="20"
type="text"
maxlength="20"
placeholder="John Doe"
required
/><br /><br />
<label for="phone">Phone: </label
><input
id="phone"
name="phone"
maxlength="12"
type="tel"
placeholder="012-345-6789"
required
/><br /><br />
<label for="email">Email: </label
><input
id="email"
name="email"
size="30"
type="email"
maxlength="30"
placeholder="contact#example.com"
required
/><br /><br />
<label for="ptime">Pickup time </label
><input id="ptime" name="pickup-time" type="time" required /><br /><br />
<label for="pdate">Pickup Date </label
><input id="pdate" name="pickup-date" type="date" required /><br /><br />
<div id="add_stop_here"></div>
<input type="button" id="add" value="+Add Stop" />
</form>
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);
i have a complex div with input field somewhat like this
<input type="text" name="firstname">
<input type="text" name="lastname">
<input type="text" name="email">
<input type="text" name="address">
<div id="section_toClone">
<input type="text" name="tree[tree1][fruit]">
<input type="text" name="tree[tree1][height]">
<input type="checkbox name tree[tree1][color] value="green">Green </input>
<input type="checkbox name tree[tree1][color] value="yellow">yellow </input>
</div>
<button id="add_more"> Add </button>
now when someone click on add i want something like this to happen
<input type="text" name="tree[tree1][fruit]">
<input type="text" name="tree[tree1][height]">
<input type="checkbox name tree[tree1][color] value="green">Green </input>
<input type="checkbox name tree[tree1][color] value="yellow">yellow </input>
<input type="text" name="tree[tree2][fruit]">
<input type="text" name="tree[tree2][height]">
<input type="checkbox name tree[tree2][color] value="green">Green </input>
<input type="checkbox name tree[tree2][color] value="yellow">yellow </input>
<input type="text" name="tree[tree3][fruit]">
<input type="text" name="tree[tree3][height]">
<input type="checkbox name tree[tree3][color] value="green">Green </input>
<input type="checkbox name tree[tree3][color] value="yellow">yellow </input>
and so on..... but my script only clone doesnt change the value of tree from tree1 to tree2 to tree3 and so on.... here is my jquery script
$('#add_more').click(function(){
$("#section_toClone").clone(true).insertBefore("#add_more").find('input').val("").val('');
});
how do i increment that automatically?? i want to mention one more thing in actual html code. it has more then 3 input and 3 checkbox field
Don't even bother putting the numbers into the array keys. Just let PHP take care of it itself:
<input name="tree[fruit][]" value="foo" />
<input name="tree[fruit][]" value="bar" />
<input name="tree[fruit][]" value="baz" />
Any [] set which DOESN'T have an explicitly specified key will have one generated/assigned by PHP, and you'll end up with
$_POST['tree'] = array(
0 => 'foo',
1 => 'bar',
2 => 'baz'
);
As long as your form is generated consistently, browsers will submit the fields in the same order they appear in the HTML, so something like this will work:
<p>#1</p>
<input name="foo[color][]" value="red"/>
<input name="foo[size][]" value="large" />
<p>#2</p>
<input name="foo[color][]" value="puce" />
<input namke="foo[size][]" value="minuscule" />
and produce:
$_POST['color'] = array('red', 'puce');
| |
$_POST['size'] = array('large', 'minuscule');
But if you start mixing the order of the fields:
<p>#3</p>
<input name="foo[color][]" value="red"/>
<input name="foo[size][] value="large" />
<p>#4</p>
<input namke="foo[size][] value="minuscule" />
<input name="foo[color][] value="puce" />
$_POST['color'] = array('red', 'puce');
/
/
$_POST['size'] = array('minuscule', 'large');
Note how they're reversed.
I wouldn't post this without feeling a bit ashamed of how bad it is written, but the following solution does the trick. Badly.
var treeCount = 1;
$('#add_more').click(function(){
$("#section_toClone")
.clone(true)
.insertBefore("#add_more")
.find('input')
.val('')
.each(function(key,element){
var $element = $(element),
oldName = $element.attr('name'),
newName;
if(oldName){
newName = oldName.replace(/tree[0-9]+/, 'tree'+(treeCount+1));
$element.attr('name', newName);
}
else {
treeCount--;
}
})
.promise().done(function(){
treeCount++;
});
});
(please don't shoot me)
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'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">