I have a page with a form in which:
$('form').find('input[type=submit]')
gives [undefined]
$('form input[type=submit]')
works as expected... Is it normal?
Both works properly
console.log($('form').find('input[type=submit]').val()); console.log($('form input[type=submit]').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <input type="submit" value="somevalue" /> </form>
You should show more code, but if you are getting undefined
you may not have actually loaded the jQuery library.
If you are on Windows desktop, your browser probably has Developer Tools (usually F12) that you can use to view the JavaScript console and to debug (step through) your code as it executes.
The return value of a jQuery selector is an array, and typically to verify whether you selected a single element you need only check the length of this array (assuming that jQuery is loaded correctly, which you can test by typing jQuery
into the console which should show function(a,b){...}
or similar, as opposed to throwing an exception about an undefined reference).
To test these examples, open your JavaScript / Dev Tools console first, then click Run Snippet
WORKING CODE (jQuery is loaded)
var $elem = $("form input[type='submit']"); if ($elem.length === 1) { if (console) console.log("found the element"); } else { if (console) console.log("did not find the element (could inject it, or log error, etc.)"); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <input type='submit' value='Submit form' /> </form>
NON-WORKING CODE (jQuery is NOT loaded)
try { var $elem = $("form input[type='submit']"); if ($elem.length === 1) { if (console) console.log("found the element"); } else { if (console) console.log("did not find the element (could inject it, or log error, etc.)"); } } catch (ex) { if(console)console.log(ex.message); }
<form> <input type='submit' value='Submit form' /> </form>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.