Frage

I have a jquery code but is not working and seems that I need prototype code.

Here is the code: http://jsfiddle.net/qKG5F/1627/

<script type="text/javascript">
(function() {
$('form > input').keyup(function() {

    var empty = false;
    $('form > input').each(function() {
        if ($(this).val() == '') {
            empty = true;
        }
    });

    if (empty) {
        $('#search').attr('disabled', 'disabled');
    } else {
        $('#search').removeAttr('disabled');
    }
});
})()
</script>
<form>
FROM<br />
<input type="text"/><br />
TO<br />
<input type="text"/><br />     
<input type="submit" id="search" value="GO" disabled="disabled" />
</form> 

Please somebody can help me to convert this jquery to prototype code?

All kind of help will be accepted.

War es hilfreich?

Lösung

For sake of completeness I went ahead and converted your code to PrototypeJS. I optimized the code a bit (sorry can't help it) to exit when the first empty field is found.

<script type="text/javascript">
document.observe('dom:loaded',function(){
    $$('form > input').invoke('observe','keyup',function() {
        var empty = false;
        $$('form > input').each(function() {
            if (this.value == '') {
                empty = true;
                throw $break;
            }
        });
        $('search').writeAttribute('disabled',empty);
    });
});
</script>
<form>
FROM<br />
<input type="text"/><br />
TO<br />
<input type="text"/><br />     
<input type="submit" id="search" value="GO" disabled="disabled" />
</form> 

Andere Tipps

The issue is that your JavaScript is executing before the DOM elements load.

A very simple fix would be to wrap your function invocation within the default jQuery function.

<script type="text/javascript">
$(function() {
  $('form > input').keyup(function() {

      var empty = false;
      $('form > input').each(function() {
          if ($(this).val() == '') {
              empty = true;
          }
      });

      if (empty) {
          $('#search').attr('disabled', 'disabled');
      } else {
          $('#search').removeAttr('disabled');
      }
  });
});
</script>
<form>
FROM<br />
<input type="text"/><br />
TO<br />
<input type="text"/><br />     
<input type="submit" id="search" value="GO" disabled="disabled" />
</form> 

Passing a function to jQuery is the equivalent of calling $(document).ready(someFunctionHere). What this does is defer the execution of the function until the DOM has finished loading.

Alternatively, putting your script tag at the bottom of your HTML would also achieve the desired effect.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top