unable to append data properly to a JS array variable - javascript

I have 2 input fields inside a div within a form element like this
<form>
<div id="si-goal-section">
<div class="si-goal-container">
<input type="text" class="si-input goal-icon" name="goal-icon">
<input type="text" class="si-input goal-title" name="goal-title">
</div>
</div>
<div>
<button type="button" id="goal-btn">Add goal</button>
</div>
</form>
When i click on the button "Add goal" i am appending a new "si-goal-container" div. This is the script for that
$('form #goal-btn').click(function() {
$('form #si-goal-section').append('<div class="si-goal-container"><input type="text" class="si-input goal-icon" name="goal-icon"><input type="text" class="si-input goal-title" name="goal-title"></div>')
})
i then create an array variable in JS and collect and pass the form data into it like this
var data_to_send = []
$('form').find('.si-input').each(function() {
if($(this).hasClass('goal-icon')) {
data_to_send[$(this).attr('name')] = $(this).val()
}
if($(this).hasClass('goal-title')) {
data_to_send[$(this).attr('name')] = $(this).val()
}
})
So this approach will not work because the name fields are the same and the values just get over written. What else could be done here so i could store the appended data in the array and access it later in the php side ?
i tried something like this
var data_to_send = {}
data_to_send.goal = []
$('form').find('.si-input').each(function() {
if($(this).attr('name') != undefined) {
data_to_send.goal.push({
'goalIcon': $(this).find('.goal-icon').val()
'goalTitle': $(this).find('goal-title').val()
})
}
})
But this too doesn't give me the required o/p i am looking for. I need my data_to_send array to look something like this in the ajax call.
...
data_to_send['bannerImage']:
data_to_send['goalName']:
data_to_send['goalIcon'][0]:
data_to_send['goalTitle'][0]:
data_to_send['goalIcon'][1]:
data_to_send['goalTitle'][1]:
...
What would be the right way to append the fields and store it into the array ? I i am using serialize() then how do i use it only for particular fields ?

Give an id to your first input elements of si-goal-section as below:
<div class="si-goal-container">
<input type="text" id="goalicon_1" class="si-input goal-icon" name="goal-icon"/>
<input type="text" id="goaltitle_1" class="si-input goal-title" name="goal-title"/>
</div>
now in JS on click event of button fetch the ids for title and icon from last si-goal-section and split it based on _ as below:
$('form #goal-btn').click(function() {
var goalIconID=parseInt($(".si-goal-container:last .goal-icon").attr('id').split("_")[1])+1;
//fetch .goal-icon's and goal-title's id by from last .si-goal-container and add + 1 [increment id]
var goalTitleID=parseInt($(".si-goal-container:last .goal-title").attr('id').split("_")[1])+1;
$('form #si-goal-section').append('<div class="si-goal-container"><input type="text" class="si-input goal-icon" id="goalicon_'+goalIconID+'" name="goal-icon"><input type="text" id="goaltitle_'+goalTitleID+'" class="si-input goal-title" name="goal-title"></div>');
//add id to the newly created elements
})
Thus you can now have unique elements and push it to your array as values
DEMO

Try this : You can iterate over si-goal-container div and then read si-input input fields inside it. Store values in map and add map to array as shown below
$(document).ready(function(e) {
$('form #goal-btn').click(function() {
$('form #si-goal-section').append('<div class="si-goal-container"><input type="text" class="si-input goal-icon" name="goal-icon"><input type="text" class="si-input goal-title" name="goal-title"></div>')
});
$('form #value-goal-btn').click(function() {
var data_to_send = new Array();
$('form').find('div.si-goal-container').each(function() {
var container_data = {};
$(this).find('.si-input').each(function(){
container_data[$(this).attr('name')] = $(this).val();
});
data_to_send.push(container_data);
});
alert(JSON.stringify(data_to_send));
});
});
JSFiddle Demo

Related

when I will type the first row 3 input box then those values are shown in the display name input box

when I will type the first row 3 input box then those values are shown in the display name input box.
var output = $('.keyupDisplay');
$('.keyupName').keyup( function() {
output.val(function () {
return $('.keyupName').map(function () {
return this.value;
}).get();
});
});
It is shown on the display input box but shows with "," separation. Like Mr,Motalib,Hossain
I need the result like this Like Mr Motalib Hossain
Use join
Cache the fields
Also no need to use a function inside the val
Use input since it also handles paste
Lastly, don't name a field after what you decided to use to interrogate it. As we see it can change
const $displayName = $('.displayName')
const $names = $('.personName').on('input', function() {
$displayName.val(
$names
.map(function() { return this.value; })
.get()
.join(' ')
)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Names: <input type="text" id="title" class="personName" />
<input type="text" id="firstName" class="personName" />
<input type="text" id="lastName" class="personName" />
<br/>
<input type="text" class="displayName" />

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');
}
});
});

Value of set of input tags in a JS array

