Set value of array of input fields, by name - javascript

I have a set of input fields on my page. They're setup as an array like so:
<input type="text" name="test[name][]" /><br />
<input type="text" name="test[name][]" /><br />
<input type="text" name="test[name][]" /><br />
<input type="text" name="test[name][]" />
What i need to do next it to set a unique value in each textfield. But i don't know how to iterate over these fields with jQuery. My attempt failed: DEMO
$(function() {
$.each('input[name="test[name][]"]', function() {
$(this).val('blaat');
});
});
Any idea how i can iterate over each input field, selecting them by name!? I don't have any influence on these controls. So i cannot give them an extra class name or anything like that. All i have are their names.

The selector you use to get array just a is string but not array
'input[name^="test"]' should be $('input[name="test[name][]"]')
You can do it this way,
Live Demo
$(function() {
$.each($('input[name^="test[name][]"]'), function() {
$(this).val('blaat');
});
});
​
​

You could do something like
$(function() {
$.each($('input[name^="test"]'), function() {
$(this).val('blaat');
});
});​
EDIT:
More efficient
$(function() {
$('input[name^="test"]').each(function() {
$(this).val('blaat');
});
});​

Related

Selecting specific element within a div?

I am building a contact form, and I am having problems with jQuery. I want to select specific input fields that have an error and apply the class err. Unfortunately, my code selects all inputs when there is an error. I am having trouble identifying which part of my logic is wrong.
$('#send_mail').click(function(){
$("#contact_body").find('label').each(function(){
var contact_label = $('input[required=true], textarea[required=true]');
var label_check = $(this).find(contact_label);
$(contact_label).removeClass('err');
if (!$.trim($(label_check).val())){
$(contact_label).addClass('err');
}
});
});
The order of my HTML goes something like so:
#contact_body
<label>
<input>
</label>
This selects all input and textarea elements:
var contact_label = $('input[required=true], textarea[required=true]');
Instead, you should restrict it to the elements within the label:
var contact_label = $(this).find('input[required=true], textarea[required=true]');
Note that $(contact_label) and contact_label are equivalent in your code, as well as $(label_check) and label_check.
Also, you can use the state parameter of toggleClass() to simplify this:
contact_label.removeClass('err');
if (!$.trim(label_check.val())){
contact_label.addClass('err');
}
… to this:
contact_label.toggleClass('err', !$.trim(label_check.val()));
Here's the updated event:
$('#send_mail').click(function(){
$('#contact_body').find('label').each(function(){
var contact_label = $(this).find('input[required=true], textarea[required=true]');
var label_check = $(this).find(contact_label);
contact_label.toggleClass('err', !$.trim(label_check.val()));
});
});
I think your original code would work if you just changed this line:
$(contact_label).addClass('err');
To this:
$(label_check).addClass('err');
Because $(contact_label) references all the required inputs, whereas $(label_check) references only the input being checked.
But your code could be simplified, and you make unnecessary calls to $(), giving it an argument that is already a JQuery object.
I also do not see that you need to loop through the labels. You could loop through the required inputs instead.
$('#send_mail').click(function(){
$("#contact_body").find(':input[required]').each(function() {
var $input = $(this);
$input.removeClass('err');
if (!$.trim($input.val())){
$input.addClass('err');
}
});
});
Which could be shortened by using the .toggleClass() function:
$('#send_mail').click(function(){
$("#contact_body").find(':input[required]').each(function() {
$(this).toggleClass('err', !$.trim($input.val()));
});
});
Notes:
The selector ':input' matches <input>, <select> and <textarea> elements.
This is a slightly different approach. Gives a bit more flexibility.
arr = ['first', 'last', 'email', 'msg']; //IDs of fields to check
$('#send_mail').click(function(){
$('input, textarea').removeClass('err');
for (var i=0; i<arr.length-1; i++) { //Loop through all field IDs
if ( $('#'+arr[i]).val() == '' ) {
$('#'+arr[i]).addClass('err').focus();
return false;
}
}
//AJAX to send email goes here
alert('Email sent');
});
.err{background:yellow;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="first">First Name:</label>
<input id="first" type="text" required /><br>
<label for="last">Last Name:</label>
<input id="last" type="text" required/><br>
<label for="email">Email:</label>
<input id="email" type="email" required /><br>
<label for="msg">Message:</label>
<textarea id="msg" required></textarea>
<button id="send_mail">Send</button>
you can simplify the code, there will be less mistakes:
$('#send_mail').click(function(){
$("#contact_body").find('label').each(function(){
var field = $(this).find('[required=true]');
if ($.trim($(field).val())){
$(this).removeClass('err');
}
});
});

What is the best way to iterate input inside a div using this

i'm trying to know (without success), what is the best way to iterate all input element with a specific class in a specific div after a click on a button.
<div>
<input type="text" class="inputtext">
<input type="text" class="inputtext">
<input type="text" class="inputtext">
<input type="text" class="anotherclass">
<input type="text" class="anotherclass">
<button class="full">click me</button>
</div>
So i want to get the value of every input with the class inputtext (but not the one with the class anotherclass). I've tried this :
$(".full").click(function() {
console.log($(this).parent().children(".inputtext").val());
});
Thanks for your attention !
Use .map
var values = $(".inputtext").map(function() { return this.value }).get();
values will be an array of each input value.
Use the .each method of JQuery:
$(".full").click(function() {
$(this).parent().children(".inputtext").each(function(){console.log($(this).val());});
});
Working Fiddle: https://jsfiddle.net/jx6d4neh/
Try with
$(".full").click(function() {
$(this).siblings(".inputtext").each(function(){
console.log($(this).val());
});
});
You could use the each() function, somewhat like this:
$(".full").click(function() {
$(this).parent().children(".inputtext").each(function(){
console.log($(this).val());
});
});
https://api.jquery.com/each/
Or better traverse using siblings() instead of parent().children() like this
$(".full").click(function() {
$(this).siblings(".inputtext").each(function(){
console.log($(this).val());
});
});
https://api.jquery.com/siblings/

how to change an attribute value in jquery

i am unsure why my code does not work, any help would be much appreciated
i am trying to create a jquery function where by, when a user clicks on an
image (e.g: messaging-img) the input field take up the value 101010 | when a user clicks on the unlimited-img the input field take up the value 202020. could one kind;y advise me on this - thank you
$(document).ready(function () {
$(".messaging-img").on("click", function(){
$("#paypal-ref-111").val("101010");
});
$(".unlimited-img").on("click", function(){
$("#paypal-ref-222").val("202020");
});
$(".basic-img").on("click", function(){
$("#paypal-ref-333").val("303030");
});
});
<div class="" id="paypal_express_checkout"><input type="" checked="checked" id="paypal-ref-111" id="paypal-ref-222" id="paypal-ref-333" value=""/></div>
Here is a working solution:
Firstly, I have updated your input field to contain only one ID, named paypal-ref. An element can only contain one ID and it must be unique.
<input type="" checked="checked" id="paypal-ref" value=""/>
Secondly, your jQuery has been updated accordingly:
$(document).ready(function() {
$(".messaging-img").on("click", function() {
$("#paypal-ref").val("101010");
});
$(".unlimited-img").on("click", function() {
$("#paypal-ref").val("202020");
});
$(".basic-img").on("click", function() {
$("#paypal-ref").val("303030");
});
});
You can see a demo here

how to access value hidden elements using loop

what i need
i need to fetch hidden element data according to particular element id.
a.html
<input type="hidden" id="evt_date" value="feb 10">
<input type="hidden" id="evt_date" value="Mar 21">
<input type="hidden" id="evt_date" value="april 05">
js
<script>
$.each($('input'), function(i, val) {
if ($(this).attr("type") == "hidden") {
var event_date = document.getElementById('evt_date');
console.log(event_date);
}
});
</script>
problem
on doing console.log im getting
<input type="hidden" id="evt_date" value="feb 10">
i want to fetch all hidden element in loop using js.
updated js code
$.each($('input.event_date'),function(i,val)
{
if($(this).attr("type")=="hidden")
{
console.log(val);
var evt_date=$('.event_date').val();
console.log(evt_date);
$('.date_event').html(evt_date);
}
});
It's not a good practice to use same id for multiple element. You can instead use class attribute. So first you should change those repeated id attributes into 'class' attributes.
HTML : Updated
<input type="hidden" class="event_date" value="feb 10">
<input type="hidden" class="event_date" value="Mar 21">
<input type="hidden" class="event_date" value="april 05">
<div class="date_event"></div>
<div class="date_event"></div>
<div class="date_event"></div>
Next about your answer, loop through the each element and log the value or use it anyway. Try this,
jQuery :
You question seemed little confusing to me when in one part you asked for the data of the element and in another part you asked for the element itself.
$.each($("input[type='hidden'][class='evt_date']"), function(){
console.log($(this).val()); // value of the element
console.log($(this)); // the element itself
});
jsFiddle
Modification of your code :
jQuery :
var counter = 0;
$.each($('input.event_date'),function(i,val)
{
if($(this).attr("type")=="hidden")
{
console.log(val);
var evt_date=$(this).val();
console.log(evt_date);
$('.date_event:eq('+ counter +')').append(evt_date);
counter++;
}
});
jsFiddle
Dont know why you used same Id but this will be the short way:
$("input [id='evt_date'][type='hidden']").each(function(){
console.log($( this ))
});
$.each($('input'),function(i,val){
if($(this).attr("type")=="hidden"){
console.log($(this).val());
}
});
Demo
Try this
$('input[type="hidden"]').each(function(index,item){
console.log($(item));
});
Working demo
You are using the same id for all the inputs. The id should be unique. Use a class instead
$.each($('input.evt_date'),function(i, field) {
if($(this).attr("type")=="hidden") {
console.log(field);
}
});

form input element arrays with mootools

I tried searching for the answer to this, but did not find the specific answer I was looking for. In mootools, how do I access a form input element like below that has an array name using the "double dollar" ($$) function to be able to iterate through for form validation.
<input name="field[inventory_id]" type="text" />
<input name="field[asset_tag]" type="text" />
<input name="field[idea_tag] type="text" />
<input name="field[equip_make]" type="text" />
<input name="field[equip_model]" type="text" />
etc...
Thanks
Dan B
In MooTools you can use for example:
$$('input[name^="field"]')
This will get you all the input elements that have a name attribute starting with "field".
You could combine with that a .filter() with a funcion for validating and check in the end `the length property of this elements collection. Something like:
$$('button').addEvent('click', function () {
var inputs = $$('[name^="field"]');
var notValidating = inputs.filter(function (input) {
return !input.value;
})
alert('There are ' + notValidating.length + ' inputs not validating.');
});
jsFiddle: http://jsfiddle.net/kthaqmL2/
So I worked on this for a bit and came to the conclusion that giving all of the input elements a classname was the best method. I then used mootools double dollar function to iterate over all of the items with that classname.

Categories