Increase div id number with new div fields - javascript

The following script creates new input fields up to 4. I need to know how can I increase the ID also as follows..
with first click, "var fieldHTML" generate :
<div><input type="text" id="sPhone_1" value=""/><img src="remove-icon.png"/></div>
Second click: id="sPhone_2"
Third click: id="sPhone_3" and so on..
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var maxField = 4; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div><input type="text" id="sPhone_" value=""/><img src="remove-icon.png"/></div>'; //New input field html
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxField){
x++; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
</script>
<div class="field_wrapper">
<div>
<input type="text" name="Phone" id="sPhone" value=""/>
<img src="add-icon.png"/>
</div>
</div>

$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxField){
x++; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
newId = 'sPhone_' + x;
document.getElementById('sPhone_').id = newId;
}
});
Try this. This should post the div in the html with the initial id sPhone_, then it gets that element and replaces the id with your new created id.
Or you can create the string to append in the function like this:
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxField){
x++; //Increment field counter
var fieldHTML = '<div><input type="text" id="sPhone_"' + x + 'value=""/><img src="remove-icon.png"/></div>'; //New input field html
$(wrapper).append(fieldHTML); //Add field html
}
});

Related

how to generate dynamic input and get the value by id using jquery

Actually i have a form where i enter name ,html page name in a input box and save it to the database. Here i got some issues
i am able generate input box but how to get the value of that input box ?
how to get the dynamic values of the input box which was entered in dynamic boxes and send it to post request as i know how to send a static input box value request for multiple how can we send it .
here is what below is my code
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="mytext[]"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
i thins above i can generate dynamic input box and can remove it but unable to get values so how can generate by using id and post all dynamically generated values to the database
You can use the jquery #map() function like this:
var list = wrapper.find('input').map(function() {
return $(this).val();
}).get();
when you want to submit the list of values to the send to the server - see demo below:
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="mytext[]"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
});
/* ADDED THIS */
$('.submit').click(function() {
var list = wrapper.find('input').map(function() {
return $(this).val();
}).get();
// send to server here
console.log(list);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>
<button class="submit">Submit</button>
Yea can try something like this
var inputField = $('<div><input type="text" name="mytext[]"/>Remove</div>');
$(wrapper).append(inputField);
Then you can attach an event to that variable.
inputField.on('change', 'input', function() {
var value = $(this).val();
console.log(value);
});
Hope this helps you :)
Another way, add the following button the form:
<button class="getValue">Get Field Values</button>
Add the below button click event in JS on load:
$(getValue).click(function (e) {
e.preventDefault();
let fieldValues = "";
$("input").each(function(i,e){
fieldValues = fieldValues == "" ? $(e).val() : fieldValues + ", " + $(e).val();
})
alert(fieldValues);
});

Create dynamic text boxes then write to text file

So there must be an easier way to create this. I have a form with the following HTML:
<p>Names</p>
<ul class="container1" style="list-style-type:none;">
<li><input type="text" size="10" name="Name" /></li>
</ul>
<input type="button" class="add_form_field" value="+">
I then added some JS to create new text boxes if a user needs to add more names:
Taken from: http://www.sanwebcorner.com/2017/02/dynamically-generate-form-fields-using.html
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('<div><input type="text" name="Name"/>Delete</div>'); //add input box
}
else
{
alert('You Reached the limits')
}
});
$(wrapper).on("click",".delete", function(e){
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('<div><input type="text" name="Name"/>Delete</div>'); //add input box
}
else
{
alert('You Reached the limits')
}
});
$(wrapper).on("click",".delete", function(e){
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
function check() {
var temp = document.getElementsByClassName("formElem");
if (document.getElementById("ckbox").checked) {
for (var e = 0; e < temp.length; e++) { // For each element
var elt = temp[e];
elt.required = false;
}
} else {
for (var e = 0; e < temp.length; e++) { // For each element
var elt = temp[e];
elt.required = true;
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Names</p>
<ul class="container1" style="list-style-type:none;">
<li><input type="text" size="10" name="Name" /></li>
</ul>
<input type="button" class="add_form_field" value="+">
I then need to write those appended values to a .CSV file using PHP and here is where I am having the issue:
<?php
// Receive form Post data and Saving it in variables
header('Location: thanks.html');
$Name = "";
$Name = #$_POST ['Name'];
// Write the name of text file where data will be store
$filename = "file.csv";
// Merge all the variables with text in a single variable.
$f_data= '
Names for people: '.$Name.' ';
$file = fopen($filename, "r+");
fwrite($file,$f_data);
fclose($file);
?>
What happens is that the last appended text box gets written into the csv file.Is there a way to pass these created text boxes so they can write to a the file? Really similar question: Pass dynamic text input to PHP in order to write to text file
But I'm not sure if this can be done with text boxes.
The problem is that every input you add has the name “name”, so PHP can only access the last one (which overwrote the others). To get around this, you can add an index to the input name or make an array of them. This can be achieved like so:
<input type="text" name="name[]"...>
So now, on the PHP script you can iterate over that array to get all the inputs, or implode all the elements into a variable:
<?php
$names = implode(", ", $_POST["name"]); // all the names, comma-separated
?>
Now you can use $names inside $f_data to see all the inputted fields.
(Thanks Fred-ii for the heads up about the quotes)

javascript \u00Ao is not working

I have reference for using ;nbsp in javascript from in script is not getting compiled but It still couldn't work for me.
$(document).ready(function(){
var addButtonn = $('.add_rescuer'); //Add button selector
var wrapperr = $('.field_rescuer'); //Input field wrapper
var fieldHTMLL = '<div data-role="dynamic-fields"><div class="form-inline"><div class="form-group" id="txtboxToFilter"><label for="instansi"><font color="white">Instansi yang Terlibat:</font></label> \u00A0\u00A0\u00A0 <input type="text" class="form-control" name="rescuer[]" placeholder="Masukkan Kegiatan" required size="92"/></div> <i class="fa fa-fw fa-minus"></i></div></div></div>'; //New input field html
var y = 1; //Initial field counter is 1
$(addButtonn).click(function(){ //Once add button is clicked
y++; //Increment field counter
$(wrapperr).append(fieldHTMLL); // Add field html
});
$(wrapperr).on('click', '.remove_rescuer', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').parent('div').remove(); //Remove field html
y--; //Decrement field counter
});
});
When I tried to running that code, it was not changing anything. What is the problem ? \u00A0 has not worked properly.
In that font color is the problem, i think it's in white color:
for your reference
https://codepen.io/kalaiselvan/pen/ybWxxW
$(document).ready(function(){
var addButtonn = $('.add_rescuer'); //Add button selector
var wrapperr = $('.field_rescuer'); //Input field wrapper
var fieldHTMLL = '<div data-role="dynamic-fields"><div class="form-inline"><div class="form-group" id="txtboxToFilter"><label for="instansi"><font color="black">Instansi yang Terlibat:</font></label> \u00A0\u00A0\u00A0 <input type="text" class="form-control" name="rescuer[]" placeholder="Masukkan Kegiatan" required size="92"/></div> <i class="fa fa-fw fa-minus"></i></div></div></div>'; //New input field html
var y = 1; //Initial field counter is 1
$(addButtonn).click(function(){ //Once add button is clicked
y++; //Increment field counter
$(wrapperr).append(fieldHTMLL); // Add field html
});
$(wrapperr).on('click', '.remove_rescuer', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').parent('div').remove(); //Remove field html
y--; //Decrement field counter
});
});

Jquery, Pass an input value to a cloned input field

I have a form with a few input fields used to create an address book. If the user wants to add another set of names, they can click on add more. If the users have the same username, instead of typing it over and over again, i added a checkbox.
If the user selects the checkbox, it will pass the value from the first username input field to ALL username input fields.
The code below works on the second set of input fields but when i click on add more, it doesnt pass the values.
$('#check1, #addmore').click(function(){
if (this.checked) {
$('.pass').val($('.original').val());
}
});
here's the full code.
You can use the class you already have assigned to your button which is the .add_field_button class. Then you just have you can assign the value to each input box value with an id that starts with username as long as the #check1 element is checked.
//changed the selector, you already had this class present in your markup
$('.add_field_button').on(
"click",function(){
//if the check1 checkbox is checked
if ($("#check1").is(":checked")) {
/*select every id that starts with "username" and sets it value
to the .original input text box value*/
$("[id^=username]").val($(".original").val());
}
});
After reviewing your jsfiddle I found some additional errors:
You are using html comments in your JavaScript. Instead of <!--my comment--> you will need to use either // for single line comments or /* my comment */ for multi-line comments.
After removing the comment syntax errors I may have came across some unexpected behavior when using my original answer. The if then statement still applies but I moved it to inside your add_more button event because it was only cloning the username after the third set of inputs was being added.
Live Example: http://codepen.io/larryjoelane/pen/rxKZYm?editors=1010
Updated JavaScript:
$(document).ready(function() {
Number.prototype.pad = function(size) {
var s = String(this);
while (s.length < (size || 0)) {
s = "0" + s;
}
return s;
}
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
var c = 9;
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
c++;
$(wrapper).append('<div><label><span>Template Id :</span><input type="text" name="templateid' + x + '" id="templateid' + x + '"></label><br><label><span>UNC Path :</span><input type="text" name="uncpath' + x + '" id="uncpath' + x + '"></label><br><label><span>Username :</span><input type="text" class="pass" name="username' + x + '" id="username' + x + '"></label><br><label><span>Password :</span><input type="text" name="password' + x + '" id="password' + x + '"></label><br><label><span>Name :</span><input type="text" name="scantoname' + x + '" id="scantoname' + x + '"></label>Remove</div>'); //add input box
/*add input value to 'how many field*/
$.each($('input[name="howmany[]"]'), function() {
$(this).val(x);
});
/*add input value to 'templateid field*/
$('input[name="templateid' + x + '"]').each(function() {
$(this).val((x).pad(3, 0));
});
}
//////////added code////////////////
//if the check1 checkbox is checked
if ($("#check1").is(":checked")) {
/*select every id that starts with "username" and sets it value
to the .original input text box value*/
$("[id^=username]").val($(".original").val());
}
//////////added code////////////////
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
First you need to add the id #addmore to your button in the HTML
<button id="addmore" class="add_field_button btn btn-primary">Add More</button>
Then just modify your click function like this :
$('#check1, #addmore').click(function(){
if($('#check1').is(':checked')) {
$('.pass').val($('.original').val());
}
});

How can I extract the values entered in the input boxes generated dynamically and pass it to controller using jquery?

I have a form wherein a user can enter input boxes and remove them at a click. I want to extract the values entered in these input boxes and pass them to controller using jQuery. How do I do that?Right now I am using ids to extract the values but I do not think that is a better method because suppose I add 4 options and then I remove all of them and then again add inputs, I will not be able to track these ids and extract the values.
Here is my HTML code:
<button type="button" class="addoption" id="addoption_btn">Add more option</button>
<div id="Options">
<input type="text" name="mytext[]" id="option_1" placeholder="Option 1"/>
</div>
Here is my JavaScript:
var MaxOptions = 4; //maximum input boxes allowed
var Optionsform = $("#Options"); //Input boxes wrapper ID
var AddButton = $("#addoption_btn"); //Add button ID
var x = Optionsform.length; //initial text box count
var OptionCount=1; //to keep track of text box added
$(AddButton).click(function (e) //on add input button click
{
if(x <= MaxOptions) //max input box allowed
{
OptionCount++; //text box added increment
//add input box
$(Optionsform).append('<div><input type="text" name="mytext[]" id="option_'+ OptionCount +'" placeholder="Option '+ OptionCount +'"/>×</div>');
x++; //text box increment
}
return false;
});
$("body").on("click",".removeclass", function(e){ //user click on remove text
if( x > 1 ) {
$(this).parent('div').remove(); //remove text box
x--; //decrement textbox
}
return false;
});
Here is the jQuery I am using to pass the data to my controller:
$("#addquestion_btn").click(function(){
var val= CKEDITOR.instances['question_topic'].getData();
storequestion(val);
});
function storequestion(ques)
{
$.post("/instructor/store/question",{
question: ques,
option1: $("#option_1").val(),
option2: $("#option_2").val()
},function(data){
if(data[0]==="success")
{
window.location.href = '/instructor/create/topics';
}
else
{
alert("fails");
window.location.href = '/instructor';
//redirect to further page to enter courses
}}
,'json');
}
Please use below mentioned code to read through all displayed options.
function storequestion(ques) {
obj = {};
obj[question] = ques;
$("#Options:input[name*='mytext']").each(function (index) {
obj['option' + index] = $(this).val();
});
$.post("/instructor/store/question", obj
, function (data) {
if (data[0] === "success") {
window.location.href = '/instructor/create/topics';
}
else {
alert("fails");
window.location.href = '/instructor';
//redirect to further page to enter courses
}
}
, 'json');
}

Categories