MikeT MikeT - 4 years ago 262
jQuery Question

JQuery $(this).find(Selector) returning this

I have a form defined as this

<form name="NewForm">
<td hidden>New</td>
<td><input name="name" type="text"></td>
<td><input name="url" type="url"></td>
<td><input type="submit" value="New"></td>
<td><input type="reset" value="Cancel"></td>
</form>


on submit i call

function submitForm(event,data)
{
console.log($(this));


var valid = true;
var changed = false

var input = $(this).find("input[name='name']");

console.log("Name");
console.log(input);
console.log(input.val());
console.log(input.prop( 'defaultValue' ));
}


the console then reports

Object { 0: <form>, context: <form>, length: 1 }
Name
Object { length: 0, prevObject: Object, context: <form>, selector: "input[name='name']" }
undefined
undefined


why am i not selecting the first input on the form called name?

EDIT: Entire code file

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>

<body>
<div>
<select id="SystemActive">
<option value="Y">Active</option>
<option value="N">Deleted</option>
</select>
<button id="SystemRefresh">Refresh</button><br>
<table id="SystemTable" class="resultsGrid">
<thead>
<tr>
<th hidden>ID</th>
<th>Name</th>
<th>URL</th>
</tr>
<tr >
<form name="NewForm">
<td hidden>New</td>
<td><input name="name" type="text"></input></td>
<td><input name="url" type="url"></input></td>
<td><input type="submit" value="New"></input></td>
<td><input type="reset" value="Cancel"></input></td>
</form>
</tr>
</thead>
</table>
</div>
<script>
$(function() {
$("form").submit(submitForm)
});

function submitForm(event,data)
{
console.log($(event.target));


var valid = true;
var changed = false

var input = $(this).find("input[name=name]");
console.log("Name");
console.log(input);
console.log($(input).val());
input = $(this).find("input[name='name']");
console.log("Name2");
console.log(input);
console.log($(input).val());
input = $(this).find("input[name='name']");
console.log("Name3");
console.log(input.attr('name'));

event.preventDefault();
return false;
}

</script>

</html>

Answer Source

The problem is because form is not a valid child of a tr tag. Only td or th can be a child of a tr tag. The browser tries to repair your broken HTML and does so incorrectly (as to what you originally intended), which is why the code isn't working as expected.

Either move your form tag outside the table element, or nest it inside a td

Just right click and inspect your submit element and you'll see the browser has repaired your form tag to be an element with no children.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download