cloning form fields are populated with value from previous fields - javascript

This function clones a set of text input fields inside a div, when the user clicks the add button:
function addRows(label, maxRows, minRows) {
$('.add-' + label).live('click', function() {
if ($("." + label + "-group").length < maxRows) {
$('#' + label + '-template')
.clone()
.removeAttr('id')
.insertAfter($(this).closest('.' + label + '-group'))
.find('.minus')
.show();
}
});
}
When the user fills in a field, then clicks the add button, it displays a new row of fields, but they are populated with the values the user entered in the previous row.
What is the best way to resolve this problem? I am thinking I could empty all input text fields for that instance of rows.
I just don't know how I'll clear the appropriate rows.
The field names are: first_name[], last_name[], phone[]
So when it clones those three fields to a new row, they will have the same name as the fields above.
When the user submits, I'll loop through each value in first_name[], last_name[], phone[]

try this, call val() after other methods like appendTo or insertAfter
$('#' + label + '-template').clone().val("")...
http://jsfiddle.net/pnQhh/

Related

How to update the value of a specific input field instead of the td first child?

I have added this code to my function in javascript and am successfully updating the tables first TD with the new values of the rows after the user clicks a button to push the row up or down, the issue is I am using a input field in this td and the input is removed and the value is now just a simple text/numeric character.
How can I change this snippet to update the input field within the first td as opposed to replacing the td content with the new values outside a input field.
Array.prototype.forEach.call(document.querySelectorAll('td:first-child'),
function (elem, idx) { elem.innerHTML = idx + 1; }
)
Ok so with Archers help I have updated the code below and now have the functionality I am wanting. Thanks for all who participated in schooling this newbie ;)
Array.prototype.forEach.call(document.querySelectorAll('td:first-child input[name^=sort]'), function (elem, idx) {
elem.value = idx + 1;
By changing
'td:first-child'
to
'td:first-child input[name^=sort]'
I was able to reference the specific input field as opposed to all input fields in the first td column and no longer am replacing the input fields with plain text.
You can change the selector to target the input instead of the cell that it's in...
Array.prototype.forEach.call(document.querySelectorAll('td:first-child input'),
function (elem, idx) {
elem.value = idx + 1;
});
Or you can use your code and change its body like this:
Array.prototype.forEach.call(document.querySelectorAll('td:first-child'), function(elem, idx){
(elem.querySelector("input")||{}).value=idx+1; //use this line instead of your forEach body
});
Try it online!

For through html elements and appending only appends to last element

I have a text input and on focusout, I have couple of select elements which I want to fill with the text field's value.
And I have bunch of select tags with 'NameSelect' class
$('.textField').focusout(function() {
var name = $(this).val();
var NameOption = $('<option>', { value: name, text: name, attrid: '1'});
var selects = $('#mainForm').find('.NameSelect');
$(selects).each(function(i, obj) {
console.log($(obj)); // it seems to get the right select
$(obj).append(NameOption);
})
}
However, when I do that, even though the selects get all the right elements and for loop for the right count, it only appends the option input to the latest object, not all of them.
What am I missing here?
The issue is because NameOption holds a reference to the option, hence if you append() it multiple times it will move between each parent element.
To fix this you can either clone() the element when you append it:
selects.append(NameOption.clone());
Or you could just provide append() with a string to create a new element each time it's called:
$('.textField').focusout(function() {
var name = $(this).val();
$('#mainForm').find('.NameSelect').append('<option value="' + name + '" attrid="1">' + name + '</option>');
})
});
Note that in both cases the each() is not required.

ASP.Net Programming Validation ,Combo box inside repeater

I have a ASP website in which I have a repeater, which has a combo box and textbox.I need to have a text box value converted to uppercase when i select
particular value from combo box, but not for all values from combo box .I have tried onChange event and onKeypress Event also in javascript,but could not able
to breakthrough.
function changecase(combobOxClientId,textboxClientId)
{
var combo=$find(combobOxClientId);
if(combo.get_value()=='Textvalue')
{
var textbox=$find(textboxClientId).value;
some code here........ `}`
You need to it like this.
function changecase(combobOxClientId, textboxClientId) {
if ($("#" + combobOxClientId).val() == 'Textvalue') {
var txtval = $("#" + textboxClientId).val();
$("#" + textboxClientId).val(txtval.toUpperCase());
}
}
Assumption : combobOxClientId, textboxClientId are actual ID of elements existing in page.

add and remove a certain value from a text field

each checkbox that i check, i fill the input with it's id
now, how can i retrieve this id that i put inside the input if the user uncheck the checkbox?
exp:
estate SC,SP was checked;
input recieve SC,SP value in this format = SC,SP
but the user uncheck the checkbox with SC value, then SC should be removed from the input.
this is what i'm doing to fill the input with the checkboxes.
var separador = ",";
var estadosS = "";
$(".checkboxEstados").live("click", function(){
if($(this).is(":checked")){
estadosS += (estadosS == "") ? "" : separador;
estadosS += $(this).attr("id");
$("#holdEstados").val(estadosS);
}else{
// now i'm just cleaning all the input,
// but i need to clean only the checkbox that was unchecked
$("#holdEstados").val("");
}
});
dont know if i was clear, any question, be my guest.
Thanks.
An easy way to solve this is to avoid parsing and removing parts of the data. Instead of trying to remove 'SC', instead regenerate the entire contents of the text field each time any checkbox is selected.
When a checkbox click event is detected, deleted the contents of the text input field, scan all of the selected checkboxes, and include their IDs in the text input field.
You're logic can be greatly simplified. Simply grab each checkbox that is checked when the click event fires:
$(".checkboxEstados").live("click", function() {
var aryIds = new Array();
$(".checkboxEstados:checked").each(function() {
aryIds.push($(this).attr("id"));
});
$("#holdEstados").val(aryIds.toString());
});
Here's a working fiddle.
I would store the value in an array and add and remove values from it and then write the array to the output instead of trying to parse the text each time:
var estadosS = [];
$(".checkboxEstados").live("click", function(){
var index;
if($(this).is(":checked")){
// append the id to the list
estadosS.push($(this).attr("id"));
}else{
index = estadosS.indexOf($(this).attr("id"));
if(index > -1) {
estadosS.splice(index, 1);
}
}
$("#holdEstados").val(estadosS.join(separador));
});
If all you are aiming to do is get a list of the checked values from all the check boxes, you could do:
$('.checkboxEstados:checked').each(function(){
alert($(this).val());
});
And that should return all the check box items that have been checked. Then you don't have to worry about adding and removing data from a text box. I'm just alerting the value, you would want to store them into an object or something more useful.

How to add data to multiple input fields and save it on submit?

I am trying add some data to each add input field.
Example if the a "info" input field is added a input field.
If:
The red div and no data gets added the data should be null,
The blue div and a "p" gets added to the added info input on form submit.
The blue div and a "V" is added to the added input field.
How do I add this data to the added inputs and add the data to theirs value on submit?
My HTML and jQuery: http://jsfiddle.net/z5qeX/2/
I have an example of this with only 1 input field:
$('.redDiv').click(function() {
$('#webhost_navn').data('myData', null);
});
$('.blueDiv').click(function() {
$('#webhost_navn').data('myData', 'p');
});
$('.blackDiv').click(function() {
$('#webhost_navn').data('myData', 'V');
});
// And the form submit button with the id of smt
$('#smt').click(function() {
var myData = $('#webhost_navn').data('myData'),
val = $('#webhost_navn').val();
if (myData) {
$('#webhost_navn').val(myData + val);
}
});
How do I create this function for each added input and save all the data on submit?
When one of the red, blue or black is clicked:
1. Select the added input field
2. Create a data variable and save p, V or nothing depending on what div that where clicked.
3 .On submit add all these variable to values of the correct input fields
Its hard to be entirely sure what your asking but I think what you are looking for is jQuery's live function
$('.redDiv').live('click', function() {$('#webhost_navn').data('myData', null);});
The live function binds listeners to all newly created controls.
Something like
mydata = { "webhost_navn": {red:null, blue:"p", black:"V"}, "....": { ... , ... , ...}}
$('.blackDiv,.blueDiv,.redDiv').live("click", function() {
var field = $("#"+this.id.replace(this.className,""));
if (field) field.val(mydata[field.prop("name")][this.className.replace("Div","")];
});
.
.
.
'id' : element.prop('id') + 'info',
$(this).parent().append(element).append('<div class="redDiv" id="'+element.prop('id')+'redDiv" style="background:red;width:20px;height:20px;"></div><div class="blueDiv" id="'+element.prop('id')+'blueDiv" style="background:blue;width:20px;height:20px;"> </div><div class="blackDiv" id="'+element.prop('id')+'blackDiv"style="background:black;width:20px;height:20px;"> </div>');
})

Categories