javascript - Confirm box depending on input value -
i'm new javascript don't judge hard (any suggestions or comments highly appreciated).
i have form in rails app (haml file):
= simple_form_for(@book, remote: true) |f| .row .form-group = f.input :book_title, as: :string, label: "title of book" %br = f.input :pages_number, as: :string, label: "number of pages" %br .form-actions = f.button :submit, "create", class: "btn btn-success" = link_to t('buttons.cancel'), '#', onclick: "$.modal.close()", class: 'btn btn-warning pull-right'
the action in controller opens form:
def new @book = book.new end
the action in controller saves form:
def create end
what i'm trying check whether input number of pages bigger 10. i want create confirm box.
i trying save @pages_number = params[:pages_number]
in create
action, , use data: (@pages_number < 10 ? { confirm: "are sure?" } : nil)
in view, didn't work.
do need use javascript in case?
always remember ruby = server
; javascript = client
if evaluating against condition set server, code work.
however, since you're evaluating against dynamically created condition, you'll need use javascript determine whether value worth invoking confirm dialogue:
#app/assets/javascripts/application.js $(document).on("ajax:beforesend", "#form", function(event, xhr, settings) { var $el = $(this); var $pages = $el.find("input[name='page_numbers']"); if ($pages.val() > 10) { var response = confirm($el.data('confirm') || 'are sure?'); // not sure if pull rails confirm if (!response) { return; } } });
the above, although needs tweaking, should evaluate inputted value page_numbers
box. if user not confirm, return, preventing progress.
as you're using ajax
, use ajax:beforesend
hook interject before request sent ajax driver. if weren't using remote: true
, you'd want @ binding form.on("submit"
method.
update
after lengthy chat discussion, resolved following:
#app/assets/javascripts/application.js function validateform() { var x = $('.value').val(); if (x < 10) { var res = confirm("are sure?"); if (res == false) { return false; } } } #app/views/books/new.html.erb <%= form_for @book, onclick: "return validateform();", remote: true |f| %>
we used this reference.
Comments
Post a Comment