How to select specific form element in jQuery?

前端 未结 5 1512
清歌不尽
清歌不尽 2020-11-30 20:47

I have two form like this:

<
相关标签:
5条回答
  • 2020-11-30 21:05

    It isn't valid to have the same ID twice, that's why #name only finds the first one.

    You can try:

    $("#form2 input").val('Hello World!');
    

    Or,

    $("#form2 input[name=name]").val('Hello World!');
    

    If you're stuck with an invalid page and want to select all #names, you can use the attribute selector on the id:

    $("input[id=name]").val('Hello World!');
    
    0 讨论(0)
  • 2020-11-30 21:10

    although it is invalid html but you can use selector context to limit your selector in your case it would be like :

    $("input[name='name']" , "#form2").val("Hello World! ");

    http://api.jquery.com/jquery/#selector-context

    0 讨论(0)
  • 2020-11-30 21:11

    I prefer an id descendant selector of your #form2, like this:

    $("#form2 #name").val("Hello World!");
    

    http://api.jquery.com/descendant-selector/

    0 讨论(0)
  • 2020-11-30 21:14
    $("#name", '#form2').val("Hello World")
    
    0 讨论(0)
  • 2020-11-30 21:21

    I know the question is about setting a input but just in case if you want to set a combobox then (I search net for it and didn't find anything and this place seems a right place to guide others)

    If you had a form with ID attribute set (e.g. frm1) and you wanted to set a specific specific combobox, with no ID set but name attribute set (e.g. district); then use

    $("#frm1 select[name='district'] option[value='NWFP']").attr('selected', true);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <form id="frm1">
            <select name="district">
                <option value="" disabled="" selected="" hidden="">Area ...</option>
                <option value="NWFP">NWFP</option>
                <option value="FATA">FATA</option>
            </select>
        </form>

    0 讨论(0)
提交回复
热议问题