首页 > 解决方案 > 通过单击输入字段附近的按钮来发现输入字段 ID / 名称值的 JQuery 解决方案

问题描述

我有一个带有字段的表单,我可以在其中粘贴图像 URL 和右侧的按钮,单击该按钮将获取字段输入值并打开一个窗口以预览图片 url。

这是 HTML 部分

    <!-- Article Featured Image URL -->
    <div class="form-group">
      <label class="col-md-2 control-label" for="ArticleFeaturedImageURL">Featured Image URL</label>  
      <div class="col-md-6">
      <div class="input-group">  
          <input id="ArticleFeaturedImageURL" name="ArticleFeaturedImageURL" maxlength="250" placeholder="Write an Image URL" class="form-control input-md" type="url" pattern="https?://.+" value="">
        <span class="input-group-btn">
            <button type="button" class="btn btn-primary"><span class="glyphicon glyphicon-search" aria-hidden="true" onclick="openCustomRoxy2();"></span></button>
            <button type="button" class="imgurlview  btn btn-primary"><span class="glyphicon glyphicon-eye-open" aria-hidden="true"></span></button>
        </span>
      </div>
      <span class="help-block">A featured image represent the contents, mood, or theme of a post and will be used to create the <b>Thumbnail</b>. If not specified will be used the first image present in the article (if is available). Use full URL starting with <b>http://</b> or <b>https://</b></span>    
      </div>
    </div>  

我使用像这样的jquery:

$('.imgurlview').click(function(){
        alert($(this).prev('input').attr('id'));
});

我尝试获取字段 ID,然后用它来打开窗口或做其他事情。但是,当我单击带有 imgurlview 类的按钮时,警报框会显示“未定义”错误。

可能是一件愚蠢且容易修复的事情,但我还没有找到在每个按钮中使用 imgurlview 类的方法,我想找出附近的输入字段名称/id 值。

任何帮助都会很好

谢谢

标签: jqueryformsbutton

解决方案


由于您的图像 url 输入具有 id 属性,您可以使用它吗?

$('.imgurlview').click(function(){
    var url = $('#ArticleFeaturedImageURL').val()
});

如果出于某种原因您不知道 id 将是什么,并假设 html 结构始终相同...

$('.imgurlview').click(function(){
    var id = $(this).closest('.input-group').find('input').first().attr('id');
});

推荐阅读