jQuery <input> select input element by name

Description

jQuery <input> select input element by name

View in separate window

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Select an Element with its Name Attribute in jQuery</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
    // Select and style elements on click of the button
    $("button").click(function(){
        // Select inputs whose name attribute value ends with '_name'
        $('input[name$="_name"]').css("border-color", "lime");

        // Select input which name attribute value is exactly 'email'
        $('input[name="email"]').css("border-color", "blue");

        // Select inputs whose name attribute value starts with 'zip'
        $('input[name^="zip"]').css("border-color", "red");
    });/*  w  w w.  j  a va2 s.  com*/
});
</script>
</head>
<body>
    <form>
        <p><label>First Name: <input type="text" name="first_name"></label><p>
        <p><label>Last Name: <input type="text" name="last_name"></label><p>
        <p><label>Email Address: <input type="text" name="email"></label><p>
        <p><label>Zip Code: <input type="text" name="zip_code"></label><p>
        <button type="button">Style Inputs</button>
    </form>
</body>
</html>



PreviousNext

Related