skip to Main Content

I’ve been having this problem where in I need to capitalize the text input being sent to ajax before saving it to the database. Basically I need to lowercase the text value and then capitalize the first letter before finally saving it to database.

Here’s my take so far:

 $('#button').click(function(event) {

         event.preventDefault();

         $.ajax({
           url: '/categories',
           method: 'post',
           data: {
             category: { name: $('#new-category').val().toLowerCase().css('text-transform', 'uppercase') }
           },
           success: function(category){
              // console.log(response);
              if(category.id != null){
                let newOption = $('<option/>')
                .attr('value', category.id)
                .attr('selected', true)
                .text(category.name)

                $('#category_select').append(newOption);
                $('#new-category').val('');
              }
           },
           error: function(xhr){
             let errors = xhr.responseJSON;
           }

         });
     });

As you can see on this part:

  category: { name: $('#new-category').val().toLowerCase().css('text-transform', 'uppercase') }
               }

This returns an error. How do I do this and jQuery and make sure what is being sent out has the first text in the category name got uppercase or simply capitalize?

2

Answers


  1. Referring to this

    stackoverflow

    $('#button').click(function(event) {
    
         event.preventDefault();
    
    
         $.ajax({
           url: '/categories',
           method: 'post',
           data: {
             category: { name: capitalizeFirstLetter($('#new-category').val()) }
           },
           success: function(category){
              // console.log(response);
              if(category.id != null){
                let newOption = $('<option/>')
                .attr('value', category.id)
                .attr('selected', true)
                .text(category.name)
    
                $('#category_select').append(newOption);
                $('#new-category').val('');
              }
           },
           error: function(xhr){
             let errors = xhr.responseJSON;
           }
    
         });
     });
    
    
    function capitalizeFirstLetter(string) {
         string  = string.toLowerCase();
        return string.charAt(0).toUpperCase() + string.slice(1);
    }
    

    enter image description here

    https://jsfiddle.net/uypmjh9q/

    Login or Signup to reply.
  2. you might want to use this on your input oninput=”this.value = this.value.toUpperCase()”

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search