如果字段为空,我如何删除发送到隐藏字段的部分值并设置默认状态?



我正在制作一个图像上传和裁剪功能,以添加到用户表单。目前,用户点击改变头像按钮,它加载一个模态窗口,他们可以上传那里的图像和裁剪它。下面的jQuery获取头像的新img src,并将其传递给一个隐藏字段,以便将其发送到数据库。

jQuery的另一部分用于当用户返回用户页面时,它将化身的img src更改为显示在隐藏字段中的内容。

我需要做一些改变,首先我需要改变发送到隐藏字段的img src的url,目前它发送一切,即http://www.mywebsite.com/img/avatars/user41.png,我只希望它发送文件名,即user41.png

其次,我需要改变加载功能,所以它显示正确的图像,当用户回到那里的用户页面,路径到图像是在主站点配置文件定义如下,因为如果我做如上所述的更改,它将只有文件名的工作。

define( '_URL_AVATARS', '/img/avatars/' ); 

第三,我需要能够设置一个默认的图像,如果隐藏的头像字段是空白的-因为用户还没有上传任何东西。所以需要设置为defaultpicture。png

jQuery:

 $( document ).ready(function() {
 $(".avatar-view > img").attr('src' ,$("#avatar-val").val());   });
 $('button').click(function () {
 $("#avatar-val").val($(".avatar-view>img").prop('src'));     });
HTML:

<div class="avatar-view" title="" data-original-title="Change the avatar">
<button class="btn btn-primary btn-block avatar-save">Change Avatar</button> 
  <img src="http://www.mywebsite.com/img/avatars/user-41.png" alt="Avatar"></div>

<input name="avatar" value="http://www.mywebsite.com/img/avatars/user-41.png" id="avatar-val" type="hidden">
$('button').click(function () {
 var orig = $(".avatar-view>img").prop('src');
 var newVal = orig.replace(/^.*//g,''); // strip path and domain before storing
 $("#avatar-val").val(newVal); // capture the modified value
});
$(document).ready(function() {
  // set a default if necessary (assuming you've set the user's choice in #avatar-val, and that it will be empty or at least falsy if none was set:
  var myImage = $("#avatar-val").val() || "myDefaultImage.png";
  //included desired path in src. Probably better to use a config variable here rather than a hardcoded string, but you get the idea
  $(".avatar-view > img").attr('src' ,"/your/path/here/"+myImage);   
});

最新更新