2017-03-27 19 views
0

チェックボックスのラベルをクリックしてフォームを送信します。チェックボックスは表示されず、ラベルはボタンとしてスタイリングされます。これは私のコードです:チェックボックスのラベルをクリックしてデータを送信する方法

<%= form_tag(fetch_games_index_path, method: :get, id: 'games-filter-form', remote: true) do %> 
    <%= check_box_tag 'mobile[]', 'true', false, id: 'games-filter-checkbox', class: 'games-filter-checkbox' %> 
    <label for="games-filter-checkbox" id="game-mobile-0"></label> 
<% end %> 

とそれに対応するJS:

$('#game-mobile-0').click(function() { 
    $('#games-filter-form input[type="hidden"]').submit(); 
}); 

こうすることによって、私は初めてのラベルをクリックしたとき、それはtrueにあるチェックボックスを設定しますが、送信されたのparamsがあります空の。もう一度ラベルをクリックすると、チェックボックスはfalseに設定され、パラメータ:"mobile"=>["true"]に表示されます。私は次のコードを試しました:

$('#game-mobile-0').click(function() { 
    if($('#games-filter-checkbox').prop('checked', true)) { 
    $('#games-filter-form input[type="hidden"]').submit(); 
    } 
}); 

これをやって、スタイルの付いたアニメーションは動作しません。この問題を解決する方法は何ですか?先にありがとう。ここで

animated_button

答えて

0

このコードは助け:

$('#game-mobile-0').click(function() { 
    setTimeout(function() { 
    $('#games-filter-form input[type="hidden"]').submit(); 
    }, 300); 
}); 
0

あなたは条件付きで値を設定するのではなく、その値を参照します。

$('#game-mobile-0').click(function() { 
    if($('#games-filter-checkbox').prop('checked', true)) { 
    $('#games-filter-form input[type="hidden"]').submit(); 
    } 
}); 

http://api.jquery.com/prop/#prop-propertyName-value

$('#game-mobile-0').click(function() { 
    // cache a reference 
    var checkitem = $('#games-filter-checkbox'); 
    // set to the value it is NOT at present (check if not, un-check if checked) 
    checkitem.prop('checked', !checkitem[0].checked) 
    // if checked now, submit 
    if(checkitem[0].checked) { 
     // submit form with this id: 
     $('#games-filter-form').submit(); 
    } 
}); 
+0

をそれでも、問題が残っています。それはフォームを提出し、私のスタイルのラベルをアニメートしません。 –

+0

アニメーションは何ですか?フォームが送信されたら、ラベルのスタイルを別のものに変更しますか? –

+0

スタイリングラベルはフォームの送信とは関係ありません。送信が発生したときにスタイルを変更する場合は、jquery addclassまたはcssメソッドを使用する必要があります。 '$( '#game-mobile-0')。removeClass(" oldClass ")。addClass(" newClass ");' $( '#games-filter-form')の後にsubmit(); ' –

関連する問題