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

时间:2018-08-03 14:19:09

标签: jquery forms button

我有一个带有字段的表单,可以在其中粘贴图像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类的按钮时,警报框将显示“未定义”错误。

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

任何帮助都很好

谢谢

2 个答案:

答案 0 :(得分:1)

由于您的图片网址输入具有id属性,您可以使用否吗?

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

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

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

答案 1 :(得分:1)

next()和prev()函数用于 “获得匹配的元素集中每个元素的紧随其后的同级元素。如果提供了选择器,则只有与该选择器匹配时,它才会检索下一个同级元素”。

Source

在您的情况下,您要获取的元素不是$('。imgurlview')的同级元素。 这就是为什么它给您未定义的原因。

按照Sean T的建议,您可以使用元素“ ArticleFeaturedImageURL”的ID来获取该元素的值。