Creating multiple elements (input) on button press, within a loop - javascript

My goal with this is to have forms that contain a beginning input, and if the '+' button next to it is pressed, it will create another input below it. All of these inputs will eventually be inserted in AJAX.
Right now my form is inside a PHP foreach loop, so I have multiple forms, each with their own set of inputs and buttons.
If I click the '+' button in each form, it will create a new input below, but the way I'm trying to limit each form to 10 inputs, it's going across all forms like this:
So in that image, I clicked the '+' button of the first form 3 times (up to item 4) and then I pressed it in the next form which gave Item 5.
The functionality is basically working here, but I need each form to have it's own inputs, limited to 10. This way if they save items on any form, I can pass only those inputs to AJAX.
<form id="Items" method="post">
<label id="ItemLabel">Item 1:</label>
<input type="text" name="Items[]"><br/>
<button type="button" class="moreItems_add" onclick="moreItems(this);">+</button>
<input type="hidden" name="tickerID" id="tickerID" value="xyz">
<input type="submit" name="saveTickerItems" value="Save Ticker Items">
</form>
<!-- ticker modal JS -->
<script type="text/javascript">
var maxItems = 1;
function moreItems(button) {
if (maxItems < 10) {
var label = document.createElement("label");
label.id="ItemLabel"+maxItems;
label.innerHTML = "Item "+(maxItems+1)+": ";
var input = document.createElement("input");
input.type='text';
input.name = 'item'+maxItems;
$($(label)).insertBefore($(button));
$($(input)).insertBefore($(button));
//Insert a line break so that the next label and input are on new line
$('<br/>').insertBefore($(button));
maxItems++;
}
}
</script>

