jQuery or JS: Select input fields with 2 level brackets? - javascript

I have a dynamic form that adds users to the site, made so you can duplicate the fields to add several users on one go.
So, my looks like
<input name="user[1][name]" value="" />
<input name="user[1][username]" value="" />
<input name="user[1][password]" value="" />
And then the number is changed on the duplicated fields, eg:
<input name="user[2][name]" value="" />
<input name="user[2][username]" value="" />
<input name="user[2][password]" value="" />
and so on.
On PHP I can handle each user since it has it's own array.
But I would like to validate, for example, the username on each user via jQuery.
The closest I got to is
$(this).find('input[name="user[][username]"]').each(function() {
But for it to work I need to explicitly write the number on the first [], eg:
$(this).find('input[name="user[1][username]"]').each(function() {
Is there a way to select ALL of them? I tried putting * and * between the [] but it didn't work.
Thanks for your help!

You can use the ends with selector

You could use a for loop and not have to write the numbers yourself really easily:
var number_of_forms = 3
for(var i=1;i<=number_of_forms;i++){
$(this).find('input[name="user[' + i + '][username]"]').each(function() {
}

Related

How to Submit a Javascript Value in an Input Field

Simply, how can I do this?
<input type="hidden" value="some javascript value" />
I have a form whereby when a user clicks on Add More, more input fields are added via javascript.
I'm also using javascript-declared values to track and limit the number of fields a user can add.
I need a way for my php code to retrieve these javascript values.
Use append
$('#hidden').val('my Text');
input field should be
<input type="hidden" id="hidden"/>
the question is a bit vague, but i will give it a go
try adding a name as an array and then you can use get or post
<input name="myjavascriptinputs[]" type="hidden" value="some javascript value" />
in your php you will be able to use
foreach($_GET['myjavascriptinputs'] as $ajavascriptinput)
From the button you must be calling a javascript to add these fields dynamically. Simply append the code to that function to hand over these values to the field.
<input id="myinputfield[]" type="hidden" value="" />
<script>
function addOneMore(){
var newField = // code to add one more field
newField.value = newValue;
}
</script>
Will solve your purpose.

Validation plugin for required if previous checkbox is checked

How do I find the previous checkbox to an element using jquery?
I'm writing a custom validation plug-in "cb-required" which acts like "required" if and only if the previous checkbox is checked. The idea is a checkbox followed by one or more dependent text fields and/or selects. I'm not concerned with hiding or disabling the dependent fields in anyway, I just want to enforce "required" if the checkbox is checked.
Right now I'm simply trying to get an alert to pop-up correctly and .prev() is not doing the trick:
$.validator.addMethod("cb-required", function(value, element) {
alert("current="+$(element).attr("name")+" / previous="+$(element).prev(":checkbox").attr("name"));
return true;
}, "This information is required");
The form fields look something like this:
<input name="EMVEnabled" type="checkbox" value="1" />EMV enabled<br />
<span style="font-size:0.8em">
<strong>EMV Template</strong>
<select name="EMVTemplate" size="1" class="cb-required">
<option></option>
<option value="1">Template 1</option>
<option value="2">Template 2</option>
</select><br />
</span>
<br />
<input name="CashAdvance" type="checkbox" value="1" />Cash advance<br />
<br />
<input name="ExpressPay" type="checkbox" value="1" />Express pay<br />
<span style="font-size:0.8em">
<strong>Floor Limit Min</strong>
<input name="ExpressPayFloorMin" type="text" value="" size="12" maxlength="12" class="cb-required numeric" /><br />
<strong>Floor Limit Max</strong>
<input name="ExpressPayFloorMax" type="text" value="" size="12" maxlength="12" class="cb-required numeric" /><br />
</span>
Using your specific example, .prev(":checkbox") isn't working because that method does not move up the DOM treeā€”it will only look at direct siblings. You want to use .parent().prev(":checkbox") or parent.prevAll(":checkbox") if there is a chance that another DOM element would be between the checkbox and the dependent input's parent.
Alternatively, you may want to look into specifying, in your .validate({}) declaration for the "cb-required" rule, the exact checkbox (by jquery selector string) to use for validation, rather than relying on the structure of the DOM. This would give you the flexibility to place your checkbox anywhere in the DOM relative to the input(s) that depend on its checked state, like so:
$form.validate({
rules: {
ExpressPayFloorMin: {
"cb-required": "[name=ExpressPay]"
}
}
});
Using this method, you would need to add a third argument "param" to your validation function, which would be the selector specified in .validate():
$.validator.addMethod("cb-required", function(value, element, param) {
return $(param).prop("checked") && ($(element).val().length > 0);
}, "This information is required");
Believe it or not, your alternate method got me thinking of another way to tackle the problem. In the html I wrapped the checkbox and the dependencies in a div with class="cb-group" attribute. then the following tweak works:
$.validator.addMethod("cb-required", function(value, element) {
alert("current="+$(element).attr("name")+" / previous="+$(element).closest(".cb-group").find(":checkbox").attr("name"));
return true;
}, "This information is required");
Now I can continue and finish with the real logic. Thanks.

GetElementsByName with array like name

i often use this notation when i name my controls in order to get an array in POST or GET.
<input name="color[1]" type="text" />
<input name="color[2]" type="text" />
<input name="color[3]" type="text" />
so in my scripts i can do
<?php $data=$_GET["color"];
for each ($color as $key=>$value) {
doSomething();
} ?>
Often happens that i need to get those id back in javascript , but i cannot get them , so i often add an ID to each element in html like that
<input name="color[3]" id="color_3" type="text" />
so that i can use document.getElementsById('color_3')
Instead i would like to find way to use document.getElementsByName(color[3])...
but i cannot really get it to work.
Any help?
If you want all of the color inputs, you can use querySelectorAll instead to query for the name attribute:
document.querySelectorAll("input[name^='color[']")
This looks through the document for all input tags whose name attribute starts with color[. Here is a fiddle for this.
If you only want color[3], you can use:
var color3 = document.getElementsByName("color[3]");
console.log(color3[0]);
<input name="color[3]" id="color_3" type="text" />
var element = document.getElementsByName("color[3]");
alert(element[0].id);
It works fine .. The thing you should have in your mind is Return type is an array of elements not a single element

How to Generate a List of all Input name="" fields in a form with Javascript/JQuery

I'm sure there's a simple answer to this, but I'm a novice teaching myself Javascript and JQuery and I just don't know enough to figure it out myself. Any help you can provide is greatly appreciated.
I'm building a form that generates HTML emails for my company based on hundreds of different inputs entered by the form user. Rather than copying and pasting each and every input name into a $_POST line in the form's action script to retrieve the input's data, I'm wondering if there's a way to use Javascript/JQuery to generate a list of the name="" fields from each input on the form to make this easier?
For example, from the following slice of the code, how can I automatically generate a list that contains the name values "bottlespecial6image", "bottlespecial6imagewidth", "bottlespecial6imageheight", "bottlespecial6imagelink", and "bottlespecial6includeprice" (with the idea that my form has hundreds (if not thousands) of inputs, so copying/pasting seems inefficient):
<input type="text" name="bottlespecial6image" value=""/>
<input type="text" name="bottlespecial6imagewidth" value=""/>
<input type="text" name="bottlespecial6imageheight" value=""/>
<input type="text" name="bottlespecial6imagelink" value=""/>
<input type="radio" name="bottlespecial6includeprice" value="yes" checked="checked" />
<input type="radio" name="bottlespecial6includeprice" value="no" checked="checked" />
I apologize if this has already been covered here -- I searched around here for similar questions, but couldn't find anything.
To create a serialized array to submit, you'd use jQuery's serialize()
$('form').serialize();
to just get the names in an array, you can map them:
var inputs = $('form').find('input[name]'); //all inputs with a name in the form
var names = $.map(inputs, function(el) { return el.name });
FIDDLE
$("[name='yourrequiredname']")
will give you list of all elements by same name

three text input into one POST name

If I have three text input and I want to combine the values in these three text input into one POST name, how can I do that?
UPDATE:
a good example would be if I have a phone number field, and I have three fields for the phone number... I wanted this to be posted as one so back in the server side I can just access it as $POST['phone']
Would be nice if something like jQuery can help me out here.
Have them as an array:
<input type="text" name="inputs[]" />
<input type="text" name="inputs[]" />
<input type="text" name="inputs[]" />
Then you can access them in the POST array.
You have not indicated the programming language, but in PHP it would be, $_POST['inputs'][0], $_POST['inputs'][1], $_POST['inputs'][2]...
Since you want to have only one phone input which contains the full phone number appear on server side, not parts of it, and you are using jQuery in your project, this will make things easy for you:
1. Sample Markup
<form id="my_form" method="post">
<input type="text" name="phones[]" />
<input type="text" name="phones[]" />
<input type="text" name="phones[]" />
<input type="hidden" name="phone" />
<input type="submit" name="send" value="Send It" />
</form>
2. jQuery
$(document).ready(function(){
var $phones = $('#my_form input[name="phones[]"]'),
$phone = $('#my_form input[name="phone"]');
$('#my_form').submit(function(){
// join all the phone parts together
var phone_number = '';
$phones.each(function(){
phone_number += this.value;
});
// change the hidden input element's value
$phone.val(phone_number);
// remove the phone parts input elements
$phones.remove();
});
});
I wonder why you would need to do that.
In php, you can do as Shef said.
In simple single word cases, you can concatenate them with some separator (e.g. # or $) and process the same on the server side.

Categories

Resources