0

I have a form that its action was initially to refresh the page. but I need a button that will submit the data and change the form's action. I have tried using JavaScript below:

<form id="form1" name="form1" action="" method="post">

Button

<input type="button" class="submit" value="Save" onchange="submitForm()" />

JavaScript

function submitForm(){
    document.getElementById('form1').action = <?echo base_url().'index.php/folder/controller/controller_function/';?>;
    document.getElementById('form1').submit();
}

When I click the button, nothing happens. I have also tried using if/else statement in the form's action, but that too doesn't work:

<form id="form1" name="form1" action="<?if(isset($_POST['saveButton'])){echo base_url().'index.php/folder/controller/controller_function/';} else{echo "";}?>" method="post">
4
  • 3
    You should probably use onclick on the button. Commented Aug 27, 2013 at 3:40
  • change button onchange attribute to onclick Commented Aug 27, 2013 at 3:43
  • you can also take a look at the "formaction" attribute in html5 Commented Aug 27, 2013 at 4:05
  • omg,, of course, thanks alot everyone. i've changed my 'onchange' to 'onclick' and it worked perfectly. thanks. Commented Aug 27, 2013 at 6:09

2 Answers 2

3

Firstly, the value in your JavaScript should be quoted, as it is a string:

function submitForm(){
    document.getElementById('form1').action = '<?echo base_url().'index.php/folder/controller/controller_function/';?>';
    document.getElementById('form1').submit();
}

Secondly, you're triggering the function on the change event of a button, which probably won't work because buttons do not change. Try binding to the submit event instead, on the form itself:

<form id="form1" name="form1" action="" method="post" onsubmit='submitForm();'>

But I'd do it in the JavaScript, using an event listener:

document.getElementById('form1').addEventListener('submit', function(e) {
    e.preventDefault();
    this.action = '<?echo base_url().'index.php/folder/controller/controller_function/';?>';
    this.submit();
}, false);
Sign up to request clarification or add additional context in comments.

1 Comment

thank you. i've edited my code as you pointed, and it worked perfectly. thanks a lot.
1

Put quotes around the action as shown below:

  document.getElementById('form1').action = "<?echo base_url().'index.php/folder/controller/controller_function/';?>";

You also need onClick instead of onChange

Works fine for me with these 2 changes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.