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

3
  • 1 way to "shorten" it would be to not to return json from the server, but the entire <form>, and just simply replace that. Commented Dec 2, 2013 at 10:32
  • Start by fixing your markup (you're using same ids twice). Commented Dec 2, 2013 at 10:37
  • HTML element IDs have to be unique: programmers.stackexchange.com/a/127180 Commented Dec 2, 2013 at 10:40

6 Answers 6

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/

Sign up to request clarification or add additional context in comments.

4 Comments

Nice sulution, but when i got new datas from ajax, old variables don`t changes, if old data isset..
When i call ajax post, old datas is: <p id="address">Address:<var>Test Street 999 2324233</var></p>. If in data array address field is empty, old html does`nt hide..
Yes, sorry, I deleted my comment because after posting it I realised what you meant. Answer updated.
"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..
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.

2 Comments

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?
If only you're not developing for your own fun. In that case jedi stuff is OK.
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/

1 Comment

"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).
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?

Comments

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

Comments

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.

Comments

Your Answer

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.