Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery returns a wrong value using id selector

Tags:

jquery

php

i think i'm slowly drifting into insanity. in my code i have

<script>
     console.debug("1) <?=$_SESSION["searchEndDate"]?>");
     console.debug("2) " + $("#searchEndDate").val()); //if another element would exist with that it, it would give me that elements value here
</script>

<input type="text" class="dateInput" id="searchEndDate" value="<?=$_SESSION["searchEndDate"]?>" />

<script>
     console.debug("3) " + $("#searchEndDate").val());
     console.debug("4) <?=$_SESSION["searchEndDate"]?>"); // just to be sure it wasn't interfered anywhere
</script>

the console output weirdly says

1) 03.05.2015 //correct
2) undefined //correct (no other elements with the same id)
3) 01.05.2015 //wait...what?
4) 03.05.2015 //still correct, session was not interfered

...if i view the html source of the page, the value element clearly contains the correct value. still the debug contains the wrong value...when i initialize a datepicker later on in the code, the datepicker will have the wrong date. i'm genuinely confused...

what do i miss?


[EDIT]: Yes, i'm aware that the actual initialisation of the datepickers will have to be in the document ready function. but that's not the point! please read questions troughly before answering!

[EDIT 2]: used jQuery:

jQuery core 1.10.2
jQuery ui 1.10.4
jQuery mobile 1.4.5
like image 401
Mr.Manhattan Avatar asked Jun 20 '26 14:06

Mr.Manhattan


1 Answers

Ok I have following code up and running on my localhost:

<?php
session_start();

$_SESSION['searchEndDate'] = '03.05.2015';
?>

<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>

<script>
     console.debug("1) <?=$_SESSION["searchEndDate"]?>");
     console.debug("2) " + $("#searchEndDate").val()); //if another element would exist with that it, it would give me that elements value here
</script>

<input type="text" class="dateInput" id="searchEndDate" value="<?=$_SESSION["searchEndDate"]?>" />

<script>
     console.debug("3) " + $("#searchEndDate").val());
     console.debug("4) <?=$_SESSION["searchEndDate"]?>"); // just to be sure it wasn't interfered anywhere
</script>

And my console output is like this:

1) 03.05.2015
2) undefined
3) 03.05.2015
4) 03.05.2015

Maybe there is problem with your browser history, trying to autocomplete input fields it knows? Try something like - http://www.w3schools.com/tags/att_input_autocomplete.asp

like image 174
Pirozek Avatar answered Jun 22 '26 06:06

Pirozek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!