0

Learning jquery, in chrome console created form:

var $form1 = $("<form/>", { id: 'form1' });
$div1.append($form1);

Then tried to access the fields during form submission: This works:

$('#form1').submit(function(e) {
    e.preventDefault();
    $('#form1 input, #form1 select').each(function(index){
        var input = $(this);
        console.log('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
    });
});
Output: Type: textName: name1Value: hello world Type: submitName: submit1Value: submit

But this does not:

$($form1).submit(function(e) {
    e.preventDefault();
    $($form1).each(function(index){
        var input = $(this);
        console.log('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
    });
});
Output: Type: undefinedName: undefinedValue:

How do I access the form fields using the variable $form1 instead of the actual element #form1?

Thanks for answer.

2
  • You are not eaching the inputs Commented Sep 24, 2017 at 19:28
  • How do I get access to the inputs? I tried $form1.children but that results in exception. Commented Sep 24, 2017 at 19:44

1 Answer 1

2

You can use children with selector to filter needed ones.

var $div1 = $('body');
var $form1 = $("<form>", { id: 'form1' });
$div1.append($form1);

$form1.append('<input name="test" type="text"/> <input value="go" name="whattodo" type="submit" />');


$($form1).submit(function(e) {
    e.preventDefault();
    $form1.children('input').each(function(index){
        var input = $(this);
        console.log('Type: ' + input.attr('type') + ' Name: ' + input.attr('name') + ' Value: ' + input.val());
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.