Associative array passing as empty string - javascript

I am trying to pass an array to PHP via Ajax, but the array is being passed as an empty string. This is my code when creating the array:
var params = new Array();
var inputs = new Array();
inputs = $(":input");
$.each(inputs, function(key, value) {
params[value.id] = value.value;
});
alert(params);
Before that there are around 20 inputs that look like this:
<input name="first_name" id="first_name" type="text" class="medium"/>
<input name="last_name" id="last_name" type="text" class="medium"/>
The alert(params) is just giving me an empty string. However, alert(params['first_name']) actually gives me the first_name input value.
Why isn't the array going through?

Can you try this -
$(document).ready(function() {
var params = new Array();
var inputs = $(":input");
$.each(inputs, function(key, value) {
//I guess the problem was that params is array and your id's were strings
//array's elements are arr[0], arr[1],
//not like arr[firstname], arr[lastname], ...
params[value.id] = value.value;
});
alert(params);
});
//moved everything inside $(document).ready
with this -
<input name="first_name" id="0" value="1" type="text" class="medium"/>
<input name="last_name" id="1" value="2" type="text" class="medium"/>
<!-- Changed id's from string to numbers. -->
Update:
Also, try this it might help you understand whats going on -
$(document).ready(function() {
var params = {}; //use object instead of array
var inputs = $(":input");
$.each(inputs, function(key, value) {
params[value.id] = value.value;
});
for(var prop in params) {
alert(prop + " = " + params[prop]);
}
});
Notice: params is an object now not an array.
With this -
<input name="first_name" id="firstname" value="Your first name." type="text" class="medium"/>
<input name="last_name" id="lastname" value="Your last name." type="text" class="medium"/>

You can't simply pass a variable to the server, you need to serialize it into name, value pairs, or use JSON.

I'm slightly unsure what you're trying to accomplish by creating an array in Javascript like this.
Your best bet is probably to use the JQuery command serialize then grab the data using $_GET

Related

Javascript set value for Form obeject Array

I am looking to add data to a form object which is an array.
This works fine:
<input type="text" name="object" value="">
<script>document.form.object.value = "value";</script>
But when the object is an array it's not working:
<input type="text" name="object[]" value="">
<script>document.form.object[0].value = "value";</script>
The value of the object is not changing.... Any idea?
I would like to loop the script so I need to create an array. Didn't find any solution...
Per example, I would utilize document.form.elements['object[]'].value = "value". Otherwise, if you intended on having multiple form elements with the same name (multiple inputs with object[], and iterate via the collection, can use the following:
var myForm = document.form;
var myControls = myForm.elements['object[]'];
for (var i = 0; i < myControls.length; i++) {
var aControl = myControls[i];
}
The example provided, in your code, the name provided is not perceived as an array.
The attribute value "object[]" is just a string to JavaScript -- it does not interpret that as an array. However, when brackets appear in a name, you cannot use it any more in the dot-notation, but must write:
document.form["object[]"].value = "value";
<form name="form">
<input type="text" name="object[]" value="">
</form>
If you have more than one element with name="object[]", then the above will only target the first one of these. To set the value of all those elements, you must loop. This you can (for instance) do with the elements property and Array.from to iterate over those elements:
Array.from(document.form.elements["object[]"], function(elem) {
elem.value = "value";
});
<form name="form">
<input type="text" name="object[]" value="">
<input type="text" name="object[]" value="">
</form>
For those using IE: replace Array.from with [].map.call

sending multiple inputs on ajax

i have a form where i get a collection of records, and after being present is shown like this:
<input name="position" id="nameText" step-id="3" type="number" value="1" class="form-control stepinput">
<input name="position" id="nameText" step-id="4" type="number" value="2" class="form-control stepinput">
<input name="position" id="nameText" step-id="5" type="number" value="3" class="form-control stepinput">
The value is to later sort the records, and the "step_id" attribute is to send via ajax to update the specific record, but my data is not quite looking good. Wich is the best way to send my data to the controller to later being updated the records
My current code:
$('button.update-positions').on('click', function(event){
event.preventDefault();
var form = $(this).closest(".steps-form");
var map = {};
$(".stepinput").each(function() {
map[$(this).attr("step-id")] = $(this).val()
});
})
Hard to read but if I understood correctly you:
Have an 3 inputs of numbers
Want the value entered being updated in the Database
use "step-id" to identify which one to update
If so then replace step-id="" by data-stepid="" and the code for that would be:
$("button.update-positions").on("click",function(event) {
event.preventDefault();
var form = $(this).closest(".steps-form");
var map = {};
$(".stepinput").each(function(index,value) {
map[$(this).data("stepid")] = value.value;
});
console.log(map); // Your map object
});
You can't have 2 elements with the same ID and you should use a data-attribute if you want to pass on information like so.

how to get input array value by key with javascript function?

Here is sample code i try to create input array with key and on change i want to get the value of individual input array value.
<input type="text" name="items[1]" value="443" onchange="get_items(1)">
<input type="text" name="items[2]" value="233" onchange="get_items(2)">
<script>
function get_items(key)
{
alert($("items["+key+"]").val());
}
</script>
Simply pass this context as argument and get value.
<input type="text" name="items[1]" value="443" onchange="get_items(this)">
<input type="text" name="items[2]" value="233" onchange="get_items(this)">
<script>
function get_items(ele) {
alert(ele.value);
}
</script>
Refer fiddle
HTML:
<input type="text" name="items[1]" value="443" onchange="get_items(1)">
<input type="text" name="items[2]" value="233" onchange="get_items(2)">
JS:
function get_items(key)
{
alert($('input[name="items['+key+']"]').val());
}
You can get the event's target from event,
function get_items(e) {
console.log(e.target.value);
}
<input type="text" name="items[1]" value="443" onchange="get_items(event)">
<input type="text" name="items[2]" value="233" onchange="get_items(event)">
or, better, attach your listener in javascript:
function get_items(e) {
console.log(e.target.value);
};
var inputs = document.querySelectorAll("input");
for (var i = 0, el; i < inputs.length; i += 1) {
el = inputs[i]
el.addEventListener("change", get_items);
};
<input type="text" name="items[1]" value="443">
<input type="text" name="items[2]" value="233">
Here is some code that does what (I think) you are trying to do:
<input type="text" name="item1" value="443" onchange="javascript:get_items(1)">
<input type="text" name="item2" value="233" onchange="javascript:get_items(2)">
<script>
function get_items(key)
{
//alert($("items["+key+"]").val());
var input = $('input[name="item' + key + '"]');
var value = input.val();
alert(value);
}
</script>
jsfiddle: https://jsfiddle.net/9kvv2q7p/4/
You can use this
function get_items(key) {
alert($("input[name='items[" + key + "]']").val());
}
I hope I was helpfull
Your HTML is missing a closing quote for the name attributes.
The name attribute should not contain [ or ]
characters. Adding these characters will complicate matters.
You should hook up your event handlers in JavaScript, not HTML.
When practical, elements should have unique id attributes added to them, which will make accessing and identifying them much easier in JavaScript and CSS
Rather than trying to identify the textboxes with indexes, just gather them up and place them into an array or array-like container, where indexes will be automatically assigned to them.
Here is a working example of how to get values by index:
// This will scan the DOM and place all matched elements into a node list
// which is an array-like object
var textBoxes = document.querySelectorAll("input[type=text]");
// Or, you can get references to them individually:
var txt1 = document.getElementById("txt1");
var txt2 = document.getElementById("txt2");
// And, put them into an array on your own:
var ary = [txt1, txt2];
// No matter how you got your references to them, it's best to hook
// them up to event handler in JavaScript, not HTML
txt1.addEventListener("change", get_items2);
txt2.addEventListener("change", get_items2);
function get_items(key) {
// You can certainly pass a key to this function
// to identify which element you are talking about
alert(textBoxes[key].value);
}
function get_items2(evt) {
// But, event handlers are automatically passed
// a reference to the object that fired the event
alert(evt.target.value);
}
get_items(0); // Call the function to get first textbox value
get_items(1); // Call the function to get second textbox value
<input type="text" id="txt1" name="txt1" value="443">
<input type="text" id="txt2" name="txt2" value="233">

Import json to html input fields with jquery

I have a json like this from a url. (Example: http//www.somedomain.com/controller/json)
[{"id":"12","event":"LOGOUT SUCCESS","ip":"0.0.0.0","date":"2016.04.08 15:44"}]
I would like to import these values to an html file's form input fields with jQuery. The form is like this:
<input id="id" type="text" value="12">
<input id="event" type="text value="LOGOUT SUCCESS">
...
Is there any simple solution for this?
Since the id of each input field is the same as the name in each name/value pair, a for..in loop can do this very easily.
$.getJSON("http//www.somedomain.com/controller/json", function(json) {
json = json[0]; //the object is in the first element of the wrapping array
for (name in json)
$("form").append('<input id="'+name+'" type="text" value="'+json[name]+'"/>');
});
If you wish to just set the values of an already existing form:
$.getJSON("http//www.somedomain.com/controller/json", function(json) {
json = json[0];
for (name in json)
$("#"+name).val(json[name]);
});
You can unserialize your json :
json_string = "[{"id":"12","event":"LOGOUT SUCCESS","ip":"0.0.0.0","date":"2016.04.08 15:44"}]";
var arr_from_json = JSON.parse( json_string );
And then loop on the attributes :
$.each( arr_from_json, function(i, n){
$("#"+i).attr("value",n);
});
Parse the JSON to an object. You can then iterate through it and create or set the input elements. Although you asked for it in the question, this is so trivial that there is little point in using jQuery for it (You Might Not Need jQuery).
If you wish to create the inputs:
var json = '[{"id":"12","event":"LOGOUT SUCCESS","ip":"0.0.0.0","date":"2016.04.08 15:44"}]',
data = JSON.parse(json)[0];
for (var key in data) {
if (data.hasOwnProperty(key)) {
var i = document.createElement("input");
i.setAttribute('type',"text");
i.setAttribute('name',key);
i.setAttribute('value',data[key]);
document.body.appendChild(i);
}
}
If you just wish to set the values:
var json = '[{"id":"12","event":"LOGOUT SUCCESS","ip":"0.0.0.0","date":"2016.04.08 15:44"}]',
data = JSON.parse(json)[0];
for (var key in data) {
if (data.hasOwnProperty(key)) {
document.getElementsByName(key)[0].value = data[key];
//or document.getElementsById("#"+key)[0].value = data[key];
}
}
<input type="text" name="id" value="" />
<input type="text" name="event" value="" />
<input type="text" name="ip" value="" />
<input type="text" name="date" value="" />

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

Categories