change attrib name with array - javascript

I have a form with this input:
<input id="cant_user" type="text" name="cant_user" value="1" onblur="addInputs()">
#userData is cloned when add a input value greater than 1 and I want to change input name from user_age to age[n]
<div id="userData">
<div class="panel-body" id="generated[0]">
<div class="form-group">
<label class="col-md-4 control-label">Age User [n]</label>
<div class="col-md-6">
<input type="number" class="form-control" name="user_age[]" value="0" required>
</div>
</div>
</div>
Javascript:
function addInputs() {
var cantUsers = document.getElementById("cant_user").value;
var countGenerated = $('[id^=generated]').length;
if (countGenerated > 0) {
$('[id^=generated]').not(':first').remove();
}
if (cantUsers != 1) {
if (cantUsers > 1 && cantUsers < 10) {
for (var i = 1; i < cantUsers; i++) {
jQuery("#userData").append(jQuery("#userData").children().first().clone());
jQuery("#userData").children().last().attr("id", "generated[" + i + "]");
for (var n = 0; n <= i; m++) {
var u = document.getElementsByName("user_age[]");
$(u).removeAttr("name").attr({
id: "generatedAge[" + n + "]",
name: "age[" + n + "]"
});
}
};
}
};
}
How can I make every label and input name shows a value from array like:
<label>Age User 1<label>
<input name="age[0]">
<label>Age User 2<label>
<input name="age[1]">

