Hi here is a jquery function i am working on i have appended a particular div. The div has 2 inputs I am trying to capture the input values in data_to_send array but it only captures one input because the names are not unique.
function() {
$('#si-goal-link-btn').click(function() {
$('#si-goal-links').append('<div class="goal-link si-goal"><label for="iconURL">Icon URL</label><input class="si-goal-link form-control" type="file" name="iconURL"><br><label for="title">Title</label><input type="text" placeholder="Enter title" class="si-goal-link form-control" name="title"><br><hr></div>')
})
$('form #si-btn').click(function(e) {
e.preventDefault()
var self = $(this)
var data_to_send = {}
$('form').find('.si-input').each(function() {
if ( $(this).attr('name') != undefined) {
if ($(this).hasClass('si-wysiwyg')){
data_to_send[$(this).attr('name')] = $(this).code()
}
if ($(this).hasClass('si-goal-link')) {
//UNABLE TO STORE THE VALUE HERE
data_to_send[$(this).attr('name')] = $(this).val()
}
data_to_send[$(this).attr('name')] = $(this).val()
}
})
var url = $('form').data('si-location')
$.post(url, data_to_send, function(data) {
})
})
}
How do i capture this data and store it as an array within an array over here ?
To get array-within-array-like behavior in Javascript, you will need to make an array a property of your data object, and then push() the same named values onto that array.
var data_to_send = {};
data_to_send.si-goal-link = [];
//inside loop or wherever is needed
data_to_send.si-goal-link.push($(this).val());
$.post(url, $('form').serialize(), function(data) {
})
Related
I am using Data Table in jquery. So i passed one input type text box and passed the single id. This data table will take a multiple text box. i will enter values manually and pass it into the controller. I want to take one or more text box values as an array..
The following image is the exact view of my data table.
I have marked red color in one place. the three text boxes are in same id but different values. how to bind that?
function UpdateAmount() {debugger;
var id = "";
var count = 0;
$("input:checkbox[name=che]:checked").each(function () {
if (count == 0) {
id = $(this).val();
var amount= $('#Amount').val();
}
else {
id += "," + $(this).val();
amount+="," + $(this).val(); // if i give this i am getting the first text box value only.
}
count = count + 1;
});
if (count == 0) {
alert("Please select atleast one record to update");
return false;
}
Really stuck to find out the solution... I want to get the all text box values ?
An Id can only be used once; use a class, then when you reference the class(es), you can loop through them.
<input class="getValues" />
<input class="getValues" />
<input class="getValues" />
Then, reference as ...
$(".getValues")
Loop through as ...
var allValues = [];
var obs = $(".getValues");
for (var i=0,len=obs.length; i<len; i++) {
allValues.push($(obs[i]).val());
}
... and you now have an array of the values.
You could also use the jQuery .each functionality.
var allValues = [];
var obs = $(".getValues");
obs.each(function(index, value) {
allValues.push(value);
}
So, the fundamental rule is that you must not have duplicate IDs. Hence, use classes. So, in your example, replace the IDs of those text boxes with classes, something like:
<input class="amount" type="text" />
Then, try the below code.
function UpdateAmount() {
debugger;
var amount = [];
$("input:checkbox[name=che]:checked").each(function () {
var $row = $(this).closest("tr");
var inputVal = $row.find(".amount").val();
amount.push(inputVal);
});
console.log (amount); // an array of values
console.log (amount.join(", ")); // a comma separated string of values
if (!amount.length) {
alert("Please select atleast one record to update");
return false;
}
}
See if that works and I will then add some details as to what the code does.
First if you have all the textbox in a div then you get all the textbox value using children function like this
function GetTextBoxValueOne() {
$("#divAllTextBox").children("input:text").each(function () {
alert($(this).val());
});
}
Now another way is you can give a class name to those textboxes which value you need and get that control with class name like this,
function GetTextBoxValueTwo() {
$(".text-box").each(function () {
alert($(this).val());
});
}
I need to get all text of value, then use json to send the value to insert all of price to the database, but i had the problem, i can't get the text of all value where input text name='price'.
here this is HTML code:
<input type='text' id='price1' name='price[]'/>
<input type='text' id='price2' name='price[]'/>
<button type='button' id='btn'/>
and this is JS code:
$('#btn').click(function (e) {
var myprice = [];
myprice = $("*[name='price']").val();
$.post(
"index.php",
{
type: "insert",
price: myprice,
}
).done(function (data) {
console.log(data);
})
});
You can use .map() to get all the values:
var myprice = $('[name="price[]"]').map(function(i,v) {
return v.value;
}).get().join(',');
//result: "value1,value2..."
DEMO
Or $.map():
var myprice = $.map($('[name="price[]"]'), function(v,i) {
return v.value;
}).join(',');
DEMO
You cannot get values once, you need to iterate as you need multiple input values.
and use the correct name, change your html:
<input type='text' id='price1' name='price'/>
<input type='text' id='price2' name='price'/>
and code:
var myprice = [];
for(var i=0; i < $("*[name='price']").length; i++){
myprice.push($("*[name='price']:eq("+i+")").val());
}
You can loop through your items (no brackets needed, no change to your HTML) and add them to the array easily -
$('#btn').click(function (e) {
e.preventDefault();
var myprice = [];
$("*[name='price']").each(function() {
myprice.push( $(this).val() );
});
console.log(myprice); // e.g., ["56", "42"]
});
Here is an EXAMPLE
The name is price[], not price.
I have large form mainly drop down lists and checkboxes. Checkboxes are created dynamically so i don't know their id's before they are created. I use drop down onChange event to do create them on the fly.
How can i loop trough the form and get all the checkboxes that are checked, that is their id and their value? I need to do this only for check boxes that are checked. All checkboxes share the same name, that is: categoriesfilters[]. Currently i have on click event on the checkbox which invoke the javascript function.
Here is the code:
function update_number_of_adds_found(field_dropdown,selected_value) {
selected_value="";
var addtypeid = $("#addtypeid").val();
// trying to store the values of the checkboxes
$(this).find("input[type=checkbox]:checked").each(
function() {
var id = $(this).attr('id');
var value = $(this).val(); // or maybe attr('value');
// the data is stored, do whatever you want with it.
alert(value);
}
);
var selected_value = {
addtypeid: addtypeid,
// need to add the ids and the values here as well
};
var url = "<?php echo site_url('search/findNumberOfAdds'); ?>";
$.post(url, selected_value, function(r){
if(r) {
$('#totalNumOfAdds').empty();
$("#totalNumOfAdds").append(r.result);
} else {
// alert(selected_value);
}
}, 'json')
}
Regards, John
Try this :
var categories = [];
$("input[name='categoriesfilters[]']:checked").each(
function() {
var id = $(this).attr("id");
var value = $(this).val();
categories[categories.length] = {id : value};
}
);
console.log(categories);
$.post(url, categories, function(r){
...
Try this :
$('form').submit(function(){
$(this).find("input[type=checkbox]:checked").each(
function() {
var id = $(this).attr('id');
var value = $(this).val(); // or maybe attr('value');
// the data is stored, do whatever you want with it.
}
);
});
I guess you want to check that on form submit.
var arr = [];
$('input[name^="categoriesfilters"]:checked').each(function() {
var obj = {
id: $(this).attr('id');
value: $(this).val();
};
arr.push(obj);
});
console.log(arr); // show us the array of objects
Would you like to use Jquery?
Add a class to each of the checkbox i.e "class_chk";
$(function(){
$('.class_chk').each(function(){
if($(this).is(':checked')){
var id = $(this).attr('id');
var val = $(this).val();
alert("id = "+id+"---- value ="+val);
}
});
});
The above way you can get all the check box id and value those are checked.
Thanks..
Hello friends I have a <input type="text" id="tempID" /> element in my form
I also have an <input type="button" onclick="doSomething()" /> element in my form.
I want to add the text box value to textbox history when user clicks on the button.
I am processing the request using Jquery ajax. So I have to do it with javascript or Jquery.
Is this possible to add values to the history of particular <input type="text" /> element using javascript/Jquery..??
Here is how you can do it using HTML5 LocalStorage
$( "#tempID" ).autocomplete({
source: function( req, resp ) {
var temp = localStorage.getItem('custom_history');
var data = JSON.parse(temp);
resp( data );
}
});
$('#tempID').on('blur', function() {
var temp = localStorage.getItem('custom_history');
var data = JSON.parse(temp);
if($.trim(this.value).length > 0)
data.push(this.value);
localStorage.setItem('custom_history', JSON.stringify(data));
});
What I am doing is Setting the value into HTML5 Local storage when users moves away from the input field, clicks somewhere else.
Then retrieving that and setting that as source for jQuery UI auto complete.
Here is a working fiddle http://jsfiddle.net/joycse06/EBduF/173/
Enter some value. Click somewhere else. Click back again and add other values. The refresh the fiddle and start typing one of those and auto complete will show up.
UPDATE
Based on his comments and later chat the final code he need is this, I am pasting in if it might someone else later
// if we dont set this line then ff will return null, and null.length will throw an error
if(!localStorage.getItem('custom_history'))
localStorage.setItem('custom_history','');
$( "#test" ).autocomplete({
source: function( req, resp ) {
var term = req.term;
var temp = localStorage.getItem('custom_history');
var data = [];
if(temp.length > 0)
data = JSON.parse(temp);
var intRegex = /^\d+$/;
data = $.map(data,function(val){
if(intRegex.test(val)){
if(val.indexOf(term) != -1)
return val;
else
return null;
}
else
return null;
});
resp( data );
}
});
$('#save').on('click', function() {
var temp = localStorage.getItem('custom_history');
var data = [];
if(temp.length > 0)
data = JSON.parse(temp);
var value = $.trim($('#test').val());
if(value.length > 0){
if($.inArray(value,data) != -1){
//alert('Duplicate');
return;
}
}
data.push(value);
localStorage.setItem('custom_history', JSON.stringify(data)); // set item to localStorage
});
You can use localStorage like following:
var arr = [];
$('input#tempID').on('click', function() {
arr.push(this.value);
localStorage.setItem('history', JSON.stringify(arr)); // set item to localStorage
});
To retrieve that value try,
var temp = localStorage.getItem('history');
if(retarr) { // checking that data it stored in localStorage or not, if not exists temp = null
var allHistories = JSON.parse(temp); // now you have history
console.log(allHistories);
}
I think you need something like autocomplete
I have a list of checkboxes. Upon clicking on each of the checkboxes i am adding the value to the hidden variable. But the question is if I want to remove the value from the list upon unchecking the checkbox . How this piece cab be done
here is the hidden form variable
<input name="IDList[]" type="hidden" id="IDList" value="" />
and the jquery
$(".myCheckboxClass").change(function() {
var output = 0;
$(".myCheckboxClass").change(function() {
if ($(this).is(":checked")) {
output += ", " + $(this).val();
} else {
output = $.grep(output, function(value) {
return value != $(this).val();
});
}
$("#IDList").val(output);
});
});
Something like this: (demo) http://jsfiddle.net/wesbos/5N2kb/1/
we use an object called vals to store the info. ADding and removing as we check/uncheck.
var vals = {};
$('input[type=checkbox]').click(function() {
var that = $(this);
if (that.is(':checked')) {
console.log(this.name);
vals[this.name] = "In your Object";
}
else {
delete vals[this.name];
}
console.log(vals);
});
Following your logic, you could do this:
$('#IDList').data('value', []);
$(".myCheckboxClass").change(function() {
var list = $('#IDList').data('value');
if ($(this).is(":checked")) {
list.push($(this).val());
} else {
var indexToRemove = list.indexOf($(this).val());
list.splice(indexToRemove, 1);
}
$('#IDList').val(list);
});
But if you only care about the value of #IDList upon data submission or other actions, you probably want to consider an alternative approach: collating the checked values when you need them.
$('#form').submit(function() {
var list = $('input.myCheckboxClass:checked', this).map(function() {
return $(this).val();
}).get();
$('#IDList').val(list);
});
See both of the above in action: http://jsfiddle.net/william/F6gVg/1/.