I have a set of input tags
<input name= "keys[]" type="text">
<input name= "keys[]" type="text">
<input name= "keys[]" type="text">
<input name= "keys[]" type="text">
<input name= "keys[]" type="text">
Is it possible to get all the input of type text values in an array using the name keys[]
I tried this
$('input[name="keys[]"]').val()
But I got the value of the first input tag only.
I wanted to get a array of the values of these input tags. Is it possible without going thru an iteration?
Thanks
Try serializeArray() it will return an array of objects with name and value.
$('input[name="keys[]"]').serializeArray()
You can use map:
$('input[name="keys[]"]').map(function(key, input) { return input.value; });
You can try something like
var array= new Array();
$('input[name="keys[]"]').each(function(index){
array[index] = $(this).val();
});
Hope I help!
http://jsfiddle.net/Gh6Z9/4/
var values = new Array();
$.each( $('input[name="keys[]"]'), function() {
values.push($(this).val());
});
console.log(values);

Set Input array value using jquery

I am trying to implement html input array.
<input type="text" name="firstName[]" id="firstName[]">
And i need to set value of another form which looks something like
<form id="tempForm">
<input type="text" name="userName" id="userName">
<input type="text" name="userId" id="userId">
</form>
into the input array using jquery on form submit.
For that i tried following on form submit,
var currentIndex=$("input[name^=firstName]").length;
$("#firstName").eq(currentIndex).val($("#userName").val());
But it doesn't works,obviously.
Question:
How to set value of input array using jquery?
Use the jquery append function for add inputs with different attribute value :
Check it :
$(document).ready(function(){
var a = ["username","userid"];
var b = ["username","userid"];
for( var i = ; i <3 ; i++){
$('#tempForm').append('<input type="text" name="'+a[i]+'" id="'+b[i]+'" />);
}
});
Then continue your other work:
replace this code with your js code :
var currentIndex=$("input[name^=firstName]").length;
$("#firstName").eq(currentIndex).val($("#"+userName).val());

javascript print array values dynamic

hi everyone i have a problem in javascript i can print array if fix them in html but whn i try to print them on clic they are not working just print the array names
if i print seriesre simple it print values that is fine but when i check any checkbox and want to print one or tow of them it just showing array name not values
thanks for help
check this example
$(document).ready(function() {
Comment = [['2011-01-29',7695],['2011-02-02',19805]];
WallPost = [['2011-01-29',11115],['2011-02-02',8680]];
Likes = [['2011-01-29',5405],['2011-02-02',10930]];
var seriesre= [Comment,WallPost,Likes];
var mygraphs = new Array();
alert(seriesre);
$("#testCheck").click(function() {
i=0;
$("#testCheck :checked").each(function() {
mygraphs[i]= $(this).val();
i++;
});
newseriesre = "["+mygraphs+"]";
alert(newseriesre);
});
});
<div class="activity">
<form method="POST" id="testCheck" name="myform">
Likes
<input type="checkbox" value="Likes" name="box2">
Comments
<input type="checkbox" value="Comment" name="box3">
Wall Post
<input type="checkbox" value="WallPost" name="box4">
</form>
</div>
You can use
alert(myarray.join())
to alert your array's values
You should use a associative array instead of an array, so that you can look up the data based on the name as a string instead of trying to find the variable. All objects in Javascript are associative arrays, so just put the data in an object.
Also:
Create the mygraphs array inside the event handler, otherwise it can not shrink when you uncheck options.
Catch the click on the checkboxes inside the form, not on the form itself.
Put a label tag around the checkbox and it's label, that way the label is also clickable.
You don't need an index variable to put values in the mygraphs array, just use the push method to add items to it.
http://jsfiddle.net/cCukJ/
Javascript:
$(function() {
Comment = [['2011-01-29',7695],['2011-02-02',19805]];
WallPost = [['2011-01-29',11115],['2011-02-02',8680]];
Likes = [['2011-01-29',5405],['2011-02-02',10930]];
var seriesre = {
'Comment': Comment,
'WallPost': WallPost,
'Likes': Likes
};
$("#testCheck :checkbox").click(function() {
var mygraphs = [];
$("#testCheck :checked").each(function() {
mygraphs.push(seriesre[$(this).val()]);
});
alert("["+mygraphs+"]");
});
});
HTML:
<div class="activity">
<form method="POST" id="testCheck" name="myform">
<label>
Likes
<input type="checkbox" value="Likes" name="box2">
</label>
<label>
Comments
<input type="checkbox" value="Comment" name="box3">
</label>
<label>
Wall Post
<input type="checkbox" value="WallPost" name="box4">
</label>
</form>
</div>
I understand that you want to alert the selected values when clicking anywhere on the form? If that's true correct code with minimal changes to your existing code will be:
var mygraphs = [];
$("#testCheck").click(function() {
$("#testCheck :checked").each(function() {
mygraphs.push($(this).val());
});
alert("Selected values are: " + mygraphs.join(", "));
});
You can try this.
alert($("#testCheck :checked")
.map( function(i, field) { return field.value}
).get());
Check your working example in http://jsfiddle.net/dharnishr/d37Gn/

Categories