0

I have the following code to check if an input field has the required attribute set on it.

computed: {        
    isRequired: function (input) {

        input = document.getElementsByTagName('input');

        for (var i = 0; i < input.length; i++) {
            return this.input.hasAttribute('required') ? 'test-class' : '';  
        }


    }
}

And the html template with code for the input component.

<div :class="isRequired" class="o-pf-required pull-left">*</div>
    <div class="col-md-6 col-lg-6" style="padding-right: 0px">

    <!-- 
          padding-right: 0px here cancels out padding on the bootstrap 
          col-lg-12 wrapper keeping the 15px padding of the outer div consistant. 
    -->

        <input :type="type" class="o-pf-input" :class="isCheckBox" :placeholder="placeholder" :name="placeholder" :required="isRequired ? true : false" :value = 'value' @input="value = $event.target.value">
        <label :for="placeholder"> {{ placeholder }} </label>
    </div>

What I want to achieve is to apply the test-class to the element where the o-pf-required class is to hide the asterisk but the browser gives me the following error:

enter image description here

A related issue on this: VueJS conditionally add an attribute for an element

6
  • this in vue computed and methods is always point to current vm instance.Not the input element during iteration. Commented Aug 24, 2017 at 10:17
  • Oops. You're right. I forget. Commented Aug 24, 2017 at 10:26
  • Hmm, I had an answer that wasn't exactly what you need. Can't you set the required attribute via Vue's data? This will make it a lot easier to check if the input is required. If not, try going with refs (vuejs.org/v2/api/#ref) perhaps Commented Aug 24, 2017 at 10:50
  • What I did was set required as a props value and bind it like this :required="" to the input element in the template. I also tried to set it in the data object but it kept saying that it is set as a prop and told me to use the prop value instead. I will have a look at refs. Thanks @CaptainCarl Commented Aug 24, 2017 at 11:08
  • 1
    If you set a :required prop you need something like :required="true/false". You don't have to set a value as a prop, just as a data attribute. (data () { isRequired: true;} and <input :required="isRequired" /> Commented Aug 24, 2017 at 11:41

0

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.