user4431269
user4431269

Reputation:

shorthand javascript ? for making vars?

Is there a bether way to do this ? i try serval things, but this one is the only that works for me

var naam = $("#resvNaam").val();
var aantal = $("#resvAantal").val();
var uur = $("#resvUur").val();
var datum = $("#resvDatum").val();
var telefoon = $("#resvTelefoon").val();
var opmerking = $("#resvOpmerking").val();
var alles = "?naam=" + naam + "&aantal=" + aantal + "&uur=" + uur + "&datum=" + datum + "&telefoon=" + telefoon + "&opmerking=" + opmerking;

Upvotes: 2

Views: 88

Answers (1)

elclanrs
elclanrs

Reputation: 94131

You can put all the ids in an array, then use map:

var ids = [
  'naam',
  'aantal',
  ...
]

var ucfirst = function(x) {
  return x[0].toUpperCase() + x.slice(1)
}

var alles = '?'+ ids
  .map(function(id) {
    var value = encodeURIComponent($('#resv'+ ucfirst(id)).val())
    return id +'='+ value
  })
  .join('&')

I would suggest using the same id or name for the field and the query, so it is easier to manipulate, and write less code.

As suggested in the comments, if you use names it would be easier to serialize the form with jQuery using http://api.jquery.com/serialize/

Upvotes: 2

Related Questions