1

There is my code:

$.ajax({
 url: "?module=gestionApplication&action=importScenario&fichierconf="+$fichierconf,
 dataType: "json",
 success: function( data ) {
 $( "#dialog-scenario input#fichierxml" ).val( data.FICHIERXML );
 $( "#dialog-scenario input#fichierproxy" ).val( data.FICHIERPROXY );
 $( "#dialog-scenario select#portail" ).val( data.PORTAIL );
 $( "#dialog-scenario select#typemaj" ).val( data.MONITORING );
 $( "#dialog-scenario input#periodemaintenance" ).val( data.MAINT );
 $( "#dialog-scenario input#nomdns" ).val( data.DNSATESTER );

It works well, but i got like 40 lines of the same type is it possible to do the same action without knowing the string after data. ?

I would do something like

data.each( function(dataName) {
 $( "#dialog-scenario inputORselect#"+dataName ).val( data.dataname );
});

Thx for your help

asked Aug 16, 2012 at 9:17

4 Answers 4

1

Create a map between the name of the element and the data property:

var map,
 prop;
map = {
 "typemaj" : "MONITORING",
 "periodemaintenance" : "MAINT"
}

Then you can loop through the properties to set their values.

for( prop in map ) {
 $( "#dialog-scenario inputORselect#" + prop ).val( data[ map[prop] ] );
}
answered Aug 16, 2012 at 9:35
Sign up to request clarification or add additional context in comments.

1 Comment

I keep forgetting about maps in favour of $.each this is probably more efficient. Nice solution Bruno.
1
$.each(data, function(key, value) {
 // do your processing here
});
answered Aug 16, 2012 at 9:21

Comments

1

You're almost there, keep in mind that an id is always unique and doesn't need information about it's parent.

$.each(data, function(name, value) {
 $("#"+name.toLowerCase()).val(value);
});
answered Aug 16, 2012 at 9:21

Comments

0
success: function( data ) {
 $.each(data, function(i, dataName) {
 $( "#dialog-scenario inputORselect#"+dataName ).val( data.dataname );
 });
}
answered Aug 16, 2012 at 9:21

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.