Search code examples
jqueryhtmlruby-on-railsajaxcoffeescript

How do I fetch the contents entered in the Input field using Ajax?


I'm having an input field in the form where the users updates their Name on click of a button. This change in the input field should be captured by the Ajax and update it.

Html -

<p id="name"><%= @current_user.name %></p>

<button type="button" id="namebtn">&#xE254;</i> </button>

coffee Script -

$('form').on 'focusout', ->
    $elem = $(this)
    if !$elem.find(':focus').length
            $.ajax({
                type: "POST",
                url: "http://localhost:3000/profile/name_change",
                data: "{
                    'name': '"+$('#name').val()+"'}",
            })
        return

How do I capture the changed input from the input field?


Solution

  • You say you have an 'input field', yet #name is clearly a p element. You need to use text() to get its value in that case.

    Also note that your use of focusout on the form whilst checking the :focus element is rather odd. You could just use a standard click handler instead:

    $('#namebtn').on 'click', ->
      $.ajax({
        type: "POST",
        url: "http://localhost:3000/profile/name_change",
        data: { name: $('#name').text() }
      })
      return