1

Hi I am using selenium webdriver where I try to execute jQuery script by passing java variable to access valid id.

here is the code.

int move = 3;
String date = "2011-03-05";
String script = "$('#date_of_birth-'+move+).datepicker('update', '+date+')";
js.executeAsyncScript(script, 1000);

I want to use both move and date variable inside jQuery function.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
Exteam
  • 63
  • 7
  • 2
    Hi, what is the source of your confusion? It seems like you are unable to concatenate strings in Java. If that's the case, have a look at this Q&A: https://stackoverflow.com/questions/3753869/how-do-i-concatenate-two-strings-in-java – Erwin Bolwidt Aug 13 '18 at 03:28

3 Answers3

1

If you want the string concatenation to take place within Java itself, then it has to happen outside of the intended JavaScript string. What you are currently doing is to intercalate the literal strings move and date inside your JavaScript string.

String script = "$('#date_of_birth-'" + move + "').datepicker('update', '" + date + "')";

But, we can use a StringBuilder here which would make things easier to read (and possibly run faster):

StringBuilder sb = new StringBuilder("");
sb.append("$('#date_of_birth-'");
sb.append(move);
sb.append("').datepicker('update', '");
sb.append(date);
sb.append("')");
String script = sb.toString();
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • still not working :( the script is working without passing java variables `String script = "$('#date_of_birth-1').datepicker('update', '2018-08-15')";` but when I pass variables nothing update on datepicker. – Exteam Aug 13 '18 at 03:55
  • you edit your answer but it still not working test on your system. – Exteam Aug 13 '18 at 14:39
0

Can you try below snippet in your application which may works i guess:-

Exsisting problem: $('#date_of_birth-'3).datepicker('update', '2011-03-05');

Current solution: $('#date_of_birth-3').datepicker('update', '2011-03-05');

snippet: int move = 3; String date = "2011-03-05";

    String scripting = "$('#date_of_birth-" + move + "').datepicker('update', '" + date + "')";

    System.out.println(scripting);

    StringBuilder sb1 = new StringBuilder("");
    sb1.append("$('#date_of_birth-");
    sb1.append(move+"'");

    sb1.append(").datepicker('update', '");
    sb1.append(date);
    sb1.append("')");

    String script1 = sb1.toString();
    System.out.println(script1);
-1

After long struggles and debugging I found the solution.

here is the right way to pass java variable to jQuery function.

String script = "$('#date_of_birth-" + move + "').datepicker('update', '" + date + "')";
Exteam
  • 63
  • 7