Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    Regular Coder
    Join Date
    Nov 2009
    Posts
    200
    Thanks
    23
    Thanked 0 Times in 0 Posts

    Attribute Default Value

    Can you get an attribute default value so you don't have to repeat it in the following example:

    Code:
    <p title="foo" id="p">Hello, world!</p>
    <input type="text" id="i">
    <script>
        var p = document.getElementById('p'),
            i = document.getElementById('i');
        i.oninput = function () {
            p.title = this.value;
            if (this.value == 'bar') {
                p.title = 'foo';
            }
        };
    </script>
    DEMO

    Is there something like p.title = p.title.defaultValue as we use for text fields?

  • #2
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,398
    Thanks
    12
    Thanked 570 Times in 563 Posts
    Did you try
    Code:
    p.title = p.getAttribute('title');
    It should get the HTML title attribute (= the default value) rather than the title property

  • #3
    Regular Coder
    Join Date
    Nov 2009
    Posts
    200
    Thanks
    23
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by devnull69 View Post
    Did you try
    Code:
    p.title = p.getAttribute('title');
    I'm afraid it doesn't work.

  • #4
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,980
    Thanks
    56
    Thanked 557 Times in 554 Posts
    would a custom attribute work, or is that just going in circles?

    Code:
    <p title="foo" data-dflt="foo" id="p">Hello, world!</p>
    
    if (this.value == 'bar') {
            p.title = p.getAttribute("data-dflt");
        }

  • #5
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,901
    Thanks
    79
    Thanked 4,423 Times in 4,388 Posts
    I think that's likely what he is after. I'm not convinced that he wants the default value to be the same as the original value. But if indeed that's what he wants, then:
    Code:
    <p title="foo" id="p">Hello, world!</p>
    <input type="text" id="i">
    <script>
        var p = document.getElementById('p'),
            i = document.getElementById('i');
        p.setAttribute("defaultTitle",p.title);
        i.oninput = function () {
            p.title = this.value == 'bar' ? p.getAttribute("defaultTitle") : this.value;
        };
    </script>
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •