单击标签更改输入属性

时间:2016-07-18 12:24:42

标签: javascript jquery html

我需要什么:

如果我点击标签,我想在输入中添加一个选中的内容。

当我尝试它时,我收到了两个警告。这是不正确的,在firebug中输入字段不会改变。

对于测试,我想输出filterguid但是警报是空的,并且还有两个警告框。

HTML标记:

<li>
 <label>
  <input type="checkbox" filterguid="895f7bc2-d609-4b09-97f9-c09f9fc90d1b"> Weiblich
  </label>
</li>

jQuery的:

$('.targetgroup-frame li label').on('click', function(){
   $(this).children().prop('checked', true);
    alert($(this).children().prop('filterguid'));
});

我的jQuery代码是否正确?

谢谢。

2 个答案:

答案 0 :(得分:1)

HTML - 除了在输入上添加id以便于jquery-targeting之外,没有任何更改。

function hoverTest
  % create a figure (units normalized makes updating the position easier in the callback
  f = figure ( 'units', 'normalized' );
  % create an axes
  ax = axes ( 'parent', f );
  % load some data for plotting
  c = load ( 'clown' );
  % plot the data
  image ( c.X, 'parent', ax );
  % create a uipanel to host the text we will display
  uip = uipanel ( 'parent', f, 'position', [0 0 0.18 0.05], 'visible', 'off' );
  % create a text control to display the image info
  txt = uicontrol ( 'style', 'edit', 'parent', uip, 'units', 'normalized', 'position', [0 0 1 1] );
  % assign the callback for when the mouse moves
  f.WindowButtonMotionFcn =  @(obj,event)updateInfo(f,uip,ax,txt,c.X);
end
function updateInfo ( f, uip, ax, txt,img )
  % update the position of the uipanel - based on the current figure point (normalized units)
  set ( uip, 'Position', [f.CurrentPoint uip.Position(3:4)] );
  % Check to see if the figure is over the axes (if not hide)
  if ax.CurrentPoint(1,1) < min(ax.XLim) || ...
     ax.CurrentPoint(1,1) > max(ax.XLim) || ...
     ax.CurrentPoint(1,2) < min(ax.YLim) || ...
     ax.CurrentPoint(1,2) > max(ax.YLim)
   uip.Visible = 'off';
  else
    % show the panel
    uip.Visible = 'on';
    % get the current point
    cp = round(ax.CurrentPoint);
    % update the text string of the uicontrol
    txt.String = sprintf ( 'img(%i,%i) = %i', cp(1,1), cp(1,2), img(cp(1,2),cp(1,1) ) );
  end

end

您不必使用jquery来更改复选框的状态,因为html会为您执行此操作。

您可以使用以下脚本侦听更改并获取已检查状态和filterguid。

<li>
    <label>
        <input type="checkbox" id="checkbox" filterguid="895f7bc2-d609-4b09-97f9-c09f9fc90d1b"> Weiblich
    </label>
</li>

答案 1 :(得分:-2)

属性

的标签
  

与标签元素在同一文档中的可标记表单相关元素的ID。文档中第一个具有与for属性值匹配的ID的元素是此label元素的标记控件。

此外,您应该data-attribute而不是attribute。 HTM5不支持attribute

示例

&#13;
&#13;
$("#chkTest").on("click", function(){
  console.log($(this).data("filterguid"))
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<label for="chkTest">
  <input id="chkTest" type="checkbox" data-filterguid="895f7bc2-d609-4b09-97f9-c09f9fc90d1b">Weiblich
</label>
&#13;
&#13;
&#13;

参考

相关问题