0

LF way to short my js/jquery function:

$.ajax({ // Start ajax post
..........
success:    function (data) { // on Success statment start
..........
//1. Part
$('var#address').text(data.address);            
$('var#telephone').text(data.telephone);            
$('var#mobile').text(data.mobile);          
$('var#fax').text(data.fax);            
$('var#email').text(data.email);            
$('var#webpage').text(data.webpage);        

//2. Part
if (!data.address){ $('p#address').hide(); } else {  $('p#address').show(); }; 
if (!data.telephone){ $('p#telephone').hide(); } else {  $('p#telephone').show(); }; 
if (!data.mobile){ $('p#mobile').hide(); } else {  $('p#mobile').show(); }; 
if (!data.fax){ $('p#fax').hide(); } else {  $('p#fax').show(); }; 
if (!data.email){ $('p#email').hide(); } else {  $('p#email').show(); }; 
if (!data.webpage){ $('p#webpage').hide(); } else {  $('p#webpage').show(); }; 

}, End Ajax post success statement 

Here is my html:

<p id="address">Address:<var id="address">Test Street 999 2324233</var></p>
<p id="telephone">Telephone:<var id="telephone">+1 0000009</var></p>
<p id="mobile">Mobile:<var id="mobile">+1 0000009</var></p>
<p id="email">E-mail:<var id="email">info@example</var></p>
<p id="webpage">Web Page:<var id="webpage">www.example.com</var>/p>

How can we reduce the number of selector*(1. part)* and else if the amount (2. part)?

Kārlis Millers
  • 664
  • 2
  • 11
  • 29

6 Answers6

3

Assuming your object's property names exactly match the spelling of your element ids you can do this:

for (var k in data) {
    $('var#' + k).text(data[k]);
    $('p#' + k).toggle(!!data[k]);
}

...because .toggle() accepts a boolean to say whether to show or hide. Any properties that don't have a matching element id would have no effect.

Note: your html is invalid if you have multiple elements with the same ids, but it will still work because your selectors specify the tag and id. Still, it might be tidier to just remove the ids from the var elements:

<p id="address">Address:<var>Test Street 999 2324233</var></p>
<!-- etc. -->

With this JS:

$('#' + k).toggle(!!data[k]).find('var').text(data[k]);

And then adding some code to hide any elements that aren't in the returned data object:

$('var').parent('p').hide();

...and putting it all together:

$.ajax({
    // other ajax params here
    success : function(data) {
        $('var').parent('p').hide();
        for (var k in data) {
            $('#' + k).toggle(!!data[k]).find('var').text(data[k]);
        }
    }
});

Demo: http://jsfiddle.net/z98cw/1/

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • Nice sulution, but when i got new datas from ajax, old variables don`t changes, if old data isset.. – Kārlis Millers Dec 02 '13 at 10:54
  • When i call ajax post, old datas is:

    Address:Test Street 999 2324233

    . If in data array address field is empty, old html does`nt hide..
    – Kārlis Millers Dec 02 '13 at 11:09
  • Yes, sorry, I deleted my comment because after posting it I realised what you meant. Answer updated. – nnnnnn Dec 02 '13 at 11:11
  • "And then adding some code to hide any elements that aren't in the returned data object": In first time works, but if i do one more ajax post hided element doesnt go back.. – Kārlis Millers Dec 02 '13 at 11:32
1

As long as the properties of the object match the id attributes of the p tags you can iterate through the object using the property name as a selector. Also since id attributes are unique, refrain from prefixing the selector with var it is unnecessary.

var data = {
    address: "address",
    telephone: "telephone",
    mobile: "mobile",
    fax: "fax",
    email: "email",
    webpage: "webpage"
};

for(x in data){
    var elem = $("#" + x);
    if(elem.length == 1){
        elem.text(data[x]);
    }
}

JS Fiddle: http://jsfiddle.net/3uhx6/

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • _"Also since id attributes are unique"_ - They're supposed to be unique, but they're not in the OP's markup. Note that the `if(element.length==1)` test isn't needed, you can just say `$("#"+x).text(data[x])` (jQuery doesn't mind if no elements matched). – nnnnnn Dec 02 '13 at 10:45
1
["address", "telephone", "mobile", "fax", "email", "webpage"].map(
    function(key) { 
        if (data.hasOwnProperty(key) && !!data[key]) { 
            $('p#' + key).show(); 
        } else { 
            $('p#' + key).hide();
        } 
    });

But you should not.

birukaze
  • 376
  • 1
  • 12
  • Because "shorten da code" is not what you should be eager to achieve. You should be looking forward to code easy to read and understand, supporting generalized data processing, mapping, validation, etc. Why don't you really take a look at js templates? – birukaze Dec 02 '13 at 13:36
  • If only you're not developing for your own fun. In that case jedi stuff is OK. – birukaze Dec 02 '13 at 13:38
0

This is what templating systems are created for. If you insist on using jQuery there is a jQuery plugin: https://github.com/codepb/jquery-template

More: What Javascript Template Engines you recommend?

Community
  • 1
  • 1
Tomas Klingen
  • 141
  • 1
  • 5
0

I would use javascript templates for this (I've shortened the example a quite a bit, but you should get the gist).

First the template, I love Underscore.js for this so I gonna go ahead and use that.

<% if data.address %>
  <p id="address">Address: {%= Test Street 999 2324233 %}</p>

to compile this inside your success function

success: function(data) {
    //assuming data is a json that looks like this {'address':'my street'}
    var template = _.template(path_to_your_template, data);
    $('var#addresscontainer').html(template);
}
Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
0

Thanks for birukaze and nnnnnn:

With your advice came function;) :

                        for (var key in data) {
                        if (data.hasOwnProperty(key) && !!data[key]) { 
                            $('p#' + key).show().find('var').text(data[key]); 
                        } else { 
                            $('p#' + key).hide();
                        } 
                    };

Now i can avoid for selector with var.

Kārlis Millers
  • 664
  • 2
  • 11
  • 29