Can't get data from dynamically created input fields - javascript

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.

Related

Setting values of dynamically added input fields changing all input fields

I have a form where users can create recipes. I start them off with one ingredient field (among others) and then use .append() to add as many more as they want to the div container that holds the first ingredient. The first input field has an id of IngredientName1 and dynamically added input fields are IngredientName2, IngredientName3, etc.
When they start typing in the input field, I pop a list of available ingredients filtered by the value they key into IngredientNameX. When they click on an ingredient in the list, it sets the value of the IngredientNameX field to the text from the div - like a search & click to complete thing. This all works very well; however, when you add IngredientName2 (or any beyond the one I started them with initially) clicking on an available ingredient sets the values of every single IngredientNameX field. No matter how many there are.
I hope this is enough context without being overly verbose, here's my code (I've removed a lot that is not relevant for the purpose of posting, hoping I didn't remove too much):
<div id="ingredientsContainer">
<input type="hidden" id="ingredientCounter" value="1">
<div class="ingredientsRowContainer">
<div class="ingredientsInputContainer"><input class="effect-1 ingredientsInput" type="text" name="IngredientName1" placeholder="Ingredient" id="IngredientName1" data-ingID="1"><span class="focus-border"></span></div>
</div>
<input type="hidden" name="Ingredient1ID" id="Ingredient1ID">
</div>
<script>
$(document).ready(function(){
$(document).on('keyup', "[id^=IngredientName]",function () {
var value = $(this).val().toLowerCase();
var searchValue = $(this).val();
var valueLength = value.length;
if(valueLength>1){
var theIngredient = $(this).attr("data-ingID");
$("#Ingredients").removeClass("hidden")
var $results = $('#Ingredients').children().filter(function() {
return $(this).text() === searchValue;
});
//user selected an ingredient from the list
$(".ingredientsValues").click(function(){
console.log("theIngredient: "+theIngredient);//LOGS THE CORRECT NUMBER
var selectedIngredientID = $(this).attr("id");
var selectedIngredientText = $(this).text();
$("#IngredientName"+String(theIngredient)).val(selectedIngredientText);//THIS IS WHAT SETS EVERYTHING WITH AN ID OF IngredientNameX
$("#Ingredient"+String(theIngredient)+"ID").val(selectedIngredientID);
$("#Ingredients").addClass("hidden");
});
$("#Ingredients *").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
} else {
$("#Ingredients").addClass("hidden")
}
});
$("#AddIngredient").click(function(){
var ingredientCounter = $("#ingredientCounter").val();
ingredientCounter++;
$("#ingredientCounter").val(ingredientCounter);
$('#ingredientsContainer').append('\
<div class="ingredientsRowContainer">\
<div class="ingredientsInputContainer"><input class="effect-1 ingredientsInput" type="text" name="IngredientName'+ingredientCounter+'" placeholder="Ingredient" id="IngredientName'+ingredientCounter+'" data-ingID="'+ingredientCounter+'"><span class="focus-border"></span></div>\
</div>\
<input type="hidden" name="Ingredient'+ingredientCounter+'ID" id="Ingredient'+ingredientCounter+'ID">\
');
});
});
</script>
[UPDATE] I realized the problem is happening because the function is running multiple times. I assume this happening because I'm calling a function on keyup of a field whose id starts with IngredientName so when one has a key up event, all existing fields run the function. How do i modify my:
$(document).on('keyup', "[id^=IngredientName]",function () {
to only run on the field with focus?

Why do you just delete an item? Is it possible to delete the selected item?

I have a function to add inputs to a form through "append" and I have another button that removes the inputs entered. For this, with "last-child" I delete the last generated div but from here the button stops working and I can not eliminate other elements previously introduced.
That is, if I only enter a single element it deletes it without problems and yet when I have several elements it only deletes a single time and the delete function stops working.
Do you know what is due?
$( ".add_button" ).click(function() {
var first = document.getElementById('producto');
var options = first.innerHTML + options;
var newElement = '<div class="juan"><div class="form-group"><label>Producto</label><select class="form-control select2 producto" name="producto[]" id="producto" required>' + options + '</select></div><div class="form-group"><label>Cantidad</label><input type="number" name="cantidad[]" class="form-control" value=""/></div><div class="form-group"><label for="nombre">Nº albarán proveedor</label><input type="text" class="form-control" id="albaran_proveedor" name="albaran_proveedor[]" placeholder="El número de albarán del proveedor..."></div><div class="form-group"><label for="precio">Precio</label><input type="number" class="form-control" id="precio" name="precio[]" placeholder="Precio...(Solo números y punto para decimales) "></div><div class="form-group"><label>Fecha recepción:</label><div class="input-group"><div class="input-group-addon"><i class="fa fa-calendar"></i></div><input type="text" id="fecha_recepcion" name="fecha_recepcion[]" class="form-control" data-mask></div><br>Quitar producto</div>';
$( ".field_wrapper" ).append( $(newElement) );
$('.select2').select2();
});
$(".field_wrapper").on('click', '.remove_button', function(e){
e.preventDefault();
$('div.juan:last-child > div.form-group').remove();
});
You're removing the div.form-group within the div.juan, not the div.juan itself. So it continues to be the last child, and subsequent attempts to remove it just don't remove anything (since it's already been removed).
You probably want:
$('div.juan:last-child').remove();
That said, it will only remove the div.juan if it's also the last child in its container (which it probably will be in your case). If you meant the last div.juan, you want either jQuery's :last selector extension, or its last method:
$('div.juan:last').remove();
// or
$('div.juan').last().remove();
In a comment you've said you want to be able to delete any of the inputs, even if it's not the last one. And looking closely at the HTML you have in a string, I see you're putting a .remove_button in each input's structure. That makes it easy to delete the structure associated with that specific button, by using closest to find the div.juan it's in and then removing that:
$(".field_wrapper").on('click', '.remove_button', function(e){
e.preventDefault();
$(this).closest("div.juan").remove(); // <===============
});

Jquery serializeArray break then continue

I'm really new to using serializeArray in jQuery so please forgive me if i'm not asking the correct question.
I have a form which on click add the data to fields within a div ID which works fine, it keeps adding data each time i click which is great, however is it possible to split each form's results? For example, you type in a name and phone number, click add, then in the div ID #results it adds the data then i want the next time you add data, it add's it to the same div ID but seperated by a box
$("#saveAndAdd").click(function(){
addTrip();
var x = $(".cool-test").serializeArray();
$.each(x, function(i, field){
$("#results").append(field.value + " " );
});
});
function addTrip() {
var providerName = $("#providerName").val();
var providerPhone = $("#providerPhone").val();
$("#providerTypeValue").html(providerType);
$("#providerNameValue").html(providerName);
$("#providerPhoneValue").html(providerPhone);
<label class="uikit-text-input__label" for="Input field">Name</label>
<input class="uikit-text-input input-half" name="Input field" id="providerName" type="text" value="" aria-required="true">
<label class="uikit-text-input__label" for="Input field">Phone</label>
<input class="uikit-text-input input-half" name="Input field" id="providerPhone" type="text" value="" aria-required="true">

how to display data from DB on the .append input field

i have a button that creates a new input field and a default field
<div class="container1">
<button class="add_form_field">Add Title</button>
<div class="form-group label-floating">
<input type="text" id="title_name">
</div>
</div>
and this is the jquery that creates a new input field.
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" id="title_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--;
});
and i have ajax call to get the title name from my database based on the user logged in.
$.ajax({
url:'../ajax/getprofile.php',
type:'POST',
data:{userid:user},
dataType:'JSON',
success: function(result){
$('#title_name').val(result.title_name);
}
});
when i use console.log(result) to see what the data is being returned what happen is that only one data is being returned from my ajax request..
i just didn't include the other data on my question earlier cuz those data only return one data.. i only have problem with the title_name
this code works fine for only the default input field.. like the data from my database only shows up on the default input field not on the appended input field..
saying i have a user id of 10001 and my db is look like this
tbl_title
id | name
10001 | sample
10001 | test
what i want to achieve is that when i make a request from ajax and returned the requested value it will display on my input field.and since my id is similar to the tbl_title (id) it should display the two data on the input field. but unfortunately only the 1st data is being displayed only on the default input field what i wanted to make is that if the data is more than 1 it will also display on the appended input field.. but i dont have any idea how this works..
b4 i only got one data that is being returned so i updated my mysql to return all the data that have similar id so now i got array1 and array2 array1 is on the picture and the array2 is similar to the picture but the only difference is their title_name.. so what should i do to display my the two title_name on the array on my input field
The id is the same for each input. So jQuery takes the first catch in this line:
$('#title_name').val(result.title_name);
Thats why only the first input works ...
Try to change it something like this:
$(wrapper).append('<div><input type="text" id="input_' + x + '"/> ...
and:
$('#input' + x ).val(result.title_name);
Probably not exactly right but a push in the right direction ;) The id is the problem.

How to set text box to appear blank after .click function

So I have a simple log in that requires a user to input values from a json file into two different text boxes ,when the user name and (in this case I have used ID as password) matches then an alert appears to say... "welcome"
After the .click function is carried out the users text still remains in the text box, how can I get both text boxes to appear blank after the .click function?
$(document).ready(function() {
//Hide alert when page loads
$("#loginalert").hide();
$("#invalid").hide();
$("#loginbtn").click(function(event){
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
var name = $('#userName2').val();
var valid = false;
for (var i=0; i<jd.user.length; i++) {
if ((jd.user[i].ID == id) && (jd.user[i].name == name)) {
valid=true;
$('#loginalert').html('<img src="' + jd.user[i].imgpath + '"><br><p> Welcome: ' + jd.user[i].name + '</p><button type="button" id="btnhide" class="btn btn-primary btn-md">Hide</button>');
//show the alert after loading the information
$("#loginalert").stop().fadeIn('slow').animate({ opacity: 1.0 }, 3000)
$('#invalid').hide();
$('#btnhide').on('click', function(e){
//console.log('here');
e.preventDefault();
$('#loginalert').hide();
});
}
}
if (!valid) {
$('#invalid').fadeIn('slow');
$('#loginalert').hide();
}
});
}); });
username 1 and #username 2 are the text boxes - is there any way to get user name 2 to display in stars ****** when the user enters the password - this question is not that necessary but if i could also get that working that would be good.
thanks guys hope someone can help :)
is there any way to get user name 2 to display in stars ****** when
the user enters the password
You can use an input box with text property set as password. But that password masking character will be . instead of *. Not exactly sure, whether it will be a different character in some browsers.
<input type="password" id="txtPassword" />
text box to appear blank after .click function
You can set the .val() property of the jQuery objects of two those two textboxes.
$('#userName, #username2').val('');
Use <input type="password"> to show typing as stars.
Clear inputs by setting their value to be empty: $('#userName').val('');
And perhaps consider breaking your code down into a couple smaller functions so it's easier to follow.
document.getElementById("#myTextbox").value="";
This should get your textbox and set the value of it to "", which is blank.
Edit: JSFiddle
Another Method:
You can also add the script directly inside the button without using/creating a function.
<input id="inputId" type="name" />
<button onclick="document.querySelector('#inputId').value='';"> Clear </button>
Using querySelector:
<input id="inputId" type="name" />
<button onclick="click()"> Clear </button>
<script>
function click() {
document.querySelector('#inputId').value="";
}
</script>

Categories