I have form elements in multiple rows. What is the best way to name these elements so that i can read all the values in the form and generate a JSON with the values? Since HTML does not support Arrays what is the best alternative?
Each row has 2 text elements and 1 Select element. These rows are generated dynamically.
Edit: Basically i want an easy way to convert my data into JSON so that i can pass it to a service.
Each of my row looks like this
<tr><td><input type="text"></input></td>
<td><select><option>Exact</option><option>Regex</option><option>Action</option></select></td>
<td><input type="text"></input></td></tr>
<tr><td><input type="text"></input></td>
<td><select><option>Exact</option><option>Regex</option><option>Action</option></select></td>
<td><input type="text"></input></td></tr> .....
I think I understand. You can just change your HTML:
<div class="form"> // I prefer getting a namespaced super element
<div class="row">
<input name="name[0][yo]"/>
// Other elements
</div>
<div class="row">
<input name="name[1][yo]"/>
// other elements
</div>
</div>
Then in JQuery:
$.post('to_my_page', $('.form input, .form select, .form textarea').serialize(), function(data){
// Done
}, 'json');
That should allow you to post an array of input rows to another page.
This is of course an extremely simple and basic example.
To extract all the data from the form you can simply use jQuery's serializeArray() method just like this:
$('form').serializeArray();
jsFiddle example
A good way to accomplish that is put an id on the values, for example is you are using just a text wrap it in a span then when you need to make the JSON iterate over rows and get the data from it, i.e.:
var elements = []
$('#formId tr').each(function (i, e){
elements.push({
ElementTd1: $('#td1').val()
});
});
Related
The situation:
<body>
<div id="1">
<input type="text" name="email_1"/>
<input type="text" name="email_2"/>
</div>
<div id="2">
<input type="text" name="email_3"/>
<input type="text" name="email_4"/>
</div>
<!--and so on...-->
</body>
And I need to validate inputs inside these 2 inputs inside every div to be equal(only inside div). Maybe the main problem is that all divs are dynamically generated, and we don't know exactly their quantity to provide knockout support. How to do that? What is the most elegant solution?
Update 1
I've tried:
1. To make some binding using knockout model. But my solution for this
was to create some observable property to check inputs values. This
is bad way I guess.
2. To use jquery for this. Tried to validate fields via validate class for
inputs(http://jqueryvalidation.org/jQuery.validator.addClassRules/)
Update 2
My solution was something like that:
<div id="1">
<input type="text" name="email_1"/>
<input type="text" name="email_2"/>
<label data-bind="visible: checkEmailsEquality(email_1,email_2)">Emails must be equal</label>
</div>
But this solution is not ok, because this binding works only once - at page loading, what isn't good. I need to bind this check to text update in these inputs, and I don't know how.
Update 3
My suggestion is to deal with it in this way:
Make on the first email input this binding http://knockoutjs.com/documentation/textinput-binding.html
Bind with similar function in knockout's model as wrote Wayne Ellery.
If values aren't equal make error label visible.
The main condition is to pass apropriate inputs ids to function, and I guess this will work.
The simplest way to do this is to just use a computed which will compare the two emails.
Below in ViewModel I'm using the jQuery $.map method to map all items to an array of Item objects.
var ViewModel = function (model) {
var self = this;
self.items = $.map(model.items, function(item) { return new Item(item) });
};
Here I'm using a computed method in Item to compare email1 and email2.
var Item = function (item) {
var self = this;
self.email1 = ko.observable(item.email1);
self.email2 = ko.observable(item.email2);
self.areEmailsSame = ko.computed(function() {
return self.email1() === self.email2();
});
};
http://jsfiddle.net/pxar0587/1/
I've found maybe the most elegant solution, it's about using equalTo attribute, e.g.:
<div id="1">
<input type="text" id="1" name="email_1" equalTo="#2"/>
<input type="text" id="2" name="email_2" equalTo="#1"/>
</div>
Hope this help somebody.
I'm a beginner in js and jquery library. I'd like to get an array of input fields with a particular name, and validate input. Each of my input fields have a name like NS[0], NS[1] etc. The total number of fields will have to be determined by the code, since the fields are generated by javascript.
I know that I can have jquery address the individual object like this:
$("input[name=NS\\[0\\]]").val() for <input type="text" name="NS[0]">.
However, how can I get an array of all these similiar elements, from NS[0] to NS[x] where x has to be determined based on how many fields have been generated? I already have other fields with different name patterns sharing the same css class, so using class is not an option. These boxes are in a particular div area, but in the same area are other input fields, so choosing all input boxes of the same area selects them as well.
In other words, how do I use jquery to check the name of each input field, after getting the entire array of input fields, to check each individual name?
Since I have input fields of various names in the area determined by the table id CNTR1, I would select them with $('#CNTR1 input'). I can also select individual fields by using $("input[name=]"). However, what I want to do, is to select everything under $('#CNTR1 input'), and then run a loop on their names, checking whether the names match a predetermined criteria. How can I do that?
The html code:
<table class="table" id="cnservers">
<thead>
<tr>
<th>Type</th>
<th>Preference</th>
<th>Value</th>
<th>Name</th>
</tr>
</thead>
<tr id="CNTR0">
<td>CNAME</td><td><input type="text" name="CN_PREF[0]" value=""></td><td>
<input type="text" name="CN_VAL[0]" value=""></td><td>
<input type="text" name="CN_NAME[0]" value="">
<a class="btn btn-danger" onclick="DelField(this.id);" id="CN_D0" >
<span class="btn-label">Delete
</span>
</a>
<a class="btn btn-primary" onclick="addField('cnservers','CN',10);" id="CN_A0" >
<span class="btn-label">Add
</span>
</td></tr>
</table>
[1]: http://i.stack.imgur.com/bm0Jq.jpg
I must be missing something. Is there a reason you can't use the http://api.jquery.com/attribute-starts-with-selector/?
$('#CNTR1').find('input[name^="NS"]')
Regarding,
However, what I want to do, is to select everything under $('#CNTR1 input'), and then run a loop on their names, checking whether the names match a predetermined criteria. How can I do that?
$("#CNTR1 input").each(function(index, elem) {
var $elem = $(elem),
name = $elem.attr('name');
var nameMatchesCondition = true; // replace with your condition
if (nameMatchesCondition) {
// do something!
}
});
EDIT 1:
Well, id is still an attribute of an html element. So you could do $('[id^="CNTR1"]') ... The value of the id attribute of an element doesn't contain the #. It's only part of the css/jquery selector. When using attribute style selectors, you don't need it. Though I can't comment on the performance of this.
Ideally, you want to attach a second class, say js-cntr to all elements that you created with an id starting with CNTR. Even though different name pattern elements may already have one class, that class is for styling. There is no stopping you from attaching custom classes purely for selection via js. This is an accepted thing to do and which is why the class name starts with js-, to denote that its purely for use via js for selection.
Try this
HTML
<table id="CNTR1">
<tr>
<td>CNAME</td>
<td><input type="text" name="CN_PREF[1]" id="CN_IN[1]"></td>
<td><input type="text" name="CN_VAL[1]"></td>
<td><input type="text" name="CN_NAME[1]"></td>
</tr>
</table>
JS
$(document).ready(function(){
$("#CNTR1 input").each(function() {
console.log($(this).attr("name"));
// Match With predetermined criteria
});
});
Use jQuery's .filter method, with a filter function:
filterCritera = /^CN_NAME\[/; // or whatever your criteria is
var inputs = $('#CNTR0 input');
// you could also cache this filter in a variable
inputs.filter(function(index){
return filterCritera.test(this.name);
}).css('background','red');
jsbin
The markup you posted does not the markup described in your question ( it does not contain NS[0]) but you can substitute it in the reguluar expression above.
how to collect form atrribute "name" and "value" into array from specific part of form using javascript?
I have a part of form like this:
<div class="multiPickerForm">
<input type="text" name="Id" value="1">
<input type="text" name="OrderNumber" value="SK4569">
<span class="multiPickerItemAddBtn"></span>
</div>
i need to read that part of form using javascript and create array of objects like.
var obj = { name:'OrderNumber', value:'SK4569' }
or something like that so i could loop it and access data easily from formated objects for further development.
Any advice would be highly apreciated. Thanks
This ought to do it:
var obj = [];
$("div.multiPickerForm :input").each(function () {
var tmpPair new Object();
tmpPair['name'] = $(this).attr('name');
tmpPair['value'] = = $(this).val();
obj.push(tmpPair);
});
console.log(obj);
You could use serializeArray() and it does exactly what you need
<div class="multiPickerForm">
<input type="text" name="Id" value="1">
<input type="text" name="OrderNumber" value="SK4569">
<span class="multiPickerItemAddBtn"> </span>
</div>
$('.multiPickerForm :input').serializeArray()
EDIT - You can use it on a form or on a subset of form elements, i updated my example. Taken from the documentation
This method can act on a jQuery object that has selected individual
form elements, such as <input>, <textarea>, and <select>. However, it
is typically easier to select the tag itself for serialization:
fiddle here http://jsfiddle.net/yffr5/
The controls in a form can be accessed using the elements collection. You can iterate over them to test if they are descendents of a div with class multiPickerForm.
If they are and they are sucessful, put them in the array as an object.
How can I create a dynamic form using jQuery. For example if I have to repeat a block of html for 3 times and show them one by one and also how can I fetch the value of this dynamic form value.
<div>
<div>Name: <input type="text" id="name"></div>
<div>Address: <input type="text" id="address"></div>
</div>
To insert that HTML into a form 3 times, you could simply perform it in a loop.
HTML:
<form id="myForm"></form>
jQuery:
$(function() {
var $form = $('#myForm'); // Grab a reference to the form
// Append your HTML, updating the ID attributes to keep HTML valid
for(var i = 1; i <= 3; i++) {
$form.append('<div><div>Name: <input type="text" id="name' + i + '"></div><div>Address: <input type="text" id="address' + i + '"></div></div>')
}
});
As far as fetching values, how you go about it would depend on your intent. jQuery can serialize the entire form, or you can select individual input values.
.append() - http://api.jquery.com/append/
This is a pretty broad question and feels a lot like 'do my work' as opposed to 'help me solve this problem.' That being said, a generic question begets an generic answer.
You can add new address rows by using the append() method and bind that to either the current row's blur - although that seems messy, or a set of +/- buttons that allow you to add and remove rows from your form. If you're processing the form with PHP on the server side, you can name the fields like this:
<input type='text' name='address[]' />
and php will create an array in $_POST['address'] containing all the values.
I'm looking to create a form which contains a dynamic number of input text boxes. I would like each text box to form part of an array (this would in theory make it easier for me to loop through them, especially as I won't know the number of text fields that will eventually exist). The HTML code would like something like:
<p>Field 1: <input type="text" name="field[1]" id="field[1]"></p>
<p>Field 2: <input type="text" name="field[2]" id="field[2]"></p>
<p>Field 3: <input type="text" name="field[3]" id="field[3]"></p>
<p>Field 4: <input type="text" name="field[4]" id="field[4]"></p>
<p>Field 5: <input type="text" name="field[5]" id="field[5]"></p>
This data would then be sent to a PHP script and would be represented as an array - or at least, that's the theory.
So my first question is, is this achievable using HTML? Are forms designed to work that way?
If the answer to that is "yes", how would I then go about accessing each of those using jQuery or failing that, plain old JavaScript?
I've attempted to achieve this using the following jQuery code:
someval = $('#field[1]').val();
and
someval = $('#field')[1].val();
and the following JavaScript:
someval = document.getElementById('related_link_url')[1].value;
But I've not had any luck.
Thanks in advance.
Edit:
I should note that from a Javascript point of view, I've had it working where the ID of each element is something like field_1, field_2 etc. However, I feel that if I can achieve it by placing each text box into an array, it would make for tidier and easier to manage code.
Give each element a class and access the group using jQuery:
<p>Field 1: <input type="text" name="field[1]" class="fields"></p>
<p>Field 2: <input type="text" name="field[2]" class="fields"></p>
<!-- etc... -->
jQuery:
$("input.fields").each(function (index)
{
// Your code here
});
This will run the anonymous function on each input element with a classname of "fields", with the this keyword pointing to the current element. See http://api.jquery.com/each/ for more info.
First of all, id attribute cannot contains [ or ] character.
There is lots of ways to get jQuery/plain JavaScript references to these elements. You can use descendant selector:
<fieldset id="list-of-fields">
<!-- your inputs here -->
</fieldset>
$("#list-of-fields input");
document.getElementById("list....").getElementsByTagName("input");
You can also use attribute selector:
$("input[name^=field]");
I'm not sure whether that's the only way but I think in plain JavaScript you'll have to fetch all input elements (document.getElementsByTagName) and then loop through array of these elements and check each element (whether it has name attribute which value starts with field).