获取隐藏的第一个输入类型

时间:2016-12-27 08:59:01

标签: javascript jquery

我有这张桌子

        <tbody>
            @foreach($users as $user)
                <tr>
                    <input type='hidden' value='{{$user->username}}' />
                    <td><div contenteditable="true" class='contenteditable'>{{$user->username}}</div><div class='result'></div></td>
                    <td><div contenteditable="true" class='contenteditable'>{{$user->email}}</div><div class='result'></div></td>
                    <td>
                        <select class='form-control'>
                        @foreach($permissions as $permission)
                            @if($permission->id == $user->permission)
                                <option style='color:red' selected='true'>{{$permission->permission_name}}</option>
                            @else
                                <option>{{$permission->permission_name}}</option>
                            @endif
                        @endforeach
                        </select>
                    </td>
                    <td><div contenteditable="true" class='contenteditable'>{{$user->phone}}</div><div class='result'></div></td>
                    <td>
                        <select class='form-control'>
                        @foreach($divisions as $division)
                            @if($division->id == $user->division)
                                <option style='color:red' selected='true'>{{$division->division_name}}</option>
                            @else
                                <option>{{$division->division_name}}</option>
                            @endif
                        @endforeach
                        </select>
                        <div class='result'></div>
                    </td>
                    <td>
                        <button class='btn btn-success'>عرض</button>
                        <button class='btn btn-info'>تعديل</button>
                        <button class='btn btn-danger'>حذف</button>
                    </td>
                </tr>
            @endforeach
        </tbody>

我有这个js函数来获取像这样的输入类型隐藏值

$(".contenteditable").keyup(function(){
   var result = document.activeElement;
   var result = result.parentNode.firstChild;
   console.log(result);
 })

我需要的是javascript或jquery代码,当我键入contenteditable div我得到第一个值

<input type='hidden' value='{{$user->username}}' />

1 个答案:

答案 0 :(得分:4)

您应该使用.closest()遍历tr元素,然后使用.find():first选择器来定位:hidden元素

$(".contenteditable").keyup(function(){
   var result = $(this).closest('tr').find('[type="hidden"]:first').val();
   console.log(result);
});

注意:tr只能将tdth作为子元素。所以<input>应该是其中任何一个的孩子