简体   繁体   中英

Dynamically generated textfield not showing the value set by javascript

I have a dynamically generated textfield (using the following code):

echo "<div><table width='100%'><tr>
         <td>
             Date: <input type='text' class='span2' id='currDate'>
         </td><td rowspan='2'></td></tr></table>";

This field is generated once a user presses a button, this button links to a javascript:

$('#receipts button').live('click', function(){
        var id = this.id;
        $.ajax({
            type: "post", url: "receipt-stock.php", data: "production_detail_id="+id,
            success: function(data) {
                $('.modal-body').html(data);
                $('#new_receipt').modal('show');
                var myDate = new Date();
                var prettyDate = myDate.getDate()+'-' +(myDate.getMonth()+1)+'-'+myDate.getFullYear();
                $("#currDate").val(prettyDate);
                $('#currDate').datepicker({ dateFormat: 'dd-mm-yy' });
            }
        });
    });

As it can be seen from the javascript i am displaying a modal which contains the textfield from the code above. Everything works fine except the part where i am setting the value of #currDate to the current date, the textfield does not show anything nether it shows the date-picker when in focus.

However upon using alert i found that the textfield has the value i want, it just doesn't display it.

I think the problem is after you do .modal() , you have two elements with the id #currDate , which isn't valid HTML. Without seeing the entire page, it's hard to say for sure, but I've seen this problem quite a bit actually. jQuery will find the first ID, and that's the element that is getting your value set.

The exact fix is hard to say without seeing the rest of the code. You might try setting the value of the currDate element before you call .modal() . If there is a way to change currDate to a class or unique ID, that may help. Alternatively, you might be able to change the code you have to something like $('#new_reciept #currDate').val(prettyDate); .

As a previous poster says, it is the .datepicker() call that is blanking out the date. you can add a parameter defaultDate: new Date() that should allow you to remove the code above and give the results you desire.

Also, your input element is never closed <input type='text' class='span2' id='currDate' > should be <input type='text' class='span2' id='currDate' />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM