简体   繁体   中英

<button type=“button”> used as form value on submit

I'm trying to figure the "best" method of having a button type=button show up on the form submit. These are not submit buttons, but they do fire some js for calculations but I also need their name and value to be posted.

I think I can also have a checkbox of the same name and jquery update this checked status, but that seems unprofessional and I would also have to hide the checkboxes.

Is there a elegant solution for this?

Using Twitter Bootstrap, jquery, Ruby on Rails.

The main goal of this approach is to have a few big buttons as checkboxes for easy use on a tablet etc.

You could use ajax to serve your purpose. In the view you just have a button with text box, enter some input and click on the button. IN Jquery onclick method is called and the value is passed as ajax and your calculations can be carried upon and the result is stored in the db(if required).

Your view code should be something like this

<input type="button" id="submitt">
<div id="myDiv"> </div>

Your jquery code should be like this

 var content = '';
$(document).ready(function() {  
 $('#submitt').click(function(){


// do some calculations and store it in a variable nm
        $.ajax({url:"demo/"+nm, success:function(result){         
           myFunction(result);
           $("#myDiv").html(content);  // To output the result           
       }});
        return false;
});
});

    function myFunction(result)
{
             content = '';
            for (var i = 0; i < result.length; i++) {
                content += result[i].name;
                content += '<br/>';
            }
}

In the routing file

match 'demo/:nm' => 'demo#newsy'

and finally in the controller file

def newsy
    @name = request["nm"]  
    new_emp = Client.new
    new_emp.name = @name
    new_emp.save
    @myys = Client.all
    render :json => @myys
end

IMHO there is nothing unprofessional in hiding inputs. And if you don't want to hide checkboxes, you can use type="hidden"

Working demo (jsfiddle)

<button type="button" data-name="myName" class="btn" data-toggle="btn-input" data-target="#myButtonState" value="myValue">Click me</button>
<input type="hidden" id="myButtonState" />
$('[data-toggle="btn-input"]').each(function() {
    var $this = $(this);
    var $input = $($this.data('target'));
    var name = $this.data('name');
    var active = false;                  // Maybe check button state instead
    $this.on('click',function() {
        active = !active;

        if(active) $input.attr('name', name).val($this.val());
        else       $input.removeAttr('name');

        $this.button('toggle');
    });
});

The removeAttr mimics the checkbox state (whether it's submitted or not).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM