Search code examples
javascripthtmljquerythymeleaf

HTML+JS/jQuery: Is there a way to append the value of an element to the form action string?


I am new to JavaScript, HTML and jQuery. The backend object was sent to the frontend and a loop is displaying the objects in a table. I am using thymeleaf and Java to achieve this.

Once that is done I am having an update form for each object as a modal/popup which has its input fields populated with jQuery based on the fields that where populated by the loop on the list. You can see that in the code. I don't have access to the backend object in the modal so I need to access the data on the frontend.

I have successfully retrieved the id value of the object and successfully set the hidden input "thepostid" to that value. My dilemma is how do I append the value of this element after the update/ in the action field?

EDIT: I have to mention that I am aware that I can simply use the hidden input field and retrieve it in the backend, but I want to learn a new way of doing this.

<form class="forms-sample" id="formm" method="POST"
        enctype="multipart/form-data" action="/dashboard/showposts/update/"+ <-//HOW TO APPEND VALUE HERE?
          <input type="hidden" id="thepostid" name="thepostid">
     ////
function update(id) {

let _id=id.split("-").pop()
let rowid=`row-${_id}`;
let postid=`post-${_id}`;
let imageid=`image-${_id}`;

console.log(rowid);

let row=$("#"+rowid);
let postvalue=$("#"+postid).val();
let image=$("#"+imageid).val();

const title=row.find("td:eq(1)").text();
const tags=row.find("td:eq(4)").text();
const thepostid=row.find("td:eq(0)").text();

$("#title").val(title);
$("#tags").val(tags);
$("#content").val(postvalue);
$("#filename").val(image);
$("#thepostid").val(thepostid);

$("#mysimpleModal").css("display","block")
}

Solution

  • As Carlos1232 suggested in the comments, you use jQuery's attribute-getting/setting method: .attr(). This works because the form's action is an attribute.

    For instance, to add the string 'foo' to a form's action, you could do:

    // <form action="example.com/">
    const newPartToAdd = 'foo';
    const originalUrl = $('form').attr('action');
    $('form').attr('action', originalUrl + newPartToAdd);
    // <form action="example.com/foo">
    

    Now, when your form is submitted, it will pass the new data in that string as part of the URL. Presumably you'd want to use a real string, with data that you extracted from the page, but the principle is the same regardless.

    However, what you really might be looking for here is the fetch built-in browser method (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). Alternatively, to stick with jQuery, check out the ajax, get, post, etc. methods.

    These will let you make a request with any data, and you won't need to involve a form to do so.