I have code which takes a name and a number. I want to have a button that, when you click it, adds another field for another name and number, but it should have a different id because I need to use it for later.
So far, I have the code below but it doesn't work.
function addField() {
var id = 2
var name = 'Name of Owner # ' + id
var phonenum = 'Phone number'
$('.form-group').append('<br><label for="' + id + '">' + name + ':</label><input type="text" class="form-control" name="NewPnOwner" id="NewPnOwner' + id + '" />')
$('.form-group').append('<br><label for="' + id + '">' + phonenum + ':</label><input type="number" class="form-control" name="NewPnNumber" id="NewPnNumber' + id + '"/>')
id++;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group col-sm-4">
<fieldset>
<legend>
<code>New Phone Number</code>
</legend>
<label for="NewPnOwner">Name of Owner #1: </label>
<input type="text" class="form-control" name="NewPnOwner" id="NewPnOwner" />
<br />
<label for="Phonenumber">Phone number: </label>
<input type="number" class="form-control" name="NewPnNumber" id="NewPnNumber" />
<br />
<input type="button" id="button" value="Add New Field" onclick="addField()" />
</fieldset>
</div>
Just define id outside the function like this, otherwise it will initialize with value 2 on every call of addField().
var id = 2
function addField() {
var name = 'Name of Owner # ' + id
var phonenum = 'Phone number'
$('.form-group').append('<br><label for="' + id + '">' + name + ':</label><input type="text" class="form-control" name="NewPnOwner" id="NewPnOwner' + id + '" />')
$('.form-group').append('<br><label for="' + id + '">' + phonenum + ':</label><input type="number" class="form-control" name="NewPnNumber" id="NewPnNumber' + id + '"/>')
id++;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group col-sm-4">
<fieldset>
<legend><code>New Phone Number</code></legend>
<label for="NewPnOwner">Name of Owner #1: </label>
<input type="text" class="form-control" name="NewPnOwner" id="NewPnOwner">
<br>
<label for="Phonenumber">Phone number: </label>
<input type="number" class="form-control" name="NewPnNumber" id="NewPnNumber" />
<br>
<input type="button" id="button" value="Add New Field" onclick="addField()" />
</fieldset>
</div>
But
even though that this is the correct solution to your problem, I would not recommend you to give them ids like that. I can't think of any valid reason to solve any problem like so. There are probably better solutions for your real problem.
Related
firebase.auth().onAuthStateChanged(function(user) {
console.log(user);
if (user) {
var user_id = user.uid;
firebase.database().ref('Clients/'+user_id)
.once('value').then(function(snapshot){
snapshot.forEach(function(childSnapshot) {
var client_name = childSnapshot.child("client_name").val();
var client_phone = childSnapshot.child("client_phone").val();
var client_address = childSnapshot.child("client_address").val();
var total = client_name + "<br>" + client_phone + "<br>" + client_address;
console.log(total);
$('.client_option').append('<option>' + total +'</option');
});
})
}
else{
window.location.href="{% url 'login' %}";
}
});
In this code, I already got individual client information. I have 3 input fields. As these values are displayed as options, I want that, when the user selects a set of options(client_name, phone, address), the individual info passes to specific fields. Here are my input fields.
<input type="text" class="form-control" id="clientName" list="client"
autocomplete="off">
<datalist class="form-control client_option" id="client" hidden>
</datalist>
<input type="tel" pattern="[0-9]{3}-[0-9]{2}-[0-9]{3}" id="phone"
class="form-control" autocomplete="off">
<input type="text" class="form-control" id="address" autocomplete="off">
Thanks in advance.
function disp(){
var client_name = $('#client_name').val();
var client_phone = $('#client_phone').val();
var client_address = $('#client_address').val();
var total = client_name + "-" + client_phone + "-" + client_address;
$('.client_option').append('<option>' + total +'</option');
}
$(document).on("change", ".client_option", function(){
var valArr = $(".client_option option:selected").text().split("-");
$("#clientName").val(valArr[0]);
$("#phone").val(valArr[1]);
$("#address").val(valArr[2]);
$("#client").append("<option>" + $(".client_option option:selected").text() + "</option>");
});
<input id="client_name"> </input>
<input id="client_phone"> </input>
<input id="client_address"> </input>
<button type="submit" onclick="disp()">Submit</button>
<select class="client_option"><option>Please Select</option></select>
<input type="text" class="form-control" id="clientName" list="client"
autocomplete="off">
<datalist class="form-control client_option" id="client" hidden>
</datalist>
<input type="tel" pattern="[0-9]{3}-[0-9]{2}-[0-9]{3}" id="phone"
class="form-control" autocomplete="off">
<input type="text" class="form-control" id="address" autocomplete="off">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Try this out to make this example I have replaced the childSnapshopt.child but it should work as same.
The big point is you can use text() to insert the text into an element.
I also suggest that you use template strings to build your string. Then there is no need of the string concat.
function disp(){
var client_name = $('#client_name').val();
var client_phone = $('#client_phone').val();
var client_address = $('#client_address').val();
var total = `${client_name} \n${client_phone} \n${client_address}`
console.log(total);
$('.client_option').text('<option>' + total +'</option');
}
<input id="client_name"> </input>
<input id="client_phone"> </input>
<input id="client_address"> </input>
<button type="submit" onclick="disp()"></button>
<div class=".client_option"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I am creating a JS form where i need 3 inputs from user and after typing the 3 inputs , on clicking 'Add record' button ,it should display them on the same page one after another (line by line) for every button click. With my code, it is writing every new input entry in the same line and not next line. How do i do it ?
My result:
Andrew Arts 2007 Evelyn Computers 2006
Expected result :
Andrew Arts 2007
Evelyn Computers 2006
function doSubmit() {
document.getElementById('f1').innerHTML += document.myform.name.value + " ";
document.getElementById('f1').innerHTML += document.myform.major.value + " ";
document.getElementById('f1').innerHTML += document.myform.year.value + " ";
return false;
}
<body>
<form name="myform">
<p>
Name: <input name="name" size="30" type="text" /> course: <input name="major" size="30" type="text" /> Year : <input name="year" size="4" type="text" />
</p>
<input type="button" value="Add record" onClick='doSubmit(); return false' />
</form>
<p id='f1'></p>
</body>
You use a <br> tag to break the line inside a <p> tag.
You just have to make a small change in your function :
function doSubmit() {
document.getElementById('f1').innerHTML += document.myform.name.value + " ";
document.getElementById('f1').innerHTML += document.myform.major.value + " ";
document.getElementById('f1').innerHTML += document.myform.year.value + " ";
document.getElementById('f1').innerHTML +='<br />'
return false;
}
If you're looking to style your form values , it would be good to append <p>tag for each form value . It will require a small change like below :
function doSubmit() {
document.getElementById('form-value').innerHTML += '<p>'+ document.myform.name.value + " " + document.myform.major.value + " " + document.myform.year.value + " " + "</p>";
return false;
}
Your HTML :
<body>
<form name="myform">
<p>
Name: <input name="name" size="30" type="text" /> course: <input name="major" size="30"
type="text" /> Year : <input name="year" size="4" type="text" />
</p>
<input type="button" value="Add record" onClick='doSubmit(); return false' />
</form>
<div id="form-value">
</div>
I would suggest creating a new p element for every submitted input. You also don't want to store the user input into the innerHTML, because it can lead to cross-site scripting attacks. To prevent this, you can use innerText instead. Here is an example of how you can achieve all that with your code:
function doSubmit() {
const newInputParagraph = document.createElement("p");
newInputParagraph.innerText += document.myform.name.value + " ";
newInputParagraph.innerText += document.myform.major.value + " ";
newInputParagraph.innerText += document.myform.year.value + " ";
document.getElementById("inputs").appendChild(newInputParagraph);
}
And you need to add container for input results (simple div) to your markup, for example like this:
<form name="myform">
<p>
Name: <input name="name" size="30" type="text" /> course: <input name="major" size="30" type="text" /> Year : <input name="year" size="4" type="text" />
</p>
<input type="button" value="Add record" onClick='doSubmit(); return false' />
</form>
<div id="inputs"></div>
I am adding textboxes through jquery and for one text box it is removing perfeclty but when I add two textboxes then it does now remove both.
this is jquery
<script>
$(document).ready(function($){
$('.product-form .add-product').click(function(){
var n = $('.text-product').length + 1;
var product_html = $('<p class="text-product"><label for="product' + n + '">Name <span class="product-number">' + n + '</span></label> <input required type="text" name="productnames[]" value="" id="product' + n + '" /> <label for="productprice' + n + '">Price <span class="product-number">' + n + '</span></label> <input required type="text" name="productprices[]" value="" id="productprice' + n + '" />Remove</p>');
product_html.hide();
$('.product-form p.text-product:last').after(product_html);
product_html.fadeIn('slow');
return false;
});
$('.product-form').on('click', '.remove-category', function(){
$(this).parent().fadeOut("slow", function() {
$(this).remove();
$('.product-number').each(function(index){
$(this).text( index + 1 );
});
});
return false;
});
});
</script>
and this is my html
<div>
<form>
<div class="product-form">
<p class="text-product">
<label for="product1">Name <span class="product-number">1</span></label>
<input required type="text" name="productnames[]" value="" id="product1" />
<label for="product1">Price <span class="product-number">1</span></label>
<input required type="text" name="productprices[]" value="" id="product1" />
<div>
<a class="add-product" href="#">Add More</a>
</div>
</p>
</div>
<div>
<input type="submit" name="submitDetails" value="Finish"/>
</div>
</form>
</div>
If only one textbox for instance productnames is added then it removal function works but when I add botch productnames and productprices textbox removal function does not remove both
Your code should read $('.product-form').on('click', '.remove-product', function() rather than 'click', '.remove-category'. Also, don't place the Add More div element inside the paragraph element. The numbering also breaks a bit, but you can figure that out.
I have some code that I'm using to allow the user to add products. They can control the number of products added, as well as delete products they've created. My problem is that with the code I'm using, I've only managed to be able to change the id of the second div as well as the name/id of the first input. How can I change the names of all the inputs, not just the first input?
The javascript:
<script type="text/javascript">
$(document).ready(function() {
$('#add').click(function() {
var num = $('.clonedInput').length;
var newNum = new Number(num + 1);
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
$('#input' + num).after(newElem);
$('#remove').attr('disabled','');
});
$('#remove').click(function() {
var num = $('.clonedInput').length;
$('#input' + num).remove();
$('#add').attr('disabled','');
if (num-1 == 1)
$('#remove').attr('disabled','disabled');
});
$('#remove').attr('disabled','disabled');
});
</script>
The form:
<form id="myForm">
<div id="input1" class="clonedInput">
<p>Product Name: <input type="text" name="name1" id="name1" /></p>
<p>Product Description:</p>
<textarea rows="10" cols="50" name="desc1" id="desc1"></textarea>
<p>Brand Name: <input type="text" name="brand1" id="brand1" /></p>
<p>Product Code Number: <input type="text" name="code1" id="code1" /></p>
<p>West Texas Co-op Bid Product Number (if different from the Product Code Number): <input type="text" name="coop1" id="coop1" /></p>
<p>Commodity processing availability:</p>
<p><input type="checkbox" name="yes" id="yes1" value="Yes"> Yes <input type="checkbox" name="no" id="no1" value="No"> No</p>
<p>If yes, what is the commodity processing code number?: <input type="text" name="comm1" id="comm1" /></p>
</div>
<div>
<input type="button" id="add" value="Add Product" />
<input type="button" id="remove" value="Remove Product" />
</div>
</form>
Live example: http://test.joshrodg.com/wp-content/themes/rodgersconsulting/test.php
I figured it out...I was able to tweak what I found here: http://jsfiddle.net/e6cwd/9/
The JQuery:
<script src="http://code.jquery.com/jquery-1.4.2.js" type="text/javascript"></script>
The JavaScript:
<script type="text/javascript">
$(document).ready(function() {
$("#btnAdd").click(function() {
var num = $(".clonedSection").length;
var newNum = new Number(num + 1);
var newSection = $("#clonedSection" + num).clone().attr("id", "clonedSection" + newNum);
newSection.children(":first").children(":first").attr("id", "name" + newNum).attr("name", "name" + newNum);
newSection.children(":nth-child(3)").children(":first").attr("id", "desc" + newNum).attr("name", "desc" + newNum);
newSection.children(":nth-child(4)").children(":first").attr("id", "brand" + newNum).attr("name", "brand" + newNum);
newSection.children(":nth-child(5)").children(":first").attr("id", "code" + newNum).attr("name", "code" + newNum);
newSection.children(":nth-child(6)").children(":first").attr("id", "coop" + newNum).attr("name", "coop" + newNum);
newSection.children(":nth-child(7)").children(":first").attr("id", "yes" + newNum).attr("name", "yes" + newNum);
newSection.children(":nth-child(7)").children(":nth-child(2)").attr("id", "no" + newNum).attr("name", "no" + newNum);
newSection.children(":nth-child(8)").children(":first").attr("id", "comm" + newNum).attr("name", "comm" + newNum);
$(".clonedSection").last().append(newSection)
$("#btnDel").attr("disabled","");
if (newNum == 5)
$("#btnAdd").attr("disabled","disabled");
});
$("#btnDel").click(function() {
var num = $(".clonedSection").length; // how many "duplicatable" input fields we currently have
$("#clonedSection" + num).remove(); // remove the last element
// enable the "add" button
$("#btnAdd").attr("disabled","");
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$("#btnDel").attr("disabled","disabled");
});
$("#btnDel").attr("disabled","disabled");
});
</script>
The HTML:
<form id="myForm">
<div id="clonedSection1" class="clonedSection">
<p>Name: <input type="text" name="name" id="name" /></p>
<p>Product Description:</p>
<p><textarea rows="10" cols="50" name="desc" id="desc"></textarea></p>
<p>Brand Name: <input type="text" name="brand" id="brand" /></p>
<p>Product Code Number: <input type="text" name="code" id="code" /></p>
<p>West Texas Co-op Bid Product Number (if different from the Product Code Number): <input type="text" name="coop" id="coop" /></p>
<p>Commodity processing availability: <input type="checkbox" name="yes" id="yes" value="Yes"> Yes <input type="checkbox" name="no" id="no" value="No"> No</p>
<p>Commodity processing code number (if applicable): <input type="text" name="comm" id="comm" /></p>
</div>
<div>
<input type="button" id="btnAdd" value="add another name" />
<input type="button" id="btnDel" value="remove name" />
</div>
</form>
i have a problem in grouping a dynamically generated radio buttons into a jQuery Mobile control group, i generate the radio buttons and append them into a but they are dispalayed separetly although there warping contains a 'controlgroup' data-role, here's my HTML:
<div data-role="collapsible" data-inset="true">
<h1>AddVote</h1>
<div data-role="fieldcontain" >
<form id="voting" action="get">
<label for="name"> <strong>Question:</strong></label>
<input type="text" name="name" id="name" value="" /><br>
<label for="name"><div id="AddButton" data-role="button" data-inline="true">AddOptions</div></label>
<input type="text" name="option" id="option" value="" /><br>
<div id="RemoveButton" data-role="button" data-inline="true">RemoveOptions</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend> <strong>Choose an Option:</strong></legend><br><br>
<fieldset data-role="controlgroup">
<div id="after" data-role="controlgroup" >
///////////////////////Generated radio buttons goes here//////////////////////
</div>
</fieldset>
</fieldset>
</div>
</div>
<a href="#" data-role="button" data-inline="true" >Publish</a>
</form>
and here's the script code:
function createRadioElement(elem, label, checked) {
var id = 'option1_' + label;
$('#after').append($('<input />', {
'type': 'radio',
'name': 'option1',
'id': id,
'data-role': 'controlgroup',
'data-theme':'e',
'value': '1'
}));
$('#after').append('<label for="' + id + '">'
+ label + '</label><br />').trigger('create');
}
$( '#admin' ).live( 'pageinit',function(event){
$('#AddButton').click(function(){
var x = document.getElementById('option').value;
createRadioElement(this,$('#option').val(),true);
});
Perhaps I don't understand the question correctly but is it the <br /> between the radiobuttons that concerns you? If this is the case then just replace this:
$('#after').append('<label for="' + id + '">'
+ label + '</label><br />').trigger('create');
with this:
$('#after').append('<label for="' + id + '">'
+ label + '</label>').trigger('create');
Also I believe that your <form> and <div> tags are incorrectly nested.