I changed some code, it maybe can help if i understand your idea correct
for ( var i = 1; i < cantUsers; i++) {
var userData = jQuery("#userData");
var childOfUserData = userData.children();
userData.append( childOfUserData.first().clone() );
childOfUserData = userData.children(); //because we just appen new data
childOfUserData.last().attr("id","generated[" + i + "]");
for ( var n = 0; n <= i; n++ ) {
var child = childOfUserData.get(i);
var userAge = $("input", $(child));//because you only have one input
userAge.attr("name","age[" + n + "]").attr("id","generatedAge[" + n + "]");
}

<input name="age[0]">
In the above code name attribute value acts as text not an array value.
To get an array value in the attribute, you need to change the JavaScript code
$("#userData").children().last().attr("id", generated[i]);
$(u).removeAttr("name").attr({
id: generatedAge[n],
name: age[n]
});
Now, if you check the attribute value, you will receive data into it.
Hope this will help you.

Related

How to retain <select> tag values when changing the number of displayed elements

I use a first select dropdown to choose how many age selection elements to generate. For example:
would cause 4 elements to be generated. Say I then choose some values.
If I then change the number of selected elements, I want to keep the values in any existing elements. For example, if I change the number of elements to 6, I want 6 elements with the first 4 keeping their selected values.
And I would like the new selects to appear horizontally
<label class="col-sm-1 control-label">Kids:</label>
<%--
<input type="text" class="form-control" name="Minors" value="<%=(package!= null && package.request!=null)? package.request.Minors :0 %>"/>
</div>--%>
<div class="col-sm-2">
<select class="chosen-select" style="width: 350px;" name="Minors" id="cbo-select">
<%for (int i = 0; i <= maxKids; i++)
{ %>
<option value="<%=i %>" name="Minors"><%=i%></option>
Minors = i;
<% } %>
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-sm-12" id="area">
</div>
**//////////// javascript
function selectedElementChanged() {
<%var ageKids = (int) ViewData["ageKids"];%>
var ageKids = '<%=ageKids%>';
//$(".chosen-select").area.empty();
//$(".chosen-select").area.append('<select style="width: 20%;" name="KidAges" id="auto-select" class="chosen-select">' +
// '</select>');
var selectedValue = $("#cbo-select").val();
$("#area").empty();
if (parseInt(selectedValue)) {
for (var i = 0; i < selectedValue; i++) {
$("#area")
.append('<select class="form-control chosen-select" style="width: 20%;" name="KidAges" id="auto-select">' +
'</select>');
}
var i = 0;
if (i >= 0) {
$("select[name='KidAges']")
.append('<option value ="0" name = "KidAges[0]" > < 1 </option></br>');
}
for (i = 1; i <= ageKids; i++) {
$("select[name='KidAges']").append('<option value=' + i + ' name="KidAges[' + i + ']" > ' + i + '</option>');
}
}
}
To maintain the existing dropdown values you must either store/restore values when repopulating the list or incrementally add/remove controls. The latter seems more efficient.
var desiredCount = $("#cbo-select").val();
desiredCount = parseInt(desiredCount);
var area = $("#area");
var controls = area.children();
if (desiredCount) {
var currentCount = controls.length;
if (desiredCount < currentCount) {
controls.slice(desiredCount).remove();
} else {
for (var ii = currentCount; ii < desiredCount; ++ii) {
area.append('<select class="form-control chosen-select" style="width: 20%;" name="KidAges" id="auto-select">' +
'</select>');
}
}
} else {
area.empty();
}

Javascript: could not get the value inside an array using for in loop

I want to display the form with user filled values inside the form to admin. I have displayed all type of values to the respective type of input/select/textarea tags (type: text,email, tel,number... etc) except input type=checkbox.
I am getting problem while fetching the values from array that contain values of group of checkboxes. My code is
var value = data[i][key];
var result = $.isArray(value);
if (result == true) {
var string = key;
var splitstring = string.split("#");
for (var value1 in value) {
console.log(value1);
$("input[type='checkbox'][groupid='" + splitstring[0] + "'][value='" + value1 + "']").attr('checked', true); //cb
}
}
my array(named value) contain values like
[cricket, football, tennis]
would like to make the checkbox property checked that match the condition. but when i console the values fetched one by one it shows me output as
0
1
2
i am not getting what is it???
my html code
<table class="form-group">
<tbody id="tedit">
<tr>
<td>
<div class="checkbox">
<input id="dddddddd#1428735544884535#check_box1" class="form-control" name="14287355448849394#dddddddd[]" groupid="14287355448849394" grid-name="dddddddd" value="Check Box1" type="checkbox" /><label class="jedit"><span class="mouseover">Check Box1</span></label>
</div>
</td>
</tr>
<tr>
<td>
<div class="checkbox">
<input id="dddddddd#14287355448843282#check_box2" class="form-control" groupid="14287355448849394" grid-name="dddddddd" name="14287355448849394#dddddddd[]" value="Check Box2" type="checkbox" /> <label class="jedit"> <span class="mouseover">Check Box2</span></label>
</div>
</td>
</tr>
<tr>
<td>
<div class="checkbox">
<input id="dddddddd#14287355448853367#check_box3" class="form-control" groupid="14287355448849394" grid-name="dddddddd" name="14287355448849394#dddddddd[]" value="Check Box3" type="checkbox" /> <label class="jedit"> <span class="mouseover">Check Box3</span></label>
</div>
</td>
</tr>
</tbody>
</table>
my javascript code is
$.post('<?php echo BASE_URL . 'php/processing/formDashboard/formEntryShowOneByOne.php' ?>', {id: $('#formMetaDataId').val()}, function(data) {
console.log(data);
for (var i = 0, len = data.length; i < len; i++) {
for (var key in data[i]) {
$("input[type='text'][name='" + key + "']").val(data[i][key]); //input tags
$("input[type='text'][name='" + key + "']").prop('disabled', 'true'); //input tags
//........likewise for other type of elements.......///
//.....................for checkbox........................//
var value = data[i][key];
var result = $.isArray(value);
if (result == true) {
var string = key;
var splitstring = string.split("#");
for (var value1 in value) {
console.log(value1);
$("input[type='checkbox'][groupid='" + splitstring[0] + "'][value='" + value1 + "']").attr('checked', true); //cb
}
}
}
}
});
this is simple. The 'cricket' string is retrievable like this:
value[value1]
value1 is just the iterator, in your example 0,1,2
This is your working code:
var value = data[i][key];
var result = $.isArray(value);
if (result == true) {
var string = key;
var splitstring = string.split("#");
for (var value1 in value) {
console.log(value[value1]);
$("input[type='checkbox'][groupid='" + splitstring[0] + "'][value='" + value[value1] + "']").attr('checked', true); //cb
}
}
You should use forEach function
value.forEach(function(val)
{
console.log(val);
//do your thing here
});
That's just how the for ... in loop works for arrays:
var a = ['a','b','c'];
for (var i in a) {
alert(i); // alerts 0,1,2
alert(a[i]); // alerts a,b,c
}
Thus, you just need to index your array with the loop variable:
var value = data[i][key];
var result = $.isArray(value);
if (result == true) {
var string = key;
var splitstring = string.split("#");
for (var valueIndex in value) {
console.log(value[valueIndex]);
$("input[type='checkbox'][groupid='" + splitstring[0] + "'][value='" + value[valueIndex] + "']").attr('checked', true); //cb
}
}

Input number's value to append div's

Fiddle - http://liveweave.com/enRy3c
Here's what I'm trying to do.
Say my input number is 5. I want to dynamically append 5 divs to the class .enfants. However I haven't figured out how to do that. I been searching and searching and I haven't came across anything.
jQuery/JavaScript:
var counter = 1;
// Value number = .enfants children
$(".ajouter-enfants").on('keyup change', function() {
var yourChildren = "<div>" + counter++ + "</div>";
var CallAppend = function() {
$(".enfants").append( yourChildren );
};
// If 0 or empty clear container
if ( $.inArray($(this).val(), ["0", "", " "]) > -1 ) {
$(".enfants").html("");
// If only add/have 1 div in container
} else if ($(this).val() === "1") {
$(".enfants").html("").append( yourChildren );
// If > 0 add as many divs as value says
} else {
$(".enfants").html("");
CallAppend();
}
});
HTML:
<div class="contenu" align="center">
<div>
Value number = .enfants children
</div>
<input type="number" min="0" class="ajouter-enfants" value="0" />
<div class="enfants">
</div>
</div>
How about a simple loop? If you just want to append, try something like this:
$(".ajouter-enfants").on('change', function() {
var numDivs = $(this).val();
var i;
for (i = 1; i <= numDivs; i += 1) {
$('.enfants').append('<div>' + i + '</div>');
}
});
EDIT:
If you want to replace instead of append the newly-created <div>'s, try something like:
$(".ajouter-enfants").on('keyup change', function() {
var content = '';
var numDivs = $(this).val();
var i;
for (i = 1; i <= numDivs; i += 1) {
content += '<div>' + i + '</div>';
}
$('.enfants').html(content);
});
This will replace the entire content of any elements using the class ajouter-enfants with the number of <div>'s specified in the input box.
Try this:
$(".ajouter-enfants").on('keyup change', function() {
var num = +$.trim($(this).val()), target = $(".enfants"), i = 0, s = '';
target.empty();
if (!isNaN(num) && num > 0) {
for (; i < num; i++) {
s += '<div>' + (i + 1) + '</div>';
}
target.html(s);
}
});
How would you get it to only append the value amount? It appends more when the value is (2 becomes 3, 3 becomes 6, 4 becomes 10 and repeats even when I'm decreasing the numeric value) –
#Michael Schwartz
Here is another code example that might be helpfull.
$(".ajouter-enfants").on('change', function() {
var numDivs = $(this).val();
var i;
var html ='';
for (i = 1; i <= numDivs; i += 1) {
html += '<div>' + i + '</div>';
}
$('.enfants').empty().append(html);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="contenu" align="center">
<div>
Value number = .enfants children
</div>
<input type="number" min="0" class="ajouter-enfants" value="0" />
<div class="enfants">
</div>
</div>

Using for loop to generate text boxes

I want to be able to enter a number into a text box and then on a button click generate that number of text boxes in another div tag and automatically assign the id
Something like this but not sure how to generate the text boxes and assign automatically assign the id
function textBox(selections) {
for (i=0; i < selections +1; i++) {
document.getElementById('divSelections').innerHTML = ("<form><input type="text" id="1" name=""><br></form>");
}
}
Try this one:
function textBox(selections){
selections = selections*1; // Convert to int
if( selections !== selections ) throw 'Invalid argument'; // Check NaN
var container = document.getElementById('divSelections'); //Cache container.
for(var i = 0; i <= selections; i++){
var tb = document.createElement('input');
tb.type = 'text';
tb.id = 'textBox_' + i; // Set id based on "i" value
container.appendChild(tb);
}
}
A simple approach, which allows for a number to be passed or for an input element to be used:
function appendInputs(num){
var target = document.getElementById('divSelections'),
form = document.createElement('form'),
input = document.createElement('input'),
tmp;
num = typeof num == 'undefined' ? parseInt(document.getElementById('number').value, 10) : num;
for (var i = 0; i < num; i++){
tmp = input.cloneNode();
tmp.id = 'input_' + (i+1);
tmp.name = '';
tmp.type = 'text';
tmp.placeholder = tmp.id;
form.appendChild(tmp);
}
target.appendChild(form);
}
Called by:
document.getElementById('create').addEventListener('click', function(e){
e.preventDefault();
appendInputs(); // no number passed in
});
JS Fiddle demo.
Called by:
document.getElementById('create').addEventListener('click', function(e){
e.preventDefault();
appendInputs(12);
});
JS Fiddle demo.
The above JavaScript is based on the following HTML:
<label>How many inputs to create:
<input id="number" type="number" value="1" min="0" step="1" max="100" />
</label>
<button id="create">Create inputs</button>
<div id="divSelections"></div>
See below code sample :
<asp:TextBox runat="server" ID="textNumber"></asp:TextBox>
<input type="button" value="Generate" onclick="textBox();" />
<div id="divSelections">
</div>
<script type="text/javascript">
function textBox() {
var number = parseInt(document.getElementById('<%=textNumber.ClientID%>').value);
for (var i = 0; i < number; i++) {
var existingSelection = document.getElementById('divSelections').innerHTML;
document.getElementById('divSelections').innerHTML = existingSelection + '<input type="text" id="text' + i + '" name=""><br>';
}
}
</script>
Note: Above code will generate the N number of textboxes based on the number provided in textbox.
It's not recommended to user innerHTML in a loop :
Use instead :
function textBox(selections) {
var html = '';
for (i=0; i < selections +1; i++) {
html += '<form><input type="text" id="'+i+'" name=""><br></form>';
}
document.getElementById('divSelections').innerHTML = html;
}
And be carefull with single and double quotes when you use strings
You have to change some code snippets while generating texboxes, Learn use of + concatenate operator, Check code below
function textBox(selections) {
for (var i=1; i <= selections; i++) {
document.getElementById('divSelections').innerHTML += '<input type="text" id="MytxBox' + i + '" name=""><br/>';
}
}
textBox(4); //Call function
JS Fiddle
Some points to taken care of:
1) In for loop declare i with var i
2) your selection + 1 isn't good practice at all, you can always deal with <= and < according to loop's staring variable value
3) += is to append your new HTML to existing HTML.
ID should be generate manually.
var inputName = 'divSelections_' + 'text';
for (i=0; i < selections +1; i++) {
document.getElementById('divSelections').innerHTML = ("<input type='text' id= " + (inputName+i) + " name=><br>");
}
edit : code formated
Instead of using innerHTML, I would suggest you to have the below structure
HTML:
<input type="text" id="id1" />
<button id="but" onclick="addTextBox(this)">click</button>
<div id="divsection"></div>
JS:
function addTextBox(ops) {
var no = document.getElementById('id1').value;
for (var i = 0; i < Number(no); i++) {
var text = document.createElement('input'); //create input tag
text.type = "text"; //mention the type of input
text.id = "input" + i; //add id to that tag
document.getElementById('divsection').appendChild(text); //append it
}
}
JSFiddle

Adding values of variable form fields

I have fields of type='number' in my form. These are dynamically generated by a database.
<input name="each[29]" id="form_29" placeholder="0.000" type="number" class="input" data-original-title="" title=""/>
<input name="each[30]" id="form_30" placeholder="0.000" type="number" class="input" data-original-title="" title=""/>
<input name="each[31]" id="form_31" placeholder="0.000" type="number" class="input" data-original-title="" title=""/>
The attribute name="each[xx]" is an ID of a category in the database. Here is the submit button:
<input type="submit" value="Enregistrer" onClick="return calculAuto('form_29,form_30,form_31')">
JavaScript
function calculAuto(v) {
var mystr = v;
var myarr = mystr.split(",");
var cat = '';
for (i = 0; i < myarr.length; i++) {
if ($('#' + myarr[i]).val() !== '') {
cat += $('#' + myarr[i]).val();
}
}
}
I want to calculate the sum of all the fields passed in the argument of the function.
you are doing:
var cat = ''; //string
so with cat += $('#' + myarr[i]).val();
its appending the values, do:
function calculAuto(v) {
var mystr = v;
var myarr = mystr.split(",");
var cat = 0;
for (i = 0; i < myarr.length; i++) {
if ($('#' + myarr[i]).val() !== '') {
cat += $('#' + myarr[i]).val();
}
}
console.log(cat);
return false;
}

Categories

Resources