I need a form to generate form elements dynamically. So far I have modified a script to add another field txtEmail1 and it works fine and generates fields once a user hits the add button.
Now I need to prefix label "Full Name" with serial no. 1, 2, 3, 4 and so on. I tried but I am not able to get it right need an experts help with this.
<script type="text/javascript">
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// manipulate the name/id values of the input inside the new element
newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
newElem.children(':first').attr('id', 'txtEmail' + newNum).attr('txtEmail', 'txtEmail' + newNum);
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
// enable the "remove" button
$('#btnDel').attr('disabled','');
// business rule: you can only add 5 names
if (newNum == 5)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
$('#input' + 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>
</head>
<body>
<div>
<input type="button" id="btnAdd" value="add another name" />
<input type="button" id="btnDel" value="remove name" />
</div>
<div id="input1" style="margin-bottom:4px;" class="clonedInput">
<label id="lblSno1"></label> Full Name
<input name="name1" type="text" class="TextBoxNext" id="name1" /></td>
<input name="txtEmail1" type="text" class="TextBoxNext" id="txtEmail1" /></td>
</div>
</form>
</body>
I also need to assign the count to some hidden field, so that I can run an insert query on the number of fields that the user created.
Try something like the following. I've made a few modifications to the structure of your code, namely:
* Creating a hidden template that all visible clones will be cloned from
* Getting the add/remove buttons working as desired
* Added hidden field which holds the number of items
* Putting bulk of code into functions for re-use
<script type="text/javascript">
// document - on load
$(document).ready(function() {
// add the first item
AddInput();
UpdateButtons();
// add button - click
$('#btnAdd').click(function() {
AddInput();
UpdateButtons();
});
// delete button - click
$('#btnDel').click(function() {
$('.clonedInput:last').remove();
UpdateButtons();
});
});
function AddInput()
{
// how many cloned input fields we currently have
var numItems = $('.clonedInput').length;
var newNum = new Number(numItems + 1);
// create the new element via clone() based on hidden template
var newElem = $('.templateInput').clone();
// update attributes on parent tag
newElem.attr('id', 'input' + newNum);
newElem.attr('class', 'clonedInput');
newElem.show();
// update child elements
newElem.children('#lblSno').html(newNum + ' ' + newElem.children('#lblSno').html());
newElem.children('#lblSno').attr('id', 'lblSno' + newNum);
newElem.children('#name').attr('id', 'name' + newNum);
newElem.children('#txtEmail').attr('id', 'txtEmail' + newNum);
// insert the new element
$('#allInputs').append(newElem);
}
function UpdateButtons()
{
// get number of items
var numItems = $('.clonedInput').length;
// only enable delete button when there is more than 1 item
if (numItems > 1)
$('#btnDel').removeAttr('disabled');
else
$('#btnDel').attr('disabled', 'disabled');
// only enable add button when there are less than 5 items
if (numItems < 5)
$('#btnAdd').removeAttr('disabled');
else
$('#btnAdd').attr('disabled', 'disabled');
// update the hidden field
$('#hdnNumItems').val(numItems);
}
</script>
<form>
<div>
<input type="button" id="btnAdd" value="add another name" />
<input type="button" id="btnDel" value="remove name" />
<input type="hidden" id="hdnNumItems" value="0" />
</div>
<div id="allInputs">
<div class="templateInput" style="margin-bottom:4px; display:none;">
<label id="lblSno">Full Name</label>
<input name="name" type="text" class="TextBoxNext" id="name1" /></td>
<input name="txtEmail" type="text" class="TextBoxNext" id="txtEmail1" /></td>
</div>
<div>
</form>
There are thousands of ways to do what you are trying to do, and it's all entirely depends upon your choice which one to use. So, without messing with your logic and simply going with your own code, in order to add serial numbers, just add this one line :
newElem.text(newNum + " ) Full Name " );
That's it. You've got your serial number prepended.
Related
Hi I want to create a stamp script and I want the user to enter his name and address in three fields,
then he should see the fields later in the stamp edition?
I have 3 input fields where the user can give in his data,
now i will give this data in a new class. This is what i have:
window.onload = function() {
$( "#Text1" )
.keyup(function() {
var value = $( this ).val();
$( ".ausgabe" ).text( value );
})
.keyup();
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="Text1">
<input type="text" id="Text2">
<input type="text" id="Text3">
<div class="ausgabe"></div>
It looks like you want to mimic what the user is typing in the text inputs and show it in ausgabe. If that's what you want, then you can tie the keyUp event to each of the inputs.
$(input [type='text']).keyUp(function() {
var value = $(this).val();
$('.ausgabe').text(value);
}
But this will overwrite .ausgabe every time text is entered into a different input.
You could get the value of .ausgabe every time keyUp fires and pre-pend that value:
So you may want to have a button that renders each input's value into .ausgabe:
<button>.click(function() {
$(input[type="text"]).each(function() {
var boxText = $(this).val(); //text box value
var aus = $('.ausgabe').text(); //ausgabe value
$('.ausgabe').text(boxText + ' ' + aus); //combine the current text box value with ausgabe
})
})
As you have not made it very clear what you are trying to accomplish, I am providing a simple example that might send you down the right path.
$(function() {
function updateDiv(source, target) {
var newVal = "";
source.each(function() {
newVal += "<span class='text " + $(this).attr('id').replace("Text", "item-") + "'>" + $(this).val() + "</span> ";
});
target.html(newVal);
}
$("[id^='Text']").keyup(function(e) {
updateDiv($("input[id^='Text']"), $(".ausgabe"));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="Text1">
<input type="text" id="Text2">
<input type="text" id="Text3">
<div class="ausgabe"></div>
Since you already seem to understand .html() and .text(), we can look at the Selector. The one used will select all elements with an ID Attribute of Text in the beginning of the string. See More: https://api.jquery.com/category/selectors/attribute-selectors/
I'm fiddling around with js / jquery .. I'm trying to create a preview based on data entered in a form. In one of the input fields a script adds new fields every time you press Tab (or in other words choose the next field). So from these dynamic fields I want to retrieve data from the first two fields and put them into the preview. What I've done is to run a function that adds a number on the end of the id to those fields, so they get the names contestant_1, contestant_2 etc. based on the number of fields that are opened.
I then want the data from contestant_1 and _2 to be entered in boxes in the preview.
What I then made is another function waiting for a keyup event of one of these input fields. BUT it is not able to react to them after they have gained _1 and _2. If I hard code in the first field named _1, then it comes up in the preview.
In the pictures you can see that I have entered Boks1 and Boks2 (Box1 and 2 i Norewegian) in the first two fields, but only Boks1 comes up.
Form
http://imgur.com/fmmYnBu
Preview
http://imgur.com/NcI4lN1
This code is executed when something happens in the field
$('#tname').keyup(update_tname);
$('#contestant_1').keyup(update_contestant_1);
$('#contestant_2').keyup(update_contestant_2);
This is the function that updates are well only the last two that have some importance on exactly this.
function update_contestant_1(){
console.log("Inne i update_contestant_1");
$('#preview').slideDown();
$('#pview_contestant_1').fadeIn();
// Values to preview
var contestant_1 = $('#contestant_1').val();
$('#display_contestant_1').html(contestant_1);
}
Input field looks like this
<lable for="contestant" class="col-md-2 control-label">Contestants:</lable>
<div class="input-group input-group-option col-md-4">
<input class="form-control" type="text" id="contestant_" name="option[]" placeholder="Write contestant here..." required></input>
<span class="input-group-addon input-group-addon-remove">
<span class="glyphicon glyphicon-remove"></span>
</span>
</div>
And this is the function that creates new fields, change id and delete them
$(function () {
// Variable for counting how many contestants fields that are open
var i=0;
$(document).on('focus', 'div.form-group-options div.input-group-option:last-child input', function () {
var sInputGroupHtml = $(this).parent().html();
// Uncomment comments below to inherit div classes from div on index page.
// This is not in use now, because we need a offset to line input fields below each other
// var sInputGroupClasses = $(this).parent().attr('class');
// $(this).parent().parent().append('<div class="' + sInputGroupClasses + '">' + sInputGroupHtml + '</div>');
$(this).parent().parent().append('<div class="input-group input-group-option col-md-4 col-md-offset-2">' + sInputGroupHtml + '</div>');
// Adds a number at the end of the ID
i++;
console.log(i);
var newID='contestant_'+i;
$(this).attr('id',newID);
});
$(document).on('click', 'div.form-group-options .input-group-addon-remove', function () {
$(this).parent().remove();
// Counts down so the next contestants field that opens, has the right number
i--;
console.log(i);
var newID='contestant_'+i;
$(this).attr('id',newID);
});
});
I will be greatfull for any help.
Also, hope I did this right, this is my first post here.
Following on from my previous question
I've now got a form that when clicking add, adds a new input field to the form incrementing the field name and input text by one each time. eg: phone_number1, phone_number2 etc
The jquery I'm using is :
$(document).ready(function(){
var phone_number_form_index=1;
$("#add_phone_number").click(function(){
phone_number_form_index++;
$(this).parent().before($("#phone_number_form").clone().attr("id","phone_number_form" + phone_number_form_index));
$("#phone_number_form" + phone_number_form_index).css("display","inline");
$("#phone_number_form" + phone_number_form_index + " :input").each(function(){
$(this).parent().find('span').text('Phone number ' + phone_number_form_index);
$(this).attr("name",$(this).attr("name") + phone_number_form_index);
$(this).attr("id",$(this).attr("id") + phone_number_form_index);
});
$("#remove_phone_number" + phone_number_form_index).click(function(){
$(this).closest("div").remove();
});
});
});
This JFiddle shows the form working and when adding a new row the field name is incremented as is the input text.
http://jsfiddle.net/yezw6c51/25/
However if I remove a field, the numbering can get messed up.
eg:
With one field the input text and field names are Phone Number 1 /
phone_number1
With two fields the input text and field names are Phone Number 1 &
Phone Number 2 etc
With three fields the input text and field names are Phone Number 1 &
Phone Number 2 & Phone Number 3 etc
if I then remove phone number 2 using the remove button I end up with 1 & 3, clicking add starts at 4.
Is there any way if I delete 2 instead of 1 & 3, I would get 1, 2 and the next add would be 3 ?
This would need to update all field names and input text entries that are being updated.
After adding/removing you can renumber all the inputs and labels like follows:
$(document).ready(function(){
$("#add_phone_number").click(function(){
$(this).parent().before($("#phone_number_form").clone().show());
reNumberInputs();
});
$("form").on("click", "[id^='remove_phone_number']", function(){
$(this).closest("div").remove();
reNumberInputs();
});
});
function reNumberInputs() {
$("input[type='text']:visible").each(function(index, element) {
var displayIndex = (index + 1).toString();
element.id = "phone_number" + displayIndex;
element.name = "phone_number" + displayIndex;
if (index > 0) {
$(this).prev("span").html("Phone number " + displayIndex);
$(this).next("input").prop("id", "remove_phone_number" + displayIndex).prop("name", "remove_phone_number" + displayIndex);
}
});
}
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="phone_number_form" class="hidden">
<p>
<span>Phone number</span> : <input type="text" name="phone_number" />
<input type="button" id="remove_phone_number" value="Remove" />
</p>
</div>
<form>
<p>
Phone number : <input type="text" name="phone_number1" />
</p>
<p>
<input type="button" value="Add phone number" id="add_phone_number" />
</p>
</form>
Updated Fiddle
You can use the field name as phone_number[] this will be the standard.
If you can't change the procedure then on submit of form rename your fields by getting all the created one by one and assigning current text field values to new fields but it is not a standard method.
Hope you get your answer and if you have any other question get in touch with me on my new blog on http://www.sourabhmodi.in/. I will be happy to help you..
I've got two bits of code that I'd like to work together but I don't manage to integrate this jQuery snippet into the JavaScript correctly …
JavaScript:
(function(){
// Creates the plugin
tinymce.create('tinymce.plugins.mygallery', {
// Creates control instances based on the control's ID.
createControl : function(id, controlManager) {
if (id == 'mygallery_button') {
// Creates the button
var button = controlManager.createButton('mygallery_button', {
title : 'MyGallery Shortcode', // Title of the button
image : '../wp-includes/images/smilies/icon_mrgreen.gif', // Path to the button's image
onclick : function() {
// Triggers the thickbox
var width = jQuery(window).width(), H = jQuery(window).height(), W = ( 720 < width ) ? 720 : width;
W = W - 80;
H = H - 184;
tb_show( 'My Gallery Shortcode', '#TB_inline?width=' + W + '&height=' + H + '&inlineId=mygallery-form' );
}
});
return button;
}
return null;
}
});
// Registers the plugin
tinymce.PluginManager.add('mygallery', tinymce.plugins.mygallery);
// Executes this when the DOM is ready
jQuery(function(){
// Creates a form to be displayed everytime the button is clicked
var form = jQuery('<div id="mygallery-form"><table id="mygallery-table" class="form-table">\
<form id="myForm">\
<div id="input1" style="margin-bottom:4px;" class="clonedInput">\
Name: <input type="text" name="name1" id="name1" />\
</div>\
<div>\
<input type="button" id="btnAdd" value="add another name" />\
<input type="button" id="btnDel" value="remove name" />\
</div>\
</form>\
</div>');
[…]
});
})()
jQuery:
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// manipulate the name/id values of the input inside the new element
newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
// enable the "remove" button
$('#btnDel').attr('disabled','');
// business rule: you can only add 5 names
if (newNum == 5)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
$('#input' + 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');
});
FYI: The JS creates a popup with a form (WordPress) and with the jQuery snippet I'd like to implement the feature that the user can add more input fields dynamically.
Thanks for your help!
You can put the jQuery snippet after your javascript code. That shouldn't be the problem since your jQuery code is merely binding events.
However, I can't tell where #btnAdd and #btnDel are. The problem may be that the elements are created after the jQuery code is run, hence when you called this:
$('#btnAdd').click(function(){...});
the element #btnAdd was not there.
Try this:
$(document).on('click', '#btnAdd', function(){...});
This will bind the click event to document (which is always present) instead of #btnAdd.
To improve the performance though, you should bind it to a parent of #btnAdd that you know for sure is present when document is ready.
$('<p><input type="text" class = "class-'+ (++i) +'" onclick="'(+ this.value = ''; +)'" value="Enter Choice #' + i + '"/></p>')
I'm not sure if this is the correct syntax or not, but whatever I am using is not working. ANy help? Thanks
HTML:
<input type="text" class="class-1" value="Enter Choice #1">
<input type="text" class="class-2" value="Enter Choice #2">
JQUERY:
$(document).ready(function() {
$('input[class^="class-"]').focus(function() {
var $input = $(this);
if($input.val() == $input.data('default_val') || !$input.data('default_val')) {
$input.data('default_val', $input.val());
$input.val('');
}
});
$('input[class^="class-"]').blur(function() {
var $input = $(this);
if ($input.val() == '') $input.val($input.data('default_val'));
});
});
Above code clear the value when the textfields gets focus and adds the default value when textfield is empty on lost focus (blur).
Updated fiddle: http://jsfiddle.net/K3Sx7/4/
EDIT: updated code to conform question.
Add an id to your input field:
<input id="myinput"...
Then add this code in your $(document).ready(... call:
$('#myinput') // get element whose id is 'myinput'
.click(function() { // bind a click handler
$(this).val('') // clear field
.unbind('click'); // unbind click handler to avoid field being cleared again
})
I think you can do it without jQuery
try this
<p><input type="text" class = "class-1" onclick="this.value='';" value="Enter Choice # 1"/></p>
To do it inline like that, you need to keep the this.value='' as part of the string:
$('<p><input type="text" class = "class-'+ (++i) +'" onclick="this.value=\'\'" value="Enter Choice #' + i + '"/></p>');
Notice the " onclick="this.value=\'\'", where the single quotes are escaped to keep the main string from being terminated.
Here's a working example for you.
var i = 0;
$('<input type="text" class="class-'+ ++i +'" value="Enter Choice #' + i + '"/>')
.click(function(){
this.value = '';
})
.wrap('<p />')
.parent()
.appendTo('#container');
http://jsfiddle.net/jruddell/FVqjQ/