JQuery select 表单对象属性根据name或id 选中选项和取值

             今天遇到的问题,选中表单中select的其中规定的一项,然后获取选中的值,规定终于搞定select中的属性为name,用id这个属性很快就实现功能,

用name去获取,之前没做过,这么写都不对,上网百度一下,终于搞定,作为笔记记录下来。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
 <title>My JSP 'formattributeselector_.jsp' starting page</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/script/jquery-1.7.2.js"></script>
<script type="text/javascript">
     $(function(){
     
         //根据下拉框根据 name属性选中,取值方法
          //var $item1 = $("select[name='test2'] option:eq(2)").attr("selected",true);
          var $item2 = $("select[name='test2']").find('option:eq(3)').attr('selected','selected');
         // var $province = $("select[name='test2'] option:eq(5)").val();
         //取值
         // var value1 = $item1.val();
          var $value2 = $item2.val();
          alert(value2);
         
         
         //根据id选中,取值 方法
          //var $select1 = $('#test2 option:eq(4)').attr('selected','selected');
         // var $select2 = $('#test2').find('option:eq(3)').attr('selected', true);
         // var $select3 =  $('#test2 option:eq(1)').val();
           //alert($select3);
     })

</script>
  </head>
  <body>
    <h3>表单对象属性过滤选择器</h3>
         
        <form id="form1" action="#">            下拉列表2: <br>
            <select name="test2">
                <option>浙江</option>
                <option>辽宁</option>
                <option>北京</option>
                <option>天津</option>
                <option>广州</option>
                <option>湖北</option>
            </select>
        </form>        
  </body>
</html>

猜你喜欢

转载自www.cnblogs.com/ksana/p/9236488.html