text 'Undefined' displayed when try access json list - javascript

In one of the jsp pages from my project, I have to work with this json lists:
var obj_tipo = jQuery.parseJSON( "{"Tipo":[{"id":3,"nome":"gerente"},{"id":4,"nome":"supervisor"},{"id":5,"nome":"analista"},{"id":6,"nome":"tecnico"},{"id":7,"nome":"secretaria"},{"id":8,"nome":"seguranca"}]}" );
var obj_campo = jQuery.parseJSON( "{"Key":[{"id":1,"nome":"e-mail"},{"id":2,"nome":"cidade"}]}" );
I try read each item of the list this way:
for(var item in obj_tipo.Tipo)
select.append('<option value="'+item.nome+'">'+item.nome+'</option>');
and
for(var item in obj_campo.Key)
$("table.cadastro").append('<tr> <td> '+item.nome+' : </td> <td> <input type="text" name="'+item.nome+'" size=20 maxlenght=40> </td> <tr>');
But I am getting the text 'undefined' when I display the page, instead of the corret text, despite the fact that the right amount of itens are being displayed.
Someone knows how to fix that? What the right way to access each item from my json list? the list is well formed, right?

As #Oleg said, it should be more like:
var obj_tipo = jQuery.parseJSON( '{"Tipo":[{"id":3,"nome":"gerente"},{"id":4,"nome":"supervisor"},{"id":5,"nome":"analista"},{"id":6,"nome":"tecnico"},{"id":7,"nome":"secretaria"},{"id":8,"nome":"seguranca"}]}' );
var obj_campo = jQuery.parseJSON( '{"Key":[{"id":1,"nome":"e-mail"},{"id":2,"nome":"cidade"}]}' );
I basically just changed the wrapping quotes, to '
Also, you may want to consider looping through the JSON using $.each, if you are using jQuery. See this question here for some clarification: jquery loop on Json data using $.each

