4

I want to know How I can Convert Disable submit button from jQuery to alpine js?

The Code :

<form>
  <input type="text" class="input-field" placeholder="Enter you name *" value="" />
  <button type="submit" class="submit-btn">Submit</button>
</form>

$(document).ready(function(){
    $('.submit-btn').attr('disabled',true);
    $('.input-field').keyup(function(){
        if($(this).val().length !=0)
            $('.submit-btn').attr('disabled', false);            
        else
            $('.submit-btn').attr('disabled',true);
    })
});
jhon-jhones
  • 455
  • 1
  • 13
  • 27

2 Answers2

9

Using x-bind, or its shorter syntax, :

<script src="//cdnjs.cloudflare.com/ajax/libs/alpinejs/2.3.0/alpine.js"></script>

<form x-data="{ name: ''}">
  <input type="text" x-model="name" placeholder="Enter you name *" />
  <button type="submit" :disabled="!name.length">Submit</button>
</form>
blex
  • 24,941
  • 5
  • 39
  • 72
  • in my case instead of x-bind , i use : . if i use x-bind the first view only the button is not disabled whatever the first initialize value true or false. – Yogi Arif Widodo Nov 03 '21 at 03:07
2

is this accurate for what you want ?

<div x-data="{disableSubmit: true, inputText: null}">
   <input x-model="inputText" x-on:input="[(inputText.length != 0) ? disableSubmit = false : disableSubmit = true]">
   <button x-bind:disabled="disableSubmit">submit</button>
</div>

try this on jsfiddle

Yoga Altariz
  • 32
  • 1
  • 3