开发者

JQuery/Javascript set value of form field with generated ID

On my page I have many forms, in witch field ids are generated based on DB id. like this:

            <input type="hidden" name="id" value="<?php echo (isset($content))?$content->getId():''?>" />
            <input type="hidden" id="x<?php echo $content->getId()?>"/>
            <input type=开发者_如何转开发"hidden" id="y<?php echo $content->getId()?>"/>
            <input type="hidden" id="x2<?php echo $content->getId()?>"/>
            <input type="hidden" id="y2<?php echo $content->getId()?>"/>

That gives me unique ids for all forms. Now I have Javascript function in jquery framework that sets vale of specified field that doesnt work:

            $(function(){
                $('#jcrop_target_id<?php echo $content->getId()?>').Jcrop({
                    onSelect: updateCoords
                });
            });

            function updateCoords(c)
            {
                $('#x<?php echo $content->getId()?>').val(c.x);
                $('#y<?php echo $content->getId()?>').val(c.y);
                $('#x2<?php echo $content->getId()?>').val(c.x2);
                $('#y2<?php echo $content->getId()?>').val(c.y2);
            };

Values c.* are OK, but obviously #x<?php echo $content->getId()?> doesn't work. What is the proper way to do it? Regards.


Attempting to mix php and javascript can be pretty difficult. The reason for this is that they are not processed at the same time, or in the same way. PHP gets processed first on the server and the results of that process are sent to the browser. Then any javascript is processed.

Additionally, I don't think that php tags inside of javascript will actually be processed, but I'm not 100% certain about this.

One thing that you can do (but often looks pretty ugly) is to use php to actually create your javascript. For example:

echo '<script type="text/javascript">';
echo 'function updateCoords(c) {';
echo '    $(\'#x' . $content->getId() . '\').val(c.x);';
...
echo '}';
echo '</script>';

Like I said, it looks pretty ugly so I don't really recommend it, but it should actually work like you want.


I've always set the onChange event too. Does this help?

$('#jcrop_target_id<?php echo $content->getId()?>').Jcrop({
    onSelect: updateCoords,
    onChange: updateCoords
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