Jquery Incrementing field names - javascript

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..

Related

Javascript Multiple Inputs Value Output

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/

Adding a score to every input field the user fills in the form and displaying it

Currently i have developed a program that gets the count of all the inputs field and adding up a percentage for the numbers of fields that are filled individually.
what i need now here, i need to assign a number to each input field and when the user fills an input field i need to show it to the user as a " SCORE ".
below is the program i have built.
<html>
<body>
<label> Name </label>
<input class="track"/>
<label> Name </label>
<input class="track"/>
<h5>Profile Strength <span class='perc'>0</span>%</h5>
</body>
</html>
and the JavaScript is
<script>
$('.track').change(function(e) {
update_progress();
});
// supports any number of inputs and calculates done as %
function update_progress() {
var count = $('.track').length;
var length = $('.track').filter(function() {
return this.value;
}).length;
var done = Math.floor(length * (100 / count));
$('.perc').text(done);
$('.meter').width(done + "%");
}
so when you fill the first input field the 'Profile strength' will show 50% as there are only 2 input fields, and when you fill the second input it will show 100%.
i want to show a number instead of a percentage here like
input 1 = 10
input 2 = 20
so when the user fills input 1 his "SCORE" will be 10,
and when the user fills the next input the total must add on and show 30 in real time.
sorry if have confused a few developers but this the only way i understood the assignment i got.
Try the following:
Html:
<html>
<body>
<label> Name </label>
<input class="track" data-score=10 />
<label> Name </label>
<input class="track" data-score=20 />
<h5>Profile Strength <span class='perc'>0</span>%</h5>
<h5>Score <span id="score">0</span></h5>
</body>
</html>
JS:
$('.track').change(function(e) {
update_progress();
});
// supports any number of inputs and calculates done as %
function update_progress() {
var score = 0
$('input.track').each(function(){
var _score = $(this).data("score")
if ($(this).val().length > 0) {
score += _score
}
})
$('#score').text(score)
var count = $('.track').length;
var length = $('.track').filter(function() {
return this.value;
}).length;
var done = Math.floor(length * (100 / count));
$('.perc').text(done);
$('.meter').width(done + "%");
}
Or, a live version https://jsfiddle.net/wmt6cznh/2/
Is this what you want to achieve?

Jquery if statements

I have a form which allows the user to input their own custom values for a simple online ‘thermostat’ (Minimum Temperature, Maximum Temperature and PowerSaver Maximum Temperature).
I am trying to write some jquery such that when the user submits the form with the custom values, it sets the custom values, and also changes the text to show the user which changes they made (e.g. “You've changed your minimum temperature to 5”)
Currently, only the first form field ‘minimum temperature’ is working, and setting the correct value. The other two aren’t working as expected.
In addition, I’d like the user to be able to set all the custom values at once (one form submission), and for the following statements to appear on screen simultaneously e.g.:
You've changed your minimum temperature to 5
You've changed your maximum temperature to 50
You've changed your power saver maximum temperature to 30
The above statements should only show if the user has entered a value on that field. i.e. if the user has only entered a value for the maximum temperature, it should only show the following statement:
You've changed your maximum temperature to 50
Any help or pointers in the right direction would be really appreciated. Thanks very much in advance!
Code for the form:
<form id="custom-values">
<input type="text" id="mintemperature" placeholder="Minimum temperature">
<input type="text" id="maxtemperature" placeholder="Maximum temperature">
<input type="text" id="maxtemperatureps" placeholder="Max. PowerSaver temperature">
<input type="submit" class="submit-button" value="Set!">
</form>
Jquery code:
$('#custom-values').on('submit', function(event) {
event.preventDefault();
if ($('#mintemperature').val() !== "") {
$('#message').text("You've changed your minimum temperature to " + $('#mintemperature').val())
thermostat.minTemperature = parseInt($('#mintemperature').val())
}
if ($('#maxtemperature').val() !== "") {
$('#message').text("You've changed your maximum temperature to " + $('#maxtemperature').val())
thermostat.minTemperature = parseInt($('#mintemperature').val())
}
if ($('#maxtemperatureps').val() !== "") {
$('#message').text("You've changed your power saver maximum temperature to " + $('#maxtemperatureps').val())
thermostat.minTemperature = parseInt($('#mintemperature').val())
}
});
One approach is:
$('#custom-values').on('submit', function(event) {
event.preventDefault();
// creating an object to define what setting is associated
// with each element (identified by its id as the key):
var messages = {
'mintemperature' : 'minimum',
'maxtemperature' : 'maximum',
'maxtemperatureps' : 'maximum power-saving'
},
// creating an array, using map and get, of the nodes that have
// had their values changed from the default, and whose value can
// be parsed as a number (in base 10):
changes = $(this).find('input[type="text"]').map(function () {
if ( this.value !== this.defaultValue && parseInt(this.value, 10)) {
return this;
}
}).get(),
// creating an '<li>' element as a jQuery object:
li = $('<li />'),
// creating a variable to hold a clone within the (later) forEach:
clone;
// empty out existing messages:
$('#messages').empty();
// iterate over the array of changed nodes:
changes.forEach(function (changed) {
// cloning the created jQuery <li> object:
clone = li.clone();
// setting its html to the following concatenated string:
clone.html('You have changed the ' + messages[changed.id] + ' temperature setting, to: ' + changed.value + '°C')
// appending the <li> to the '#messages' element:
.appendTo('#messages');
});
});
#messages {
border: 1px solid #000;
margin: 0.5em;
}
/* hiding the #messages element if it has
no content (including white-space): */
#messages:empty {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="custom-values">
<input type="text" id="mintemperature" placeholder="Minimum temperature">
<input type="text" id="maxtemperature" placeholder="Maximum temperature">
<input type="text" id="maxtemperatureps" placeholder="Max. PowerSaver temperature">
<input type="submit" class="submit-button" value="Set!">
</form>
<ul id="messages"></ul>
References:
appentTo().
clone().
empty().
eq().
get().
html().
on().

Want value from javascript in Jquery, this is php?

I am following this example - http://jqueryui.com/selectable/#serialize and would like to be able to set the value of a hidden input field based on the user selection. So rather than the value being displayed as per the example, that value instead would be consecutively added to the hidden input field value. How can I achieve this?
<input type="hidden" />
If you want the selected value to be placed in your hidden field, add a class or id to your hidden input, and then change the following lines from the source example page:
your hidden input
<input type="hidden" id="hiddenInput" />
from the example, change
var result = $( "#select-result" ).empty();
to your hidden input
var result = $('#hiddenInput').empty();
then change
result.append( " #" + ( index + 1 ) );
to
result.val('#' + (index + 1));
to add the values rather than replace them, change the line to
result.val(result.val() + "#" + ( index + 1 ) );
here is a working example - http://jsfiddle.net/DBuVf/1

Generate jQuery form fields along with sno in a label

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.

Categories