Question

I'm new to HTML. Exactly do I use the "name" attribute? For example, if I make two buttons

<button
    type="button"
    name="startbtn"
    onclick = start()
>
    Start
</button>

<button
    type="button"
    name="End"
>
    End
</button>

and I give them the "name" attributes presumably to differentiate between them, but how do I use the "name" tags later?

Was it helpful?

Solution

HTML elements are found/searched by their attributes in DOM tree. The HTML elements can be searched by attributes, element type, index, position, parent, child, sibling, XPath and many other ways also. Some common HTML element's attribute are Id, *Name, Class, and type. You need to use these attributes while working with either a client-side script (like JavaScript, etc.) or server side script (like PHP, etc.).

Let’s say in JavaScript, if you want to invoke the click of your start button, you can do like this. Find the element and invoke the click method of that element - document.getElementByName('startbtn').click().

In server-side scripts, when form is submitted - values of form elements are accessed by elements' name. Suppose you have a form with four input fields like name, qualification, hobbies, skill. And you want to save it in database. When you submit this form, your given value can be retrieved by the element's name.

A PHP example here

$_POST['name'] - you can access the value given to the name box in a PHP script.

$_POST['qualification']
$_POST['hobbies']
$_POST['skill']

In the same way you can access others' values in your script.

OTHER TIPS

Try this:

<input type="button" name="start" value="start" />
<input type="button" name="end" value="end" />

To retrieve these values by name:

document.getElementsByName("start")[0].value
document.getElementsByName("end")[0].value
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top