4

I have a form that is structured similarly to the one below. How do I use CSS to style the input[type=submit] element when the input[type=text] is focused?

For example:

<form id="example">
    <input type="text" name="search">
    <input type="submit" value="Search">
</form>

<style>
    #example > input[type="text"]:focus {
        // please style input[type="submit"]
    }
</style>

I'm trying to accomplish this because a wordpress theme has a search form with the search input and submit button inline. When a user focuses on the input, I want the input field and submit button to have the same border color change.

Alternatively, I could style the entire div around the input and submit button, but then we come back to the problem of styling another element when one element is focused.

Is this even possible with CSS3 or would I have to resort to a javascript function? (Last resort.)

Kody
  • 752
  • 2
  • 11
  • 22

2 Answers2

2

If the structure in your actual code is the same as what you've posted in question, you can use + (adjacent) selector to select the submit button when there's focus on text input.

This is the selector you're looking for: #example > input[type="text"]:focus + input[type="submit"]

To read more about + selector, this answer to "What does the “+” (plus sign) CSS selector mean?" explains it in a short manner and even covers browser support.


Here is a snippet to show it in action. Doesn't look too pretty, but does the job :)

#example > input[type="text"]:focus + input[type="submit"] {
  background: gray;
}
<form id="example">
    <input type="text" name="search">
    <input type="submit" value="Search">
</form>
Community
  • 1
  • 1
Marko Gresak
  • 7,950
  • 5
  • 40
  • 46
  • Yes, this will work if there is nothing in between the two ``'s – Adam Buchanan Smith Aug 19 '16 at 23:32
  • @AdamBuchananSmith, I've started my answer with "If the structure in your actual code is the same as what you've posted in question". Not sure what more do I need to say to make it clear what's required for this to work. – Marko Gresak Aug 19 '16 at 23:35
  • Oh I hit a nerve? I upvoted your answer because it literally answers the question. Sorry for all the suffering I just caused you. – Adam Buchanan Smith Aug 19 '16 at 23:38
  • @Marko Grešak There is a div element surrounding the button. If I do something like: #example > input[type="text"]:focus + div input[type="submit"], would this work? – Kody Aug 20 '16 at 00:39
-1

Here is a way using JQuery, see fiddle https://jsfiddle.net/t33rdra6/2/

  $(document).ready(function() {

    $('input').blur(function() {
        $('input[type="submit"]').removeClass("focus")
      })
      .focus(function() {
        $('input[type="submit"]').addClass("focus");
      });
  });
Adam Buchanan Smith
  • 9,422
  • 5
  • 19
  • 39