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
timmalos
5423 gold badges10 silver badges25 bronze badges
4 Answers 4
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
Bruno
5,8222 gold badges29 silver badges44 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
David Barker
I keep forgetting about maps in favour of
$.each this is probably more efficient. Nice solution Bruno.$.each(data, function(key, value) {
// do your processing here
});
answered Aug 16, 2012 at 9:21
David Barker
14.6k3 gold badges51 silver badges77 bronze badges
Comments
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
Sem
4,6895 gold badges37 silver badges53 bronze badges
Comments
success: function( data ) {
$.each(data, function(i, dataName) {
$( "#dialog-scenario inputORselect#"+dataName ).val( data.dataname );
});
}
answered Aug 16, 2012 at 9:21
frnhr
13k9 gold badges71 silver badges96 bronze badges
Comments
lang-js