You're using a global variable as your counter so it will increment with every use for every form. Why not have the button check what's in the form and do the counting itself? And while you're at it, may as well go full jQuery.
$("button.moreItems_add").on("click", function(e) {
var numItems = $("input[type='text']", $(this).closest("form")).length;
if (numItems < 10) {
var html = '<label class="ItemLabel">Item ' + (numItems + 1) + ': </label>';
html += '<input type="text" name="Items[]"/><br/>';
$(this).before(html);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="Items" method="post">
<label class="ItemLabel">Item 1:</label>
<input type="text" name="Items[]"><br/>
<button type="button" class="moreItems_add">+</button>
<input type="hidden" name="tickerID" id="tickerID" value="xyz">
<input type="submit" name="saveTickerItems" value="Save Ticker Items">
</form>
Also you were naming your text inputs sequentially, which I assume was a mistake?

Here's a solution after a couple modifications to your code.
function moreItems(button) {
var maxItems = Number(button.attributes.cnt.value);
maxItems += 1;
button.setAttribute("cnt", maxItems);
if (maxItems < 10) {
var label = document.createElement("label");
label.id = "ItemLabel" + maxItems;
label.innerHTML = "Item " + (maxItems + 1) + ": ";
var input = document.createElement("input");
input.type = 'text';
input.name = 'item' + maxItems;
$($(label)).insertBefore($(button));
$($(input)).insertBefore($(button));
$('<br/>').insertBefore($(button));
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="Items" method="post">
<label id="ItemLabel">Item 1:</label>
<input type="text" name="Items[]"><br/>
<button type="button" cnt="0" class="moreItems_add" onclick="moreItems(this);">+</button>
<input type="hidden" name="tickerID" id="tickerID">
<input type="submit" name="saveTickerItems" value="Save Ticker Items">
</form>
<br><br>
<form id="Items" method="post">
<label id="ItemLabel2">Item 1:</label>
<input type="text" name="Items[]"><br/>
<button type="button" cnt="0" class="moreItems_add" onclick="moreItems(this);">+</button>
<input type="hidden" name="tickerID" id="tickerID2">
<input type="submit" name="saveTickerItems" value="Save Ticker Items">
</form>
Changes made:
add a custom attribute to each + button, in here cnt="0".
in moreItems() function, increment value of cnt of respective form's + button.

Related

Change HTML Document Title from Form input

I am trying to change a HTML page's title based on form input. This is needed because the page will be printed as a PDF and we want it to be saved as the customer's name + caller.)
I know the following code will change the document's title.
onClick="document.title = "My new title";
But I'm trying to do something like:
onClick="document.title = document.getElementById("customerName").value +" " + "Caller" ;"
Here is an example form:
<form action="">
<label for="customerName">Customer name:</label><br>
<input type="text" id="customerName" name="customerName" ><br>
<input type="submit" value="Submit" onClick="document.title = document.getElementById("customerName").value +" " + "Caller" ;">
</form>
document.title = document.getElementById('customerName').value +' ' + 'Caller' ;
You have quote issues. Also use the submit event instead of click
document.getElementById("form1").addEventListener("submit", function(e) {
e.preventDefault(); // remove if you DO want the form to submit
document.title = document.getElementById("customerName").value + " " + "Caller";
})
<form action="" id="form1">
<label for="customerName">Customer name:</label><br>
<input type="text" id="customerName" name="customerName"><br>
<input type="submit" value="Submit">
</form>
To give you the answer just try this code and see what i did different :)
let handleSubmit = (event) => {
event.preventDefault()
document.title = document.getElementById("customerName").value + " " + "Caller";
}
<form action="#" onsubmit="handleSubmit(event)">
<label for="customerName">Customer name:</label><br>
<input type="text" id="customerName" name="customerName"><br>
<input type="submit" value="Submit">
</form>

How to transfer values from between input

Before anyone marks this as a duplicate, I have looked at many sites and am currently using this one - jQuery - passing value from one input to another for guidance, yet no result... I am trying to pass a value from one input in one form to another input in a 'table'. I have put it in a table because of a very weird reason - it does not display a Sparql value when in a form only displays in a table so the input was placed in a table. My code is below:
Form
<form onclick="txtFullName.value = txtFirstName.value +'_'+ txtLastName.value">
First name : <input type="text" name="txtFirstName" value="#ViewBag.FirstName"/> <br><br>
Last name : <input type="text" name="txtLastName" value="#ViewBag.LastName" /> <br><br>
Full name : <input type="text" id="txtFullName" name="txtFullName"> <br><br />
<input id="submit12" type="button" value="Submit">
</form>
Table
<table id="results">
<Full name:
<br>
<input id="userInput" type="text" name="fullname" ${userJson.userId == ''?'': 'disabled'} value="#ViewBag.DisplayName">
<br>
<input id="submit" type="submit" value="Submit">
</table>
JQUERY
$('#submit12').on('click', function (e) { //Form submit
$('#userInput').change(function () {
$('txtFullName').val($(this).val());
});
});
I am trying to display the txtFullName into userInput input when pressing submit but right now only the `txtFullName' is displayed when pressing submit. Also the submit is the submit button in the FORM.
Anymore info needed let me know:)
You need to change the onclick to action on the form if you are trying to use submit button. The other way is to use input type button instead of submit:
So:
$(document).ready(function() {
$('#submit12').on('click', function (e) {
console.log('test');
$("#txtFullName").val($("#txtFirstName").val() + '_' + $("#txtLastName").val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
First name : <input type="text" id="txtFirstName" value="First"/> <br><br>
Last name : <input type="text" id="txtLastName" value="Last" /> <br><br>
Full name : <input type="text" id="txtFullName" name="txtFullName"> <br><br />
<input id="submit12" type="button" value="Submit">
</form>
If you want to display txtFullName into userInput, simply do something like this:
$('#submit12').on('click', function (e) { //Form submit
$('#userInput').val($('#txtFullName').val());
});
And why do you need change function there , if yo need changes when click submit.
Edit your JQuery like this:
$('#submit12').on('click', function (e) { //Form submit
$('#userInput').change(function () {
$('#txtFullName').val($(this).val());
});
});
$('#submit').on('click', function () { //Form submit
$('#userInput').val($('#txtFullName').val());
});
I don't clearly understand why you do it but It can fix your code.
It is not entirely clear what the two buttons do, but the operation itself is really very simple. See comments inline for explanations:
// Wait until the DOM is loaded and all elements are avaialble
window.addEventListener("DOMContentLoaded", function(){
// Get references to the DOM elements you'll need
var theForm = document.getElementById("frmTest");
var txtFirstName = document.getElementById("txtFirstName");
var txtLasttName = document.getElementById("txtLastName");
var txtFulltName = document.getElementById("txtFullName");
var txtUserInput = document.getElementById("txtUserInput");
var btn1 = document.getElementById("btnSubmit1");
var btn2 = document.getElementById("btnSubmit2");
// Function to join names together
function combine(){
txtFullName.value = txtFirstName.value + '_' + txtLastName.value;
}
// Set event handlers
frmTest.addEventListener("click", combine);
btn1.addEventListener("click", combine);
});
<!-- Keep you JavaScript out of your HTML -->
<form id="frmTest">
First name : <input type="text" id="txtFirstName" name="txtFirstName" value="#ViewBag.FirstName">
<br><br>
Last name : <input type="text" id="txtLastName" name="txtLastName" value="#ViewBag.LastName" >
<br><br>
Full name : <input type="text" id="txtFullName" name="txtFullName"> <br><br />
<input id="btnSubmit1" type="button" value="Combine Names">
<table id="results">
<Full name:
<br>
<input id="txtUserInput" type="text" name="fullname" ${userJson.userId == ''?'': 'disabled'} value="#ViewBag.DisplayName">
<br>
<input id="btnSubmit2" type="submit" value="Submit">
</table>
</form>

Dynamically add html depending on dynamically generated html with jQuery

I'm currently working on a project for which I have to develop a WordPress plugin allowing to manipulate tables in databases. My work is based on this plugin, which I'm improving and editing to match the requirements of my company : https://wordpress.org/plugins/create-db-tables/
My problem however doesn't concern MySQL, but html, Php and jQuery (especially jQuery, which I'm not familiar with, at all). It's about dynamically generating a form, itself depending on a dynamically generated form (yeah...).
With the following code, the plugin user is able to dynamically add rows to the table he's creating. I would like him to be able to add "sub-rows" (I know how to handle it server-side, my problem here is only the interface), like that :
http://i.imgur.com/XHwI54W.png
When the user clicks "Add subrows", a zone appears where he can fill out a form, etc. It works perfectly (at least the interface) for the first row, but after that, whenever I click another "Add subrows" button, nothing happens.
I'd appreciate very much if someone could take time to tell me where I'm doing something wrong. Thank you so much ! :)
Here is my code :
(the first jQuery script seemingly works, I'm not the one who developed it. I duplicated it and tried to adapt the second one to my "sub-row" requirement)
<form id="create-table" method="post" action="<?php echo admin_url('admin-post.php'); ?>">
<input type="hidden" name="action" value="add_table">
<fieldset class="table-fieldset">
<label id="table-name">Table Name:</label> <br />
<span style="position: relative; top: 2px;"><?php echo "Choose prefix (by default wp_ ) : " ?></span><input type="text" class="prefix-name" name="prefix_name" size="4" id="prefix-name"><br />
<span style="position: relative; top: 2px;"><?php echo "Choose table name :" ?></span><input type="text" class="table-name" name="table_name" size="30" id="table-name">
<span>(Alphanumeric only, no special characters.)</span> <br/> <br/>
<span><font color="blue"><strong>Will this table be used for user authentication ? </strong></font></span><input type="checkbox" class="is-user-auth" name="is_user_auth" id="is-user-auth"><br/>
<span><strong>/!\ Only one table at a time can be used for user authentication : if a current table is used for this purpose, it won't be anymore.</strong></span><br/><br/>
</fieldset>
<div id="rows">
<fieldset class="row-fieldset" id="row-fieldset" value="1"><label id="row-label">Row:</label><input type="text" class="name-input" name="name[]" placeholder="Name" size="20"><input type="text" class="type-input" name="type[]" placeholder="Type [Ex: bigint(20)]" size="20"><span id="null-label">Null</span><input type="checkbox" class="null-input" name="null[]"><input type="text" class="default-input" name="default[]" placeholder="Default Value" size="20"><span id="unique-label">Unique</span><input type="checkbox" class="unique-input" name="unique[]"><button type="button" class="row-dynamic" style="background-color: #E3F6CE">Add subrows</button><div id="subrows1" value="1"></div></fieldset>
</div>
<div id="add-row">
<button type="button" class="add-row button-secondary">Add Row</button>
</div>
<fieldset>
<input type="hidden" id="items" name="items" value="1" />
</fieldset>
<fieldset>
<input type="hidden" id="subrowitems" name="subrowitems" value="101" />
</fieldset>
<fieldset>
<button type="submit" class="button button-primary button-large">Create Table</button>
</fieldset>
</form>
<!-- Script to add rows -->
<script>
jQuery(function($) {
$('.add-row').click(function () {
$('#items').val(function(i, val) { return +val+1 });
var val_2=$('#items').attr('value');
var subrow_name = 'subrows'+val_2;
var rowHTML = '<fieldset class="row-fieldset" id="row-fieldset" value=\"'+val_2+'\"><label id="row-label">Row:</label><input type="text" class="name-input" name="name[]" placeholder="Name" size="20"><input type="text" class="type-input" name="type[]" placeholder="Type [Ex: bigint(20)]" size="20"><span id="null-label">Null</span><input type="checkbox" class="null-input" name="null[]"><input type="text" class="default-input" name="default[]" placeholder="Default Value" size="20"><span id="unique-label">Unique</span><input type="checkbox" class="unique-input" name="unique[]"><button type="button" class="row-dynamic" style="background-color: #E3F6CE">Add subrows</button><div id=\"'+subrow_name+'\" value=' + val_2 + '></div></fieldset>';
$('#rows').append(rowHTML);
});
$("input.name-input").on({
keydown: function(e) {
if (e.which === 32)
return false;
},
change: function() {
this.value = this.value.replace(/\s/g, "");
}
});
$("input.table-name").on({
keydown: function(e) {
if (e.which === 32)
return false;
},
change: function() {
this.value = this.value.replace(/\s/g, "");
}
});
});
</script>
<!-- Script to add subrows -->
<script>
jQuery(function($) {
$('.row-dynamic').click(function () {
$('#subrowitems').val(function(i, val) { return +val+1 });
var val_3=$('#subrowitems').attr('value');
var subrowHTML = '<fieldset class="subrow-fieldset" value=\"' +val_3+ '\"><label id="subrow-label">Subrow:</label><input type="text" class="subrow-name-input" name="name[]" placeholder="Name" size="20" style="background-color: #E3F6CE"><input type="text" class="subrow-type-input" name="type[]" placeholder="Type [Ex: bigint(20)]" size="20" style="background-color: #E3F6CE"><span id="subrow-null-label">Null</span><input type="checkbox" class="subrow-null-input" name="null[]" style="background-color: #E3F6CE"><input type="text" class="subrow-default-input" name="default[]" placeholder="Default Value" size="20" style="background-color: #E3F6CE"><span id="subrow-unique-label">Unique</span><input type="checkbox" class="subrow-unique-input" name="unique[]" style="background-color: #E3F6CE"></fieldset>';
var subrow_val = '#subrows'+$('#row-fieldset').attr('value');
$(subrow_val).append(subrowHTML);
});
$("input.subrow-name-input").on({
keydown: function(e) {
if (e.which === 32)
return false;
},
change: function() {
this.value = this.value.replace(/\s/g, "");
}
});
$("input.table-name").on({
keydown: function(e) {
if (e.which === 32)
return false;
},
change: function() {
this.value = this.value.replace(/\s/g, "");
}
});
});
</script>
You had some duplicated id's on your HTML sintax (e.g. #row-fieldset)
If you check your HTML code you initializes a fieldset tag with the row-fieldset id
<fieldset class="row-fieldset" id="row-fieldset" value="1">
and later you create a new one with the same id
var rowHTML = '<fieldset class="row-fieldset" id="row-fieldset" value=\"'+val_2+'\
So when JQuery tries to find the proper id, only find the first one.
I added to the Add subrows button a value for locate the correct row
Also you did not provide any jQuery version so I used 2.2.0
Check this fiddle to see it running
Hope it helps

Change radio button value to the value of text input

I have this code which has a radio button. I want to get the value of the text box and set it as the value of the selected radio button.
HTML
<form action="add.php" id="registration" method="post" name='registration'
onsubmit="return formValidation();">
Monthly amount of<br>
<input id="300" name="amounts" type="radio" value="300"><label for="300">P
300.00</label><br>
<input id="amntother" name="amounts" type="radio" value="">P
<input disabled="disabled" id="otherAmount" name="amntotherSpecify" type=
"text" value=""><label for="amntother">(please specify)</label><br>
<button name="submit" style="width:305px" type="submit" value=
"Submit">ADD</button>
</form>
Javascript
window.onload = function() {
var promised = document.getElementsByName("amounts");
for (var i = 0; i < promised.length; i++) {
promised[i].onclick = function() {
var rads = this.form[this.name];
for (var i = 0; i < rads.length; i++) {
var textField = this.form[rads[i].value.toLowerCase() + "Amount"];
if (textField) textField.disabled = !rads[i].checked;
}
}
}
}
<form form="view" name='registration' method="POST" action="add.php" onSubmit="return formValidation();">
Monthly amount of</br>
<input type="radio" name="amounts" id="300" value="300" ><label for="300">P 300.00</label><br/>
<input type="radio" name="amounts" id="amntother" value="" >P<br/>
<input type="text" name="amntotherSpecify" id="otherAmount" value="" onchange="addValueToRadioBtn();"/><label for="amntother">(please specify)</label><br/>
<button type="submit" name="submit" value="Submit" style="width:305px">ADD</button>
<script>
function addValueToRadioBtn() {
if (document.getElementById("amntother").checked == true){
document.getElementById("amntother").value = document.getElementById("otherAmount").value;
}
//added an alert box just to test that the value has been updated
alert(document.getElementById("amntother").value);
}
</script>
I have removed the disabled value so that a value can be entered, on change of this value and if the radio button (otheramount) is selected then other amount value will reflect the value that was entered in the textbox.
Just to note that if you disable the text then no user will be able to add a value. If this isn't what you are looking for could you explain in more detail as to how the textbox will be populated and more in what you are trying to achieve.
Anyway hope this script helps
You don't specify formValidation or add.php. If all you want to do is add the specified value as an option, you don't need to call back to the server to do that. Just update the form with the new option:
html
<form form="view" name='registration' method="post" action="add.php" onsubmit="return formValidation();">
<div id="amountOptions">
Monthly amount of</br>
<input type="radio" name="amounts" id="opt300" value="300" ><label for="opt300">P 300.00</label><br/>
</div>
<input type="text" name="amntotherSpecify" id="newvalue" value=""/>
<input type="button" id="btnNewValue" value="Specify your own amount"/>
</form>
javascript
var btnNewValue = document.getElementById('btnNewValue');
btnNewValue.addEventListener('click', function()
{
var div = document.getElementById('amountOptions');
var newAmount = document.forms[0].amntotherSpecify.value;
var optCheck = document.getElementById('opt'+newAmount);
if(optCheck !== null)
return;
var newopt = document.createElement('input');
newopt.type = 'radio';
newopt.id = 'opt'+newAmount;
newopt.name = 'amounts';
newopt.value = newAmount;
var newoptLabel = document.createElement('label');
newoptLabel.for = newopt.id;
newoptLabel.innerHTML = 'P ' + newAmount;
var br = document.createElement('br');
div.appendChild(newopt);
div.appendChild(newoptLabel);
div.appendChild(br);
var newAmount = document.forms[0].amntotherSpecify.value = '';
});
Here's a fiddle to demonstrate it in action. You'll want to add in validation that the new option's value is a number and fits whatever constraints you have.
It's important that you note that according to the html spec, ids cannot start with a number, in fact they must start with a character in the range a-zA-Z.
how about this option...
Slight modification to HTML - extra button, extra label tag
HTML
<form form="view" name='registration' method="POST" action="add.php" onSubmit="return formValidation();">
Monthly amount of</br>
<input type="radio" name="amounts" id="300" value="300" ><label for="300">P 300.00</label><br/>
<input type="radio" name="amounts" id="amntother" value="" ><label id="labelamntother" for="amntother">P</label>
<input type="text" name="amntotherSpecify" id="otherAmount" value="" /><label for="amntother">(please specify)</label><br/>
<button type="button" name="reset" value="Reset Value" style="width:305px" onclick="location.reload(true)">Reset Radio Button Value</button>
<button type="submit" name="submit" value="Submit" style="width:305px">ADD</button>
</form>
Javascript
<script>
document.getElementById("otherAmount").onkeyup = function() {
document.getElementById("labelamntother").innerHTML ="P " + this.value;
}
</script>

How to have multiple radio buttons with different functionality?

I am working on a project in which I need to make an HTML page with couple of radio buttons.
First radio button is, INSERT. As soon as I click INSERT radio button, I would like to show three text box just below the INSERT radio button. First textbox is datacenter, second textbox is node and third textbox is data.
Second radio button is, UPDATE. As soon as I click UPDATE radio button, I would like to show same above three text box just below the UPDATE radio button.
Third radio button is, DELETE. As soon as I click DELETE radio button, I would like to show only one text box just below the DELETE radio button. In this one text box will be node.
Fourth radio button is, PROCESS. As soon as I click PROCESS radio button, I would like to show four text box just below the PROCESS radio button. In this first textbox will be datacenter, second textbox will be node, third textbox will be conf and fourth textbox will be data.
I am able to make first two radio button work (insert and update) but somehow I am not able to understand how do I make last two radio button work.
Below is my HTML
<form method="post" action="testOperation">
<input type="hidden" name="name" id="dynamicName">
<input class="changeAction" type="radio" name="tt" value="Insert" div-id="insert"/> Insert
<div id="insert" class="changeable"></div>
<br/> <input class="changeAction" type="radio" name="tt" value="Update" div-id="update"/> Update
<div id="update" class="changeable"></div>
<br/>
<input type="submit">
</form>
Below is my jquery -
$(document).ready(function(){
$(".changeAction").on("click", function(){
$('.changeable').html('')
var divId = $(this).attr("div-id");
$("#dynamicName").val(divId);
divId = "#"+divId;
var myInput = '<label for="Datacenter"> Datacenter </label> <input type="text" name="datacenter" size="20" /> <label for="Node"> Node </label> <input type="text" name="node" size="20" /> <label for="Data"> Data </label> <input type="text" name="data" size="100"/>'
$(divId).html(myInput);
})
})
And here is my jsfiddle. It will be of great help if anyone can provide any jsfiddle example?
try this code in javascript part,
var datacenter = '<label for="Datacenter"> Datacenter </label> <input type="text" name="datacenter" size="20" />';
var node = '<label for="Node"> Node </label> <input type="text" name="node" size="20" />';
var data = '<label for="Data"> Data </label> <input type="text" name="data" size="100"/>';
var config = '<label for="Config"> Config </label> <input type="text" name="config" size="100"/>';
$(".changeAction").on("click", function () {
var divId = $(this).attr("div-id");
$('.changeable').html('');
$("#dynamicName").val(divId);
switch (divId) {
case 'insert':
//insert stuff goes here!!
divId = "#" + divId;
var myInput = datacenter + node + data;
$(divId).html(myInput);
break;
case 'update':
//update stuff goes here!!
divId = "#" + divId;
var myInput = datacenter + node + data;
$(divId).html(myInput);
break;
case 'Delete':
//Delete stuff goes here!!
divId = "#" + divId;
var myInput = node;
$(divId).html(myInput);
break;
case 'process':
//process stuff goes here!!
divId = "#" + divId;
var myInput = datacenter + node + config + data;
$(divId).html(myInput);
break;
}
});
SEE FIDDLE DEMO
Change your html code to this
<input class="changeAction" type="radio" name="tt" value="Insert" div-id="insert"/> Insert
<div id="insert" class="changeable"></div>
<br/> <input class="changeAction" type="radio" name="tt" value="Update" div-id="update"/> Update
<div id="update" class="changeable"></div><br/>
<input class="changeAction" type="radio" name="tt" value="Delete" div-id="delete"/> Delete
<div id="delete" class="changeable"></div>
<br/> <input class="changeAction" type="radio" name="tt" value="Process" div-id="process"/> Process
<div id="process" class="changeable"></div>
<br/>
<input type="submit">
</form>

Categories

Resources