简体   繁体   English

如何将隐藏的表单元素值设置为单击元素的数据属性值

[英]How to set hidden form element value to data attribute value of clicked element

I would like to set the data attribute value of a clicked html element as the value of a hidden form field, using angularJS. 我想使用angularJS将单击的html元素的data属性值设置为隐藏表单字段的值。

I have a series of thumbnails to represent options in a form, and clicking one sets the value of a hidden form field to its data-val="something" value, essentially replicating the functionality of a select box. 我有一系列缩略图来表示表单中的选项,然后单击一个缩略图将隐藏表单字段的值设置为其data-val =“something”值,基本上复制了选择框的功能。

In Jquery i can do it like this: 在Jquery我可以这样做:

<script type="text/javascript">
    $(function(){
        $('#fakeselect li a').click(function(){
            event.preventDefault();
            var val = $(this).data('val');
            $('#hiddeninput').val(val);
        });
    });
</script>

<ul id="fakeselect">
        <li><a href="#" data-val=1><img....></a></li>
        <li><a href="#" data-val=2><img....></a></li>
        <li><a href="#" data-val=3><img....></a></li>
</ul>

<input type="text" name="hidden" id="hiddeninput" value="">

However i would like to do the same with angularJS, as it provides some other very usefull functionality. 但是我想对angularJS做同样的事情,因为它提供了一些非常有用的功能。

The HomePage of AngularJS shows how to do pretty much the oposite (bind an element attribute to a form field), but i cant quite work out how to do it the other way around. AngularJS的主页显示了如何做相当多的oposite(将一个元素属性绑定到一个表单字段),但我不知道如何以相反的方式做到这一点。

Try something lke: 尝试一下lke:

<ul id="fakeselect">
    <li><a ng-click="form.val=1"><img....></a></li>
    <li><a ng-click="form.val=2"><img....></a></li>
    ...
</ul>

<input type="text" name="hidden" id="hiddeninput" ng-model="form.val" />

And in the controller (make sure it applies to both the <ul> and the <input> ): 并在控制器中(确保它适用于<ul><input> ):

$scope.form = {
    val: null // OR ANY OTHER INITIAL VALUE
};

Try this: 尝试这个:

In HTML: 在HTML中:

<ul id="fakeselect">
    <li><a href="javascript:void(null);" ng-click="setValue(1)" ><img....></a></li>
    <li><a href="javascript:void(null);" ng-click="setValue(2)"><img....></a></li>
    <li><a href="javascript:void(null);" ng-click="setValue(3)"><img....></a></li>
</ul>

<input type="text" name="hidden" id="hiddeninput" value="" ng-model="hiddeninput">

In Controller: 在控制器中:

$scope.hiddeninput = '';
$scope.setValue = function(id) {
   $scope.hiddeninput = id;   
   //other stuff do here

}

See DEMO DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM