S
S
stefan_hansch2016-03-04 11:38:27
JavaScript
stefan_hansch, 2016-03-04 11:38:27

How to swap fields with jQuery?

When you click on the up or down button, the poll_row block should swap places with the previous or next one and change the value attribute of the hidden field to +1 or -1

There is the following function:

assets/javascripts/poll_items.js

$(function(){
  $(document).on('click', '.down_id', function() {
    $(this).siblings('.sequence').val(parseFloat( $(this).siblings('.sequence').val() ) + 1);
    $(this).parent().next().children('.sequence').val( $(this).parent().next().children('.sequence').val() - 1);
    $(this).closest('.poll_row').insertAfter($(this).closest('.poll_row').next());
  });

  $(document).on('click','.up_id', function() {
    $(this).siblings('.sequence').val(parseFloat( $(this).siblings('.sequence').val() ) -1);
      $(this).parent().prev().children('.sequence').val(parseFloat($(this).parent().prev().children('.sequence').val())+ 1);
    $(this).closest('.poll_row').insertBefore($(this).closest('.poll_row').prev());
  });


When the button is clicked, the value value changes. Blocks are swapped only if I press the button twice. I can not understand what is the reason that nothing happens on the first click.


What could be the reason for this?

polls/edit.html.haml

.................................................
.items-index
    = f.simple_fields_for :poll_items do |poll|
      = render 'poll_item_fields', f: poll
.................................................


polls/oll_item_fields.html.haml

.poll_row
  .poll_item
    = f.input :answer, input_html: { class: 'ctrlenter expanding' }, label: false, placeholder: 'Введите вариант ответа'
    = f.hidden_field :sequence, class: 'sequence'
    = button_tag 'вверх', type: 'button', class: 'up_id', value: 'вверх'
    = button_tag 'вниз', type: 'button', class: 'down_id', value: 'вниз'
    - if @poll.editable?(current_user)
      = link_to_remove_association "удалить", f, { wrapper_class: 'poll_item' }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilham Karimov, 2016-03-04
@Ilham

Can I see a demo of this?

A
Arthur, 2016-03-04
@astralo

I think if you enter regular html instead of haml, then your chances of getting an answer will increase.
It is not very correct to use haml jade and so on. transpiles on resources like this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question