Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use querySelector on to pick an input element by name?

Tags:

javascript

I recently received help on this site towards using querySelector on a form input such as select but as soon as I took <select> out it completely changed what had to be done in the function.

HTML:

<form onsubmit="return checkForm()">     Password: <input type="text" name="pwd">     <input type="submit" value="Submit"> </form> 

Javascript:

<script language="Javascript" type="text/javascript">     debugger;     function checkForm() {         var form = document.forms[0];         var selectElement = form.querySelector('');         var selectedValue = selectElement.value;          alert(selectedValue); </script> 

Before, I had ('select') for the querySelector, but now I'm unsure what to put there.
I've tried multiple things as well as querySelectorAll but I can't seem to figure it out.

To be clear I'm trying to pull the name="pwd".

How could I do this?

like image 210
Anthony Tobuscus Avatar asked Mar 01 '13 01:03

Anthony Tobuscus


People also ask

How do I select an element with querySelector?

The querySelector() method in HTML is used to return the first element that matches a specified CSS selector(s) in the document. Note: The querySelector() method only returns the first element that matches the specified selectors. To return all the matches, use the querySelectorAll() method.

How do I get the value of a querySelector element?

Use document. querySelector('selector') to Get Input Value in JavaScript. The document. querySelector('selector') uses CSS selectors which means, it can select elements by id, class, tag name, and name property of the DOM element.

How do I use querySelector with data attribute?

Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document. Here is the HTML for the examples in this article.


1 Answers

You can try 'input[name="pwd"]':

function checkForm(){      var form = document.forms[0];      var selectElement = form.querySelector('input[name="pwd"]');      var selectedValue = selectElement.value; } 

take a look a this http://jsfiddle.net/2ZL4G/1/

like image 77
AlexCheuk Avatar answered Sep 23 '22 02:09

AlexCheuk