Jquery get form field value

前端 未结 8 2113
醉酒成梦
醉酒成梦 2020-12-01 07:13

I am using a jquery template to dynamically generate multiple elements on the same page. Each element looks like this

相关标签:
8条回答
  • 2020-12-01 07:30

    It can be much simpler than what you are doing.

    HTML:

    <input id="myField" type="text" name="email"/>
    

    JavaScript:

    // getting the value
    var email = $("#myField").val();
    
    // setting the value
    $("#myField").val( "new value here" );
    
    0 讨论(0)
  • 2020-12-01 07:37

    You can get any input field value by $('input[fieldAttribute=value]').val()

    here is an example

    displayValue = () => {
    
      // you can get the value by name attribute like this
      
      console.log('value of firstname : ' + $('input[name=firstName]').val());
      
      // if there is the id as lastname
      
      console.log('value of lastname by id : ' + $('#lastName').val());
      
      // get value of carType from placeholder  
      console.log('value of carType from placeholder ' + $('input[placeholder=carType]').val());
    
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="formdiv">
        <form name="inpForm">
            <input type="text" name="firstName" placeholder='first name'/>
            <input type="text" name="lastName" id='lastName' placeholder='last name'/>
            
            <input type="text" placeholder="carType" />
            <input type="button" value="display value" onclick='displayValue()'/>
            
        </form>
    </div>

    0 讨论(0)
  • 2020-12-01 07:41
    var textValue = $("input[type=text]").val()
    

    this will get all values of all text boxes. You can use methods like children, firstchild, etc to hone in. Like by form $('form[name=form1] input[type=text]') Easier to use IDs for targeting elements but if it's purely dynamic you can get all input values then loop through then with JS.

    0 讨论(0)
  • 2020-12-01 07:44

    An alternative approach, without searching for the field html:

    var $form = $('#' + DynamicValueAssignedHere).find('form');
    var formData = $form.serializeArray();
    var myFieldName = 'FirstName';
    var myFieldFilter = function (field) {
      return field.name == myFieldName;
    }
    var value = formData.filter(myFieldFilter)[0].value;
    
    0 讨论(0)
  • 2020-12-01 07:46

    You have to use value attribute to get its value

    <input type="text" name="FirstName" value="First Name" />
    

    try -

    var text = $('#DynamicValueAssignedHere').find('input[name="FirstName"]').val();
    
    0 讨论(0)
  • 2020-12-01 07:47

    You can try these lines:

    $("#DynamicValueAssignedHere .formdiv form").contents().find("input[name='FirstName']").prevObject[1].value
    
    0 讨论(0)
提交回复
热议问题