9

I want to apply a CSS class to every textbox in my site:

        <div class="editor-label">
            <label for="FoodType">FoodType</label>
        </div>
        <div class="editor-field">
            <input id="HelpText" name="FoodType" type="text" value="" />
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>

And I thought, Hey! Easy. I'll add a jquery function to find them all in the masterpage.

<script type="text/javascript">
    $(document).ready(function(){
        $('input').addClass('textbox');
    }
</script>

Unfortunately this will also select the submit button. How can i only select input elements that have a text type attribute?

Alternativly is this possible using entirely CSS?

If both these methods are not possible, i guess i will just have to manually add the class to every textbox i make?

2 Answers 2

32

AFAIK it's:

$('input[type=text]').addClass('textbox');

And you can do similar in the CSS file, but that requires higher version of CSS / depending how broad you want to be with older browsers.

See attribute selectors in here. Note that:

"Browser support: The only browser that doesn’t support CSS3 attribute selectors is IE6. Both IE7 and IE8, Opera and Webkit- and Gecko-based browsers do. So using them in your style sheet is definitely safe."

Sign up to request clarification or add additional context in comments.

3 Comments

$('input[type=text]') will work in IE6 because jQuery will fall back to using its own selector engine rather than the browser's built-in support. input[type=text] { ... } in a CSS stylesheet, on the other hand, would fail in IE6.
@bobince the canonical solution would be parsing the HTML with a RegEx I guess
How would I do that in CSS or SCSS?
-1
<!DOCTYPE html>

<html>
<head>

<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>


<script type="text/javascript">
$(document).ready(function(){

$(".post_class").css({padding:"10px",background:"#333",color:"#fff"});

$("#post_button").css({padding:"10px",background:"#333", textAlign:"center",color:"#fff",cursor:"pointer"})

$("#post_button").click(function(){
var input = $("input[name='checkListItem']").val();

$(".post_class").append('<div class="item">' + input + '</div>');

});

});
</script>


</head>

<body>

<form name="checkListForm">

<input type="text" name="checkListItem"/>

</form>

<div id="post_button">Post</div>

<br/>

<div class="post_class"></div>

</body>

</html>

1 Comment

This doesn't answer the question at all so why is this posted here?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.