2

Basically i want the outer div to take all events, so the input and anything else in the div is not clickable:

<div id="div1">
    <div id="div2">
        <label>Input 1</label>
        <input type="text" id="input1" />
    </div>
</div>

$(document).ready(function() {
    $(document).on('click', '#input1', function(e){
        e.preventDefault();
    };
});

Here's the non-working example http://jsfiddle.net/KFWmk/3/

Any help appreciated :)

4 Answers4

9

In newer jQuery (1.6+):

$('div input').prop("readonly", true);

This sets the HTML readonly property to true for all inputs in a div.

Please note that using .attr() to set properties (attributes with boolean values of on or off) has been deprecated in jQuery.

Brandon
  • 16,382
  • 12
  • 55
  • 88
  • 1
    Actually appears to be even better, not sure how reliable this source is though: http://reference.sitepoint.com/html/input/readonly – qwerty Mar 05 '13 at 12:58
  • 1
    @qwerty That's correct, just tried it in IE6 and it works no problem – Brandon Mar 05 '13 at 12:58
  • Thanks that seems to work for input elements, i presume disabled is the best alternative to this for select elements – Matthew Lanham Mar 05 '13 at 13:12
2

First of all bacause you havn't included the jQuery library.
Second bacause you have a type-o.
Third because the the focus is emitted before the click event. (Prove)

If you want to make an input field not editable you can use:

$("input").prop("readonly", true);

or simply when you create the input field in html:

<input readonly type="number">

If you want to prevent focus on an input field you can use:

$("input").on("focus", function() {
    $(this).blur();
}); 
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
  • _"If you want to prevent focus"_ - Using `readonly` doesn't prevent focus, it just makes the field...well...readonly. That is, you can still tab to the field or select text with the mouse, and you can still copy the text to the clipboard - you just can't change it. – nnnnnn Mar 05 '13 at 13:11
0
$('div input').attr("readonly", "readonly");

you can make all input fields in the div as read only.

PSR
  • 39,804
  • 41
  • 111
  • 151
  • Using `.attr()` to set properties has been deprecated in jQuery, please look into using `.prop()` – Brandon Mar 05 '13 at 12:56
0

You can try like this

$(document).ready(function() {
    $('div input').prop("readonly", true);
});
GautamD31
  • 28,552
  • 10
  • 64
  • 85