0

I want to append the values if they are not null to the link. It doesn't allow the if in the string, so what should i do instead?

    var age = $('#age').val();
    var fn = $('#fn').val();
    var ln = $('#ln').val();   
    var city = $('#city').val();
    var country = $('#country').val();

    var link = "https://mysre.com/articles/index.php?title=man-sets-biggest-pizza-record" if(age !=null){ "&age=" + age + } "&fn=" + fn + "&ln=" + ln + "&city=" + city + "&country=" + country;
0

5 Answers 5

2

Lacking the fields themselves, I wonder if this might not do what you're trying for.

 var myFields = {
   age: $("#age").val,
   fn : $("#fn").val,
   ln : $("#ln").val,
   city: $("#city").val(),
   country: $("#country").val()
  }

    var link = "https://mysre.com/articles/index.php?title=man-sets-biggest-pizza-record";
    
    $.each(myFields, function(key, value){
      if(value){
        link += "&"+key+"="+value;
      }
    }

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

2 Comments

Thanks all for your answers. I have gone with this option
You might need to edit the code solution above because as it stands you get ""message": "Uncaught SyntaxError: missing ) after argument list"..... Good Solution so Upvoted..
1

There are a number of ways to solve this.

The most obvious is just to build your link piece by piece.

var a = 1;
var b = null;
var c = 5;

var str = '';
if (a) {
  str += a + '&';
}

if (b) {
  str += b + '&';
}

// ... and so on

A much cleaner solution I prefer is to actually put everything into an array or object, then build your string from that.

var data = {
    a: 1,
    b: null,
    c: 5
};

var str = 'http://myarray.com/?' + 
  Object.keys(data)
    .filter(function (key) { return data[key] })
    .map(function (key) { return key + '=' + data[key] }).join('&');

Object.keys(data) will give you an array like ['a', 'b', 'c'] (the keys from the object).

filter() will go through and build a new array from any values that return a truthful value. In this case, the resulting array would be ['a', 'c'] ('b' got removed because it's value is null, which is a falsey value).

map() will then loop through each of those, and then build a new array from the returned value of each call. That would look like this: ['a=1', 'c=5'].

Finally, join('&') will join all the values in the array into one string: a=1&c=5, which we can just add to the rest of the string.

Another option would be to use ternary operators in the string (a ? a : ''), but this doesn't scale well with lots of values.

1 Comment

Nice solution, dude!
0

Use the ternary operator, it's as simple as (expression ? value if true : value if false)

Don't forget about Javascript's truthyness to keep your expression small!

You can also utilize a trick with truthy values to perform a null coalesce with var || default, where if var is falsy, default will be used (this can be chained to use a bunch of vars if you'd like)

Comments

0

One option is to use ternary if.

var age = $('#age').val();
var fn = $('#fn').val();
var ln = $('#ln').val();
var city = $('#city').val();
var country = $('#country').val();

var link = "https://mysre.com/articles/index.php?title=man-sets-biggest-penis-record" + (age != undefined ? "&age=" + age : '') + (fn != undefined ? "&fn=" + fn : '')  + (ln != undefined ? "&ln=" + ln : '') + (city != undefined ? "&city=" + city : '') + (country != undefined ? "&country=" + country : '');

console.log(link);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

2 Comments

Looks good, I don't want to pass the &age= through if it doesn't exist though
It's not passing if undefined. There are better solutions than mine though.
0

I would put all your potential values into an object, iterate the object pushing the querystring part to an array if the object value exists and is valid, then join the parts into a real querystring which you can then attach to your url:

var obj = {
  "age": $('#age').val(),
  "fn": $('#fn').val(),
  "ln": $('#ln').val(),
  "city": $('#city').val(),
  "country": $('#country').val()
};

var arr = [];
for (var k in obj) {
  if (obj[k] || obj[k] === 0) 
    arr.push(k + "=" + encodeURIComponent(obj[k]));
}

var url = "https://penisurl";

if (arr.length) {
  url += "?" + arr.join("&");
}

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.