0

Hy guys. Any idea what could be wrong with that code:

$IDuporabnikakijeobiskopravil = document.forms["referentpodatki"].elements["id_uporabnika_ki_je_opravil_obisk"].value
$("#IDuporabnik option[value='$IDuporabnikakijeobiskopravil']:first").attr("selected", true);

It must be something with variable. If I use only second part like this:

$IDuporabnikakijeobiskopravil = document.forms["referentpodatki"].elements["id_uporabnika_ki_je_opravil_obisk"].value
$("#IDuporabnik option[value='37']:first").attr("selected", true);

It works. But no of this options resolved my problem:

$IDuporabnikakijeobiskopravil = "37"
$IDuporabnikakijeobiskopravil = 37
$IDuporabnikakijeobiskopravil = '37'
$("#IDuporabnik option[value='{$IDuporabnikakijeobiskopravil}']:first").attr("selected", true);
var IDuporabnikakijeobiskopravil =  .... 

Any help on this one would be much appriciated. THANK YOU!

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 2
    JavaScript does **not** interpolate strings, you have to do string concatenation. – Felix Kling Jul 22 '12 at 15:55
  • Make it $("#IDuporabnik option[value='" + $IDuporabnikakijeobiskopravil + "']:first").attr("selected", true); – TJ- Jul 22 '12 at 15:56
  • possible duplicate of [How to use javascript variables in jquery selectors](http://stackoverflow.com/questions/5891840/how-to-use-javascript-variables-in-jquery-selectors) – Felix Kling Jul 22 '12 at 15:56
  • You're using PHP syntax. It doesn't work in JavaScript. – JJJ Jul 22 '12 at 15:56
  • JavaScript isn't PHP, use `+` to concatenate. Also, you should use `prop` there, not `attr`. – Ry- Jul 22 '12 at 15:57

1 Answers1

1

Try like this:

$IDuporabnikakijeobiskopravil = document.forms["referentpodatki"].elements["id_uporabnika_ki_je_opravil_obisk"].value;
$("#IDuporabnik option[value='"+$IDuporabnikakijeobiskopravil+"']:first").prop("selected", true);
Engineer
  • 47,849
  • 12
  • 88
  • 91
  • THANK YOU ALL! I used this, but there was a small mistake. Correct is: $IDuporabnikakijeobiskopravil = document.forms["referentpodatki"].elements["id_uporabnika_ki_je_opravil_obisk"].value; $("#IDuporabnik option[value='"+$IDuporabnikakijeobiskopravil+"']:first").attr("selected", true); notice .prop() and .attr(). It works now. Thank you again! – Nejc Draganjec Jul 22 '12 at 16:12
  • @NejcDraganjec So what have you used `prop` or `attr`? And what jQuery version do you use? If `prop` does not work for you, than your jQuery is too old. – Engineer Jul 22 '12 at 16:14
  • I used attr. And have jQuery v1.7.2. Isn't that pretty new :)? Should I do upgrade? – Nejc Draganjec Jul 22 '12 at 16:17