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.
Related
I started to do dropdown list instead select bcz it is not possible to stylize but I did not think to future and now I found that if I want to save data from form to db I need to get ids via $_POST instead of names.
For ex. I have dropdown list with status of product:
New
Old
Handmade
If I want to save chosen sattus for chosen product it is better for me to get ID of status option. Bcz my table is like this:
item_id | option_value
1 | 1
If I send name as "old" via $_POST, I need to get its ID from another table before insert it.
I created dropdown list like this:
/* SELECT REPLACED BY DIV JS */
var select = $('.add-item__select').hide(); // Hide original select options
// Replace each select by div
select.each(function() {
var selectVal = $(this).find('.add-item__select-main').text(),
name = $(this).attr('name');
newDropdownDiv = $('<input class="add-item__input-select" name="' + name + '" placeholder="' + selectVal + '" readonly required><i class="arrow down"></i></input>')
.insertAfter($(this))
.css({paddingLeft: '0.3em', cursor: 'pointer'});
});
Each SELECT has addaed INPUT after it.
If I want to show shosen vale from dropdown list I need to show it in this way:
$('.add-item__input-select').val("text copied from list");
After this if I add ID of option to input in this way:
$('.add-item__input-select').attr("value", optionID);
Then If I want to serialize all fields values from form and this is point,
$('.add-item__form').serializeArray()
I get two results for status:
name: "status", value: "text copied from list"
and
name: "status", value: optionID
But I need just optionID.
I have everything optimized for this structure, so I would like to ask you if there is some easy way how to fix it or I need to modify structure.
I am thinking to remove INPUT and just change SELECT opacity to 0 instead of display none and use SELECT for form data serialize. But then I will need to replace all INPUTs by some DIV which will hold text of chosen option and also change everything else connected with it. For ex, if user clicked on INPUT the label was showed above it.
Thanks for advices
I found one solution but I have problem that it is working just if user will not refresh page. In DOM is everything the same after refresh but serializeArray() get just input text value and not value="ID" after page refresh.
I just remove these values which I do not want from FormData.
// Send formData to upload.php
$('.add-item__form').on('submit', function() {
event.preventDefault();
event.stopPropagation();
if ( checkFieldsIfNotEmpty() == true ) {
var formDataFields = $('.add-item__form').serializeArray(), // Get all data from form except of photos
count = Object.keys(data).length; // count fields of object
// Fill formData object by data from form
$.each(formDataFields, function(index, value) {
if ( value.name === 'category' && !$.isNumeric(value.value) || value.name === 'subcategory' && !$.isNumeric(value.value) ) {
// do nothing
} else if ( (value.name.indexOf('filter') >= 0) && !$.isNumeric(value.value) ) {
// do nothing
}
else {
formData.append(value.name, value.value); // add name and value to POST data
}
});
// foreach - fill formData with photos from form
$.each(data, function(index, value) {
formData.append('files[]', value);
});
uploadData(formData); // send data via ajax to upload.php
}
});
Can you advice me what can be problem?
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?
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.
I'm trying to leverage some form validation to do something it really wasn't designed to do. I have a table in my form and each row has a checkbox. I want to ensure that at least one of a specific type of checkbox is selected, if not I want to show a validation error. I am doing something similar with a text box with logic that looks like this:
function ValidateName() {
var $nameTextbox = $("#Name");
var $originalName = $("#OriginalName");
var nameText = $nameTextbox.val().toLowerCase();
var originalNameText = $originalName.val().toLowerCase();
//check to see if original name and group name match
if (nameText != originalNameText) {
//This isn't the same name we started with
if (uniqueNames.indexOf(nameText) > -1) {
//name isn't unique, throw validation error
var currentForm = $nameTextbox.closest("form");
//trigger validation
var errorArray = {};
errorArray["Name"] = 'Name must be unique';
currentForm.validate().showErrors(errorArray);
}
}
}
I've written something similar for the table and it works as long as I point the errorArray's index to the id of an input. However, I want to display the error somewhere more generic like the validation summary at the top of the form. How do I set up the error array to show on the form or the validation summary instead of a specific input? Is that even possible?
One way you could do this is you set a hidden input that is false when none are check and true if 1 or more are checked. You then listen to all the checkboxes by giving them all a class. I have an example shown below
http://jsfiddle.net/95acw2m9/
Html
<input type="hidden" id="IsCheckValue" name="IsCheckedValue" value="false"/>
<input type="checkbox" class="someCheckbox"/>
<input type="checkbox" class="someCheckbox"/>
<input type="checkbox" class="someCheckbox"/>
Jquery
$(document).ready(function(){
$(".someCheckbox").change(function(){
if($(".someCheckbox:checked ").length > 0){
$("#IsCheckValue").val("True")
}else{
$("#IsCheckValue").val("False")
}
})
})
Then pass that bool value in your model. In your controller method you can check the value of the bool. If the bool is false set the model to false like this
ModelState.AddModelError("Checkbox", "Must select one checkbox");
You can use the #Html.ValidationSummary() to display the error in your view.
in my form, the user can click a button to create input fields. Inside each of the created input fields, they can click the "add media links" button to create another input field underneath. They can add as many media links as they please or none at all. The first set of input fields are also sortable. I have the user interface working, I'm just wondering how to go about processing it.
right now, I am basically grabbing all of the values entered from the first set of input fields (aka "thestepvalues" in the code) and then grabbing all of the values entered from the second set of input values (aka "links" in the code) and then URL enconding it and serializing it to send to the my process.php file. The code is below:
$("#new_post").submit(function(e){
e.preventDefault();
//enter each of the values for 'the step' input field into an array
var thestepvalues = $("input[name='thestep\\[\\]']")
.map(function(){return $(this).val();}).get();
//enter each of the values for each 'links' input field into an array
var linkvalues = $("input[name='link\\[\\]']")
.map(function(){return $(this).val();}).get();
//this will basically convert everything entered into the steps as well as the links fields
//into URL appropriate strings to pass on to the process.php file
var i, string="";
for(i=0;i<thestepvalues.length; i++){
string += "thesteps[]=" + encodeURI(thestepvalues[i]) + "&";
}
for(i=0;i<linkvalues.length; i++){
string += "links[]=" + encodeURI(linkvalues[i]) + "&";
}
//send the data from the string (both kinds of input fields) as well as any
//other input fields (that aren't dynamic) from the form
$.post("process.php", string + $("#new_post").serialize(),
function(data){
if(data.email_check == 'invalid'){
$("#message_post").html("<div class='errorMessage'>Sorry " + data.name + ", " + data.email + " is NOT a valid e-mail address. Try again.</div>");
} else {
$("#message_post").html("<div class='successMessage'>" + data.email + " is a valid e-mail address. Thank you, " + data.name + ".</div>");
}
}, "json");
});
For a sample of data entered into the form, how do I go about indicating which link belongs to the parent input field? Baring in mind the parent input fields are sortable jquery ui elements.
here's a sample set of data entered, as you can tell I have no way of knowing which input field the child links belong to:
[thesteps] => Array
(
[0] => This is really the second input field, but dragged up to the first position.
[1] => This is the second input field, but used to be in the first position.
[2] => this is the third input field
)
[links] => Array
(
[0] => this is the first (child) link for the first position.
[1] => this is actually the (child) link for the third field!
)
Any help would be greatly appreciated, thanks in advance
-- 24x7
You could use HTML5 custom data attributes, setting the value of each linked set to be the same number.
For example:
<input id="1" data-newinput-id="1" />
<input id="2" data-newinput-id="1" />
<input id="3" data-newinput-id="2" />
<input id="4" data-newinput-id="2" />
Even if the inputs are re-arranged, you can match them up by getting the attribute values in jQuery like so:
var id = $(this).attr("data-newinput-id"); // 1