How to alter the name value in jQuery "add another field" function - javascript

I'm trying to add another input field as the user clicks on the "add another field" button.
Although it works perfectly, there's this minor issue as the name in the input field supposed to add +1 to the earlier name value in the additional field, which returns as a string instead of int.
Upon clicking on "Add Additional field" a new input appears with name value as name="asin1" and further on goes as name="asin11" & name="asin111". How can I add it up as a count?
And on the other hand, how can I know on the backend page how many fields were actually user added using PHP.
Any help is greatly appreciated.
$('.extra-fields-customer').click(function() {
$('.customer_records').clone().appendTo('.customer_records_dynamic');
$('.customer_records_dynamic .customer_records').addClass('single remove');
$('.single .extra-fields-customer').remove();
$('.single').append('Remove Fields');
$('.customer_records_dynamic > .single').attr("class", "remove");
$('.customer_records_dynamic input').each(function() {
var count = 1;
var fieldname = $(this).attr("name");
$(this).attr('name', fieldname + count);
count++;
});
});
$(document).on('click', '.remove-field', function(e) {
$(this).parent('.remove').remove();
e.preventDefault();
});
<script src='https://code.jquery.com/jquery-2.2.4.min.js'></script>
<div class="customer_records">
<input type="text" class="input" id="fname" name="asin" required placeholder="ASIN/FSIN or Wesite Link of the product">
<a class="extra-fields-customer button" href="#">Add Another Field</a>
</div>
<br>
<div class="customer_records_dynamic"></div>

First solution:
defined count & fieldname out of function .each
$('.extra-fields-customer').click(function() {
$('.customer_records').clone().appendTo('.customer_records_dynamic');
$('.customer_records_dynamic .customer_records').addClass('single remove');
$('.single .extra-fields-customer').remove();
$('.single').append('Remove Fields');
$('.customer_records_dynamic > .single').attr("class", "remove");
var count = 1;
var fieldname='asin';
$('.customer_records_dynamic input').each(function() {
$(this).attr('name', fieldname + count);
count++;
});
});
$(document).on('click', '.remove-field', function(e) {
$(this).parent('.remove').remove();
e.preventDefault();
});
<script src='https://code.jquery.com/jquery-2.2.4.min.js'></script>
<div class="customer_records">
<input type="text" class="input" id="fname" name="asin" required placeholder="ASIN/FSIN or Wesite Link of the product">
<a class="extra-fields-customer button" href="#">Add Another Field</a>
</div>
<br>
<div class="customer_records_dynamic"></div>
Another solution:
edit input field Like:
<input type="text" class="input" id="fname" name="asin[]" required placeholder="ASIN/FSIN or Wesite Link of the product">
now you don't need to count your inputs and use this.
$('.customer_records_dynamic input').each(function() {
$(this).attr('name', fieldname + count);
count++;
});
just edit your back-end and receive input data asin as Array

Since you are using PHP on the backend, you really do not need to keep track of the names like you would for a set static number of fields.
Have a look at this:
<input type="text" name="asin[]" />
<input type="text" name="asin[]" />
<input type="text" name="asin[]" />
// php will convert it to an array in the backend as $_POST['asin']
In your PHP you'll want something like:
<?php
foreach ($_POST['asin'] as $asinInputValue) {
// iterate over each input's value
echo $asinInputValue . "<br>";
}

Related

Get dynamically generated input value on an onClick even using Jquery

I am trying to get respective values of dynamically generated inputs. In other words, I have an X number of dynamically generated inputs; each of these inputs is bound to a button. With that being said, I would like the user to get alerted the dynamically generated input that is bound to the clicked button. What I have done so far does not sort this out and whatever button is clicked, only the first input's value is generated.
I have the following code - a dynamic input and a button:
<input type="hidden" id="job_id" name="jobIdName" value="{{ job_id }}"> // please note this input is dynamically generated....
<button name="get_id_name" class="get_id_class" id="get_id_id" >Show Id</button>
As for Jquery, I have done the following:
$('#get_id_id').each(function(index) {
$(this).click(function() {
var job_ids = $("[name='jobIdName']");
console.log('Job Ids -------------- : ' + job_ids);
});
});
The above code keeps generating only the first generated input value? Any ideas or suggestions?
I have seen some posts that might seem similar to this one but they are very old; also I am looking for a more modern implementation.
Add your "input tag" into div:
var counter = 0;
$(document).ready(function(){
$("#get_id_id").click(function() {
var divChildren = $(".job_ids").children();
if(counter < divChildren.length){
if(counter == '0'){
console.log($(divChildren).eq(0).val());
}else{
console.log($(divChildren).eq(counter).val());
}
counter++;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class ="job_ids">
<input type="hidden" name="jobIdName" value="Test01">
<input type="hidden" name="jobIdName" value="Test02">
<input type="hidden" name="jobIdName" value="Test03">
<input type="hidden" name="jobIdName" value="Test04">
<input type="hidden" name="jobIdName" value="Test05">
</div>
<button name="get_id_name" class="get_id_class" id="get_id_id" >Show Id</button>

Add Anonymous Email to field if checkbox is ticked and hide field

I have a Feedback form which allows people to submit feedback, however I want to give the user the option to remain anonymous, the thing is my CMS must have Email and Name as a mandatory fields so I was thinking of adding a dummy name and email email if they wish to be Anonymous and then hide the field. It'll look something like this:
<input type="checkbox" class="anon">
if this is ticked then add the name "Remain Anonymous" to the Name field and add anon#anonymous.com to Email field, and then also hide the div.remain-anonymous. If unticked, then show the div again and clear the fields to blank again. And do the same again if it is ticked again etc.
<form>
<div class="remain-anonymous">
<input type="text" value="Name" class="name-field">
<input type="text" value="Email" class="email-field">
</div>
<textarea placeholder="Feedback comments"></textarea>
<input type="submit" value="Submit">
</form>
You can try out the below JQuery to achieve what you want.
$(document).ready(function () {
$(".anon").on("click", function () {
var $this = $(this);
if ($this.is(':checked')) {
$(".name-field").val("Remain anonymus");
$(".email-field").val("anon#anonymous.com");
//comment this to see the fields set.
$(".remain-anonymous").hide();
} else {
$(".name-field").val("Name");
$(".email-field").val("Email");
$(".remain-anonymous").show()
}
});
});
check out the same code in the JSFiddle . click here
You can do it like below:
$(function(){
var email = "anon#anonymous.com",
name = "anonymous";
$('.anon').change(function(){
if($(this).is(":checked")){
$('.remain-anonymous').hide();
$('.name-field').val(name);
$('.email-field').val(email);
}else{
$('.remain-anonymous').show();
$('.name-field').val("");
$('.email-field').val("");
}
});
});

Why appended input field submit not working?

When user enter the key press I used Jquery to submit form and after I append another <input> field for another input. But the problem is appended input field submit not working... Instead it expecting the old one.
Code
// html
<div class="ten columns">
<input id="txt_name" class="u-full-width" name="a" type="text" autofocus>
</div>
// javascript
$('#txt_name').keypress(function (e) {
if (e.which == 13) {
$.getJSON('/_main_submit', {
a: $('input[name="a"]').val(),
}, function(data){
$('.after_sub').append(
'<div class="ten columns">'+
'<input id="txt_name" class="u-full-width" name="a" type="text" autofocus>'+
'</div>'
)
$('div input').focus();
})
return false;
}
});
You can only have one element with a certain id in the DOM. Use classes instead of id's for your input fields. Your new input also has the same name, that should be changed, too, if you expect the form to have more than one input field.

Submit multiple inputs through one form and append to array

So I am relatively new to JavaScript but I have experience with programming. I have this code which allows the user to define how many addresses they would like to enter so then I can query google maps and find the geographic center. The problem with this is that it looks very unprofessional in the sense that they have to enter the number of fields on one page and then they are prompted with that many boxes on the next page. Is there any way to make only one form(with all the parameters I require for one entry) and then after they click submit, I append it to an array and then when they decide they have enough addresses they hit the final submit so then I can process the data using a PHP call? Any help would be great, but I am new to this so I might need more spelt out explanations, sorry. Thanks again!
TL;DR: I want to create a single entry field which when submit is clicked, the page does not refresh or redirect to a new page and appends the data entry to an array. From there the user can enter a new input and this input would also be appended to the array until the user has decided no more inputs are necessary at which point they would click the final submit allowing me to process the data.
Here is the code I have so far:
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(function(){
var c = 0;
$("#button1").click(function(){
c = $("#inputs").val();
$("#mydiv").html("");
for(i=0;i<c;i++){
$("#mydiv").append('<input type="text" id="data'+i+'" name="data'+i+'" /><br/>');
}
});
$("#button2").click(function(){
$.post("getdata.php",$("#form1").serialize(),function(data){
});
});
});
</script>
</head>
<body>
<form id="form1">
Type the number of inputs:
<input type="text" id="inputs" name="inputs" />
<input type="button" id="button1" value="Create" />
<div id="mydiv"></div>
<input type="button" id ="button2" value="Send" />
</form>
</body>
</html>
getdata.php
<?php
for( $i=0; $i<$_POST["inputs"] ; $i++){
echo $_POST["data".$i]."\n";
}
?>
Here is code:
EDIT: I rewrite the code, so you can also delete each address
$(document).ready(function(){
$("#add-address").click(function(e){
e.preventDefault();
var numberOfAddresses = $("#form1").find("input[name^='data[address]']").length;
var label = '<label for="data[address][' + numberOfAddresses + ']">Address ' + (numberOfAddresses + 1) + '</label> ';
var input = '<input type="text" name="data[address][' + numberOfAddresses + ']" id="data[address][' + numberOfAddresses + ']" />';
var removeButton = '<button class="remove-address">Remove</button>';
var html = "<div class='address'>" + label + input + removeButton + "</div>";
$("#form1").find("#add-address").before(html);
});
});
$(document).on("click", ".remove-address",function(e){
e.preventDefault();
$(this).parents(".address").remove();
//update labels
$("#form1").find("label[for^='data[address]']").each(function(){
$(this).html("Address " + ($(this).parents('.address').index() + 1));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" method="post">
<div class="address">
<label for="data[address][0]">Address 1</label>
<input type="text" name="data[address][0]" id="data[address][0]" />
</div>
<button id="add-address">Add address</button>
<br />
<input type="submit" value="Submit" />
</form>
After form submit you can loop through addresses like this:
foreach ($_POST['data']['address'] as $address){
...your code
}
Hope this help! :)
Normally how I do this kind of stuff is to provide a user ability to add many input fields at client level and send them all in one array when submitting the form. That is more professional I believe. Try this JSFiddle to see what I mean.
<input type="text" name="address[]" />
if you want to POST dynamic value in a form you can do it like this:
<input type="text" name="adress[]" />
so in your case you could add new fields with javascript or jquery with the same name name="adress[]".
and in your PHP you get an array:
$adresses= $_POST['adress'];
foreach ($adresses as $adress) {
echo $adress;
}
FIDDLE DEMO
To process an array of inputs you can use the following convention:
HTML: simply add square brackets to the name attribute
<input type="text" id="data'+i+'" name="data[]" />
PHP: Post returns an array
for( $i=0; $i<$_POST["data"] ; $i++){
echo $_POST["data"][$i]."\n";
}
JAVASCRIPT: $("#form1").serialize() will retrieve all the inputs data as name=value pairs even the inputs that are added dynamically. There's no need to keep an array you can just process all of them at the end.
You don't need to create an array, $_POST is actually doing it all for you already.
So I suggest you do the following: using javascript (or jQuery), keep the button clicks, but make sure the form submission is prevented (using preventDefault on the form) [EDIT: You actually won't need this, as if the buttons are just buttons, no submit inputs, the form will not submit anyway], and just make sure you append another element every time they click a plus button or something; make sure you increment the name attributes of each input element that gets created.
When the user then creates submit, use submit the form via js, then on your getdata.php you can simply loop through all the values and use them that way you want. You will even be able to know the exact number by calculating the number of times a new input element has been added to the form.
I'll try to write up something for you in a minute, but if I was clear enough, you should be able to do that too.
EDITED: So here is what I've come up with; give it a try and see if this is something for you.
This is how the form would look like:
<form id="form1" name="myform" method="post" action="getdata.php">
Enter address 1: <input type="text" name="address-1" /> <input type="button" value="More" onclick="createNew()" />
<div id="mydiv"></div>
<input type="submit" value="Send" />
</form>
And this would be the js code:
var i = 2;
function createNew() {
$("#mydiv").append('Enter address ' + i +': <input type="text" name="address-' + i +'" /> <input type="button" value="More" onclick="createNew()" /><br />');
i++;
}
...and then getdata.php:
foreach ($_POST as $key => $value) {
echo 'The value for '.$key.' is: '.$value.'<br />';
}
here is a fiddle demo

jquery append input field and post

$('#submit').click(function(){
$.post(
'/foo.php',{
name:myform.name.value,
interest:myform.interest.value,
interest2:myform.interest2.value...
}
});
<input type="button" value="Add more interest" />
I have a form use jquery post. There is a button can append more input type text.
My questions
1 when user click and append more input field, in side of $.post(... how can I add more script, so I can post it to next page?
2 in my php page
if(isset($_POST['interest1'], $_POST['interest2']...)){}
how can I know how many extra input fields user has added?
3 how can I limit maximum 3 input fields user can append?
Are you setting form fields manually in your post request?
Bad idea, you'd be better of using jQuery's serialize method:
$.post("/foo.php", $("#myForm" ).serialize() );
For your second question: use array naming on your form elements:
<input type="text" name="interest[]">
<input type="text" name="interest[]">
<input type="text" name="interest[]">
<input type="text" name="interest[]">
This way you get an array in your post array and can use it like so:
foreach ($_POST['interest'] as $interest) {
doStuff();
}
For your third question I'm assuming you wrote a JS method that
adds an input field to the form? If so you could implement
a limit this way:
window.formFieldCount = 1;
function addFormField() {
if (window.formFieldCount >= 3) {
alert('You can only add three interests!');
return false;
}
// Do your form magic here
window.formFieldCount++;
}
HTML:
<form name="some_name">
<div id="interests">
<input type="text" name="interests[]" />
</div>
<input id="more-interests" type="button" value="Add more interest" />
<input id="submit" type="button" value="Submit" />
</form>
Javascript:
$(document).ready(function(){
var maximumNumberOfInterests = 3;
$('#more-interests').click(function(e){
if ($("input[name='interests[]']").size() < maximumNumberOfInterests) {
$('#interests').append('<input type="text" name="interests[]" />');
} else {
alert('The maximum number of interests has been reached!');
}
});
$('#submit').click(function(){
$.post('/foo.php', $('form').serialize());
});
});
PHP:
if (count($_POST['interests'])) {
foreach ($_POST['interests'] as $interest) {
echo $interest;
}
}
Here is a DEMO of the HTML/Javascript part
q2. can you change form like this:
static inputs
<input name='static[something]'>
<input name='static[somebody]'>
<input name='static[etc]'>
and dynamically generated inputs
<input name='dynamic[]'>
<input name='dynamic[]'>
<input name='dynamic[]'>
php
if (isset($_POST['dynamic']))
{
foreach ($_POST['dynamic'] as $key => $value)
{
/* do some shit with dynamic inputs */
}
}
Please use prepend function before form submit
Like
$("#myForm").prepend("<input type=\"text\" name=\"interest"+counter+"\"").submit(function(){
console.log($("#myForm" ).serializeArray())
$.post(Event.target.action, $(Event.target).serializeArray(), function(data){
// your code here
})
return false;
})

Categories

Resources