jonboy
jonboy

Reputation: 2749

Pass js variable to form action url

I'm not sure if this is possible, or if I am doing it the wrong way?

I have a form that when submitted, should send the user to a URL depending on the input.

e.g If the users inputs '2', the URL should be books/itemView?id=2

I have created a var = id, which takes the search input box data. Is it possible to add this variable to my current form action? Perhaps there is a more efficient way?

My current code is as follows;

<form id="search" action="<?php echo URL; ?>books/itemView?id=" method="post">
<input type="text" name="search" id="demo"/>
<input type="submit" value="Submit">
</form>

My JS

$(document).ready(function(){

var id = $('#search').val();

});

Quite new to JS so any help appreciated.

Upvotes: 1

Views: 11149

Answers (3)

andrusieczko
andrusieczko

Reputation: 2824

Hmm, you can try with that:

$(document).ready(function(){
  var $form = $('#search');
  var id = $form.val();
  var $search = $('#demo');
  var originalAction = $search.attr('action');
  $form.on('submit', function() {
    $search.attr('action', originalAction + id);
  });
});

Before submitting the form, jQuery's on('submit', handler) function executes the code in handler modifying the attribute action that you want.

originalAction variable stores the content of the action attribute that was partially generated in php, then you append your id dynamically created with js.

Upvotes: 1

Paulo Segundo
Paulo Segundo

Reputation: 448

JS should be

$('#search').on('submit', function() {
    var id = $('#demo').val();
    var formAction = $('#search').attr('action');
    $('#search').attr('action', formAction + id);
});

Upvotes: 4

brso05
brso05

Reputation: 13222

If they enter 2 in the search input then your id will be appended to your url like:

url?search=2

So maybe you want to change the name of your search input to id or add another input field.

<form id="search" action="<?php echo URL; ?>books/itemView" method="post">
<input type="text" name="id" id="demo"/>
<input type="submit" value="Submit">
</form>

That should be all you need no jquery or javascript necessary.

When you submit it should result in:

books/itemView?id=2(or whatever is in the search/id input when you click submit)

Upvotes: 1

Related Questions