Using for in on arrays is not a good idea. Either use for (var i = 0; i < arr.length; i++) {... or native forEach or jQuery's each...
var obj = $.parseJSON('{"Tipo":[{...},{...},{...}]}'); // mind the quotes
$.each(obj.Tipo, function (index, item) {
select.append('<option value="' + item.nome + '">' + item.nome + '</option>');
});

Use
for(var item in obj_tipo.Tipo) {
var nome= obj_tipo.Tipo[item].nome;
select.append('<option value="'+nome+'">'+ nome +'</option>');
}
instead of
for(var item in obj_tipo.Tipo)
select.append('<option value="'+item.nome+'">'+item.nome+'</option>');
For more info visit for...in
variable: A different property name is assigned to variable on each iteration.

I don't have any idea about Java language. But you can get the Nome and id field by using below code snippet.
Please try with the below code snippet. Let me know if any concern.
var tipo = obj_tipo.Tipo;
for(var i = 0; i < tipo.Length; i++)
{
select.append('<option value="'+tipo[i].id+'">'+tipo[i].nome+'</option>');
}

The item in your code returns the index of the array. I updated your code to get to a solution. Please find the fiddle here
$("table.cadastro").append('<tr> <td> '+obj_campo.Key[item].nome+' : </td> <td> <input type="text" name="'+obj_campo.Key[item].nome+'" size=20 maxlenght=40> </td> <tr>');
or
for(var item in obj_tipo.Tipo)
$('select').append('<option value="'+obj_tipo.Tipo[item].nome+'">'+obj_tipo.Tipo[item].nome+'</option>');

Related

How to pass an list of objects to view and populate them in input fields dynamically

Im passing a list objects to the view using Spring model attribute. And in the view im trying to populate set of inputs dynamically using jquery as below :
passing the list from the controller :
List<String> supplierNames = Arrays.asList("address1", "address2", "address3");
model.addAttribute("consumerAddresses", supplierNames);
view (jsp):
<div class="input_fields_wrap">
<div><input type="text" id='label1'><input type="text" id='address1'></div>
</div>
<script>
$(document).ready(function() {
var consumerAddresses = "${consumerAddresses}";
var max_fields = 10;
var wrapper = $(".input_fields_wrap");
for (i = 0; i < consumerAddresses.length; i++) {
$(wrapper).append('<div><input type="text" id="label' + i + '" value=' + consumerAddresses[i] + '/><input type="text"
id="address' + i + '" value=' + consumerAddresses[i] + '/></div>');
}
});
</script>
Now the issue is consumerAddresses are passed as array [address1, address2, address3] but in input fields its populated as [/ a/ d/ likewise. what has gone wrong here?
Inside consumerAddresses you have not an array, it's a string.
And then when you're trying to iterate over it you just take some chars from it.
You need to convert string to an array before iterating through it.
In this case you can use split method.
var consumerAddressesArray = consumerAddresses.replace(/[[\]']+/g,'').split(", ");
After this operations you will have
[
"address1",
"address2",
"address3"
]
inside your consumerAddressesArray variable.
And make sure that you have trimmed all rudimentary chars. I mean [, (space), ]. In my example I've used regex for that (.replace(/[[\]']+/g,'')). It will replace square brackets with empty string.
You can get value which is return by spring mvc in some jsp variable then use for-loop in jsp to iterate through that list i.e :
<%
//get value in jsp variable
//i.e :request.getAttribute("consumerAddresses");
//here i assumme consumerAddresses is variable in jsp which has that arry value
for(int x=0;x<consumerAddresses.length;x++) {%>
$(wrapper).append('<div><input type="text" id="label<%=x%>" value='<%=consumerAddresses[x]%>'/>
<input type="text" id="address<%=x%>" value='<%=consumerAddresses[x]%>'/></div>');
<%}%>
Note : Above code is not tested it might be having some syntax error .Also, you can do same using jstl .

Dynamically assigning variable names JavaScript

I am trying to dynamically assign variable names using the user's input. For example:
var input = document.querySelector('input');
for(var i = 0; i < 10; i++){
var newVariableName = //input.value;
}
Any help would be very much appreciated.
Thank you,
Scratch Cat
Everything in JavaScript is an object. The way JavaScript works, you can add properties to objects in two ways:
Specify them the fixed way (e.g. obj.propertyName = 'Value')
Specify them using array notation (e.g. obj[propertyName] = 'Value'). In this case, note that propertyName is a string value.
In both cases, the result will be exactly the same. You could retrieve those properties likewise, e.g. obj.propertyName and obj[propertyName]. Both will return 'Value'.
In your case, #LuudJacobs's suggestion about using the window object will most probably do the trick...
You can use array in which the keys will be the input values and the value would be anything you want.
html
<form>
<input type="text" value="demo1" class="example"><br />
<input type="text" value="demo2" class="example"><br />
<input type="text" value="demo3" class="example">
</form>
js
First you declare array
var a = new Array();
Then you use for loop to assign key names to array which will be the input values
for(var i = 0; i < 3; i++){
a[x[i].value] = x[i].value;
}
Finally you can use those key names to access the values
alert(a['demo1'] + ' ' +a['demo2'] + ' ' + a['demo3']);
Here is a link to an example
https://jsfiddle.net/309fpsjn/1/
<html>
<form>
<input type="text" value="demo1" class="example"><br />
<input type="text" value="demo2" class="example"><br />
<input type="text" value="demo3" class="example">
</form>
<script>
var x = document.querySelectorAll(".example");
var a = new Array();
for(var i = 0; i < 3; i++){
a[x[i].value] = x[i].value;
}
alert(a['demo1'] + ' ' +a['demo2'] + ' ' + a['demo3']);
</script>
</html>

Loop through each child in a div with data-attribute

I have multiple <div>s, based on a <select>, where each one contains multiple <input>s and sometimes a disabled <select> with a fixed value. Now I'm trying to loop through each of the divs and put all inputs and select values into an array and push that array into the "master" array.
However this seems not to work to well.
I feel like I'm already close but yet so far. :(
var dummy = [];
for(var i = 1; i <= toSend.count; i++){
var temp = [];
$("div[data-row="+i+"]").children('input, select').each(function(){
temp.push( $(this).val() );
});
dummy.push(temp);
};
console.log(dummy);
toSend.count is the counting of how many div's with data-row exist.
The HTML looks like this :
<div id="container">
<div data-row="1">
<input type="text"/>
<input type="text"/>
</div>
<div data-row="2">
<input type="text"/>
<input type="text"/>
</div>
</div>
Aaah, nevermind this was my own stupidity! I'm generating the div's via AJAX
and I copy pasted myself an error.
All div's had data-row=1, no wonder it packed all in one array >.<
(Edit: pays to read the code more completely)
Since the toSend variable is just the DIVs with a data-row attribute, no need to loop over toSend to find the DIVs:
var dummy = [];
$("#container div[data-row]").each(function() {
var temp = [];
$(this).children("input, select").each(function() {
temp.push(this.value);
});
dummy.push(temp);
});
After this, you might not even need the toSend variable at all.
Brief code for what you want to achieve.
$("div[data-row="+i+"]")each(function(){
$(this).children('input, select').each(function(){
console.log( $(this).val());
console.log("Child Change");
});
console.log("Div Change");
});
.each function from jquery is not syncrounious, use for instead.
var $tmp;
for(var i = 1; i <= toSend.count; i++)
{
$tmp = $("div[data-row="+i+"]").children('input, select');
for(var ii = 1,len = $tmp.length; ii <= len; ii++){
console.log( $tmp.eq(ii).val());
};
console.log("New line #" + i);
};

Getting multiple selected checkbox values in a string in javascript and PHP

I have location name and location Id in database table. Using foreach loop i'm printing the values in checkbox in PHP. I have a submit button which triggers a javascript. I want the user selected all checkbox values separated by comma, in a javascript variable. How can I do this?
<!-- Javascript -->
<script>
function getLoc(){
var all_location_id = document.getElementByName("location[]").value;
var str = <!-- Here I want the selected checkbox values, eg: 1, 4, 6 -->
}
<script>
foreach($cityrows as $cityrow){
echo '<input type="checkbox" name="location[]" value="'.$cityrow['location_id'].'" />'.$cityrow['location'];
echo '<br>';
}
echo '<input name="searchDonor" type="button" class="button" value="Search Donor" onclick="getLoc()" />';
var checkboxes = document.getElementsByName('location[]');
var vals = "";
for (var i=0, n=checkboxes.length;i<n;i++)
{
if (checkboxes[i].checked)
{
vals += ","+checkboxes[i].value;
}
}
if (vals) vals = vals.substring(1);
This is a variation to get all checked checkboxes in all_location_id without using an "if" statement
var all_location_id = document.querySelectorAll('input[name="location[]"]:checked');
var aIds = [];
for(var x = 0, l = all_location_id.length; x < l; x++)
{
aIds.push(all_location_id[x].value);
}
var str = aIds.join(', ');
console.log(str);
var fav = [];
$.each($("input[name='name']:checked"), function(){
fav.push($(this).val());
});
It will give you the value separeted by commas
I you are using jQuery you can put the checkboxes in a form and then use something like this:
var formData = jQuery("#" + formId).serialize();
$.ajax({
type: "POST",
url: url,
data: formData,
success: success
});
In some cases it might make more sense to process each selected item one at a time.
In other words, make a separate server call for each selected item passing the value of the selected item. In some cases the list will need to be processed as a whole, but in some not.
I needed to process a list of selected people and then have the results of the query show up on an existing page beneath the existing data for that person. I initially though of passing the whole list to the server, parsing the list, then passing back the data for all of the patients. I would have then needed to parse the returning data and insert it into the page in each of the appropriate places. Sending the request for the data one person at a time turned out to be much easier. Javascript for getting the selected items is described here: check if checkbox is checked javascript and jQuery for the same is described here: How to check whether a checkbox is checked in jQuery?.
This code work fine for me, Here i contvert array to string with ~ sign
<input type="checkbox" value="created" name="today_check"><strong> Created </strong>
<input type="checkbox" value="modified" name="today_check"><strong> Modified </strong>
<a class="get_tody_btn">Submit</a>
<script type="text/javascript">
$('.get_tody_btn').click(function(){
var ck_string = "";
$.each($("input[name='today_check']:checked"), function(){
ck_string += "~"+$(this).val();
});
if (ck_string ){
ck_string = ck_string .substring(1);
}else{
alert('Please choose atleast one value.');
}
});
</script>

I need help getting Javascript to read an HTML form, and assign it to a specific array

I need help getting javascript to read an html input form, and assign the input to an array, or atleast what i think is an array....im not sure.
i want to take the data from an html form, and put it in here:
var users = ['"This is a random qoute"-lastname,firstname."','"This is a random
qoute"-lastname,firstname."'];
is this possible?
If you want an array of the text input names and values, the following will do the job. If you want to
serialize a form for posting, that takes a little more code.
<script type="text/javascript">
function getInputs(form) {
var input, inputs = form.getElementsByTagName('input');
var result = [];
for (var i=0, iLen=inputs.length; i<iLen; i++) {
input = inputs[i];
if (input.type == 'text') {
result.push(input.name + ': ' + input.value)
}
}
return result;
}
</script>
<form>
<table>
<tr>
<td>name<td><input type="text" name="userName">
<tr>
<td>age<td><input type="text" name="userAge">
<tr>
<td colspan="2"><input type="button" value="Show inputs"
onclick="alert(getInputs(this.form));">
</table>
</form>
Shows "userName: <value>, userAge: <value>"
Check about jQuery.serializeArray
Example:
$('form').submit(function() {
var params = $(this).serializeArray();
console.log(params);
return false;
});
The console will show something like:
[
{
name: "input1Name",
value: "input1Value"
},
{
name: "input2Name",
value: "input2Value"
}
]
After your form submit you can access your params in objects, like:
Get all
jQuery.each(params, function(objPosition, obj){
alert("name: " + obj.name + " Value: " + obj.value);
});
OR to get one ( in this case's the first one)
alert("name: " + params[0].name + " Value: " + params[0].value);
You can see it working here: http://jsfiddle.net/ricardolohmann/Jfu9H/
You can do this nicely with jQuery.serialize()
If you are not familiar with jQuery use this Tutorial to understand its basics. It's a Java Script Library.
Now you can work according to this example written by me.
it reads form element values into a string,
var srt=$("form").serialize();
and split the resulted string from '&' sing to get the expected string array.
var srtArray=srt.split('&');
result is something like this,
["text1=Lasantha", "dropDownList1=Single", "List1=Multiple1", "List1=Multiple3", "checkBox2=check2", "radioButton1=radio1"]
it is in the form of,
["name=value","name=value"....]

